# Components
Source: https://docs.inco.org/architecture/components
## Smart Contract Library
The Smart Contract Library extends the EVM with encrypted data types and operations. It is deployed on the host blockchain and provides:
* Encrypted data types (`ebool`, `eaddress`, `euint256`)
* Arithmetic operations (`e.add`, `e.sub`, `e.mul`, `e.div`, etc.)
* Comparison operations (`e.eq`, `e.le`, `e.gt`, etc.)
* Conditional operations (`e.select`)
* Access Control (`e.allow`)
This library allows developers to write smart contracts that handle encrypted data without modifying the underlying blockchain.
## Confidential Compute Server
The Confidential Compute Server runs inside a Trusted Execution Environment (TEE) and securely handles all confidential operations in the system. It provides a unified service for encrypted computation and decryption, ensuring privacy and integrity for sensitive data and operations.
Key responsibilities:
* Executes confidential computations and decryption requests within a secure enclave
* Processes encrypted operations triggered by blockchain events
* Validates access control before performing decryption
* Monitors the blockchain for requests and returns results directly, without requiring callback transactions
All results and attestations are verified on-chain to guarantee trust and integrity. The Confidential Compute Server streamlines the architecture, providing robust security and reliability for confidential blockchain applications.
## Client-side JavaScript Library
The JavaScript Library provides client-side functionality for interacting with the host chain and Inco:
* Encrypts user inputs using the network's public key
* Handles ephemeral key and EIP-712 signature generation for decryption requests
* Decrypts results locally for the user
# Decryption mechanisms
Source: https://docs.inco.org/architecture/decryption-mechanisms
Inco provides three types of decryption mechanisms:
* Attested Decrypt for obtaining cryptographic proofs of decryption that can be submitted on-chain
* Attested Compute for performing computations on encrypted data off-chain with attestation
* Attested Reveal for decrypting data that has been made publicly accessible
## Attested Decrypt
Used when an authorized user needs a cryptographic proof of decryption that can be selectively revealed on-chain:
1. User requests decryption attestation offchain (via wallet signature or session key)
2. Client sends request with proof of authorization to decryption network
3. The decryption network verifies ACL permissions
4. Each decryption network node decrypts the value and creates a signed attestation
5. User receives the decryption attestation containing the plaintext and signatures
6. User can submit the attestation to a smart contract for on-chain verification and use
```mermaid theme={null}
sequenceDiagram
participant User
participant ACL Contract
participant Inco Network
participant Contract
User->>User: Sign authorization (wallet/voucher)
User->>Inco Network: Request decryption attestation
Inco Network->>ACL Contract: Query ACL
ACL Contract->>Inco Network: Return permissions
Inco Network->>Inco Network: If allowed:
Inco Network->>Inco Network: - Decrypt data
Inco Network->>Inco Network: - Create signed attestation
Inco Network->>User: Return decryption attestation
User->>Contract: Submit attestation for verification
Contract->>Contract: Verify signatures
Contract->>Contract: Use decrypted value
```
## Attested Compute
Used when you need to perform computations on encrypted data completely off-chain and get a decryption attestation:
1. User requests computation attestation offchain (via wallet signature or session key)
2. Client sends request with proof of authorization and computation operation to decryption network
3. The decryption network verifies ACL permissions
4. Each decryption network node performs the computation on the encrypted data and creates a signed attestation
5. User receives the computation attestation containing the result and signatures
6. User can submit the attestation to a smart contract for on-chain verification and use
```mermaid theme={null}
sequenceDiagram
participant User
participant ACL Contract
participant Inco Network
participant Contract
User->>User: Sign authorization (wallet/voucher)
User->>Inco Network: Request computation attestation
Inco Network->>ACL Contract: Query ACL
ACL Contract->>Inco Network: Return permissions
Inco Network->>Inco Network: If allowed:
Inco Network->>Inco Network: - Perform computation on encrypted data
Inco Network->>Inco Network: - Create signed attestation
Inco Network->>User: Return computation attestation
User->>Contract: Submit attestation for verification
Contract->>Contract: Verify signatures
Contract->>Contract: Use computation result
```
## Attested Reveal
Used when data has been made publicly accessible and anyone can request decryption attestation:
1. Data is made public using e.reveal() on-chain
2. Anyone can request decryption attestation offchain
3. The decryption network verifies the data has been revealed
4. Each decryption network node decrypts the value and creates a signed attestation
5. Requester receives the decryption attestation containing the plaintext and signatures
6. Anyone can submit the attestation to a smart contract for on-chain verification and use
```mermaid theme={null}
sequenceDiagram
participant User
participant Contract
participant Inco Network
Contract->>Contract: e.reveal(handle)
User->>Inco Network: Request decryption attestation
Inco Network->>Contract: Verify data is revealed
Contract->>Inco Network: Confirm revelation
Inco Network->>Inco Network: - Decrypt data
Inco Network->>Inco Network: - Create signed attestation
Inco Network->>User: Return decryption attestation
User->>Contract: Submit attestation for verification
Contract->>Contract: Verify signatures
Contract->>Contract: Use decrypted value
```
# Overview
Source: https://docs.inco.org/architecture/overview
Inco is a confidentiality layer for blockchains that enables privacy-preserving smart contracts without modifying the underlying blockchain. Unlike monolithic privacy solutions, Inco follows a modular approach similar to how SSL/TLS provides security for internet protocols.
> Whitepaper coming soon!
## High-level Components
Inco's architecture consists of three main components that work together to provide confidential computing capabilities:
1. Smart Contract Library
2. Confidential Compute Server
3. Client-side JavaScript Library
These components work together to provide a seamless experience for developers building privacy-preserving applications on blockchain. The system handles encrypted data types, performs confidential computations, and manages secure decryption processes while maintaining compatibility with existing EVM blockchains.
# Build with AI
Source: https://docs.inco.org/build-with-ai
Use the Inco agent skill to build confidential smart contracts, dApps, and games with your AI coding assistant.
## Overview
The **Inco agent skill** teaches your AI coding assistant how to build confidential applications on Inco Lightning, covering encrypted types, programmable access control, and attestation across the `@inco/lightning` Solidity library and the `@inco/lightning-js` SDK.
It works in **Claude Code, Codex, Cursor, and 70+ agents**, and brings *game-design sense* to your workflow, helping you decide what must stay private, which Inco feature to reach for, and how to wire it together end to end.
## Install
Install with the [Vercel `skills`](https://github.com/vercel-labs/skills) CLI, which works with Claude Code, Codex, Cursor, Cline, and 70+ more:
```bash theme={null}
npx skills add Inco-fhevm/skills
```
To install for a specific agent, add the `-a` flag, for example `npx skills add Inco-fhevm/skills -a codex`.
Install as a native plugin, which gives you the namespaced `/inco:lightning` command and the `inco` umbrella for future skills:
```bash theme={null}
/plugin marketplace add Inco-fhevm/skills
/plugin install inco@inco
```
[Download the skill (zip)](https://github.com/Inco-fhevm/skills/raw/main/assets/inco-lightning.zip), unzip it, and copy the skill folder into your agent's skills directory:
```bash theme={null}
mkdir -p ~/.claude/skills
cp -R lightning ~/.claude/skills/lightning
```
## Use the skill
Invoke **`/lightning`** (or **`/inco:lightning`** if you installed the Claude Code plugin), or just describe what you want, and it activates on its own when your request involves confidential or Inco work:
```text theme={null}
"build a confidential sealed-bid auction on Inco"
"what should be private in my on-chain poker game?"
"add a hidden-roles mafia mechanic to my confidential game"
```
Start a fresh project with `npx create-inco-app`, or ask the skill to scaffold the Inco starter for you.
## What it does
* **Decides what to hide.** Answer two questions (*what's secret, and when does it reveal?*), and it routes you to the right pattern.
* **Knows the genres.** A catalog of 8 confidential-game archetypes: encrypted board, fog-of-war (Battleship), hidden hand (poker), hidden roles (mafia), sealed-bid auction, simultaneous-move (RPS), provably-fair casino, and word/code guessing.
* **Picks the settlement model.** On-chain attestation (for wagers) vs. private decrypt plus client-side (for single-player), with an honest line on when each is safe to use.
* **Writes the contract *and* the frontend.** The encrypt → transact → reveal/decrypt → render loop, fee handling, and attestation verification.
## What's inside
The `@inco/lightning` Solidity library (encrypted types, `e.allow`, attestation) and the `@inco/lightning-js` SDK and Foundry/Hardhat setup with a local covalidator.
The decision tree, archetype catalog, cross-cutting patterns (confidential randomness, equality-match, encrypted packing), the two settlement models, and the frontend loop.
Full example contracts to learn from: a wager game with on-chain settlement, a single-player game with client-side reveal, and a confidential ERC-20 token.
## Inco MCP
The **Inco MCP** exposes the Inco documentation to MCP-compatible clients over [Model Context Protocol](https://modelcontextprotocol.io). Instead of relying on pre-existing (and often out-of-date) knowledge of Inco, the model looks up the real patterns, types, and function signatures from the latest documentation as it works — so you get code that is consistent with the actual framework version you are using rather than code that just "sounds right".
### Install
After creating your project directory, create a `.cursor` folder. Within that folder, create a `mcp.json` file and enter the following:
```json theme={null}
{
"mcpServers": {
"Inco-mcp": {
"url": "https://docs.inco.org/mcp"
}
}
}
```
Add the Inco MCP server from your CLI:
```bash theme={null}
claude mcp add inco-mcp --transport http https://docs.inco.org/mcp
```
You can verify it's configured by running:
```bash theme={null}
claude mcp list
```
## Next steps
Browse the skill source, worked contracts, and full install options.
Set up the Inco toolchain and run your first confidential contract.
# Balances & token resolution
Source: https://docs.inco.org/ctoken/balances
Read public and confidential balances without losing precision.
## Public and confidential balances
| Method | Arguments | Result | Notes |
| -------------------- | ----------------------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `publicBalanceExact` | `{ token }` | `ExactBalance` | Public ERC-20 balance of wallet owner; no signature. |
| `publicBalanceOf` | `{ token }` | `number` | Display compatibility; may lose precision. |
| `publicBalances` | `{ tokens: Address[] }` | `Record
` | Batched public balances; deduplicates token addresses; any failed row rejects. |
| `balanceExact` | `{ token }` | `ExactBalance` | Confidential balance; may request a session signature. |
| `balanceOf` | `{ token }` | `number` | Display compatibility; failed/pending reads throw. |
| `balances` | `{ tokens }` | `Record` | Batch confidential values; any failed/pending row rejects. |
| `balancesSettled` | `{ tokens }` | `Record` | Per-token read errors and transient pending states; global session/authorization failures can still reject the whole call. |
| `preflightHandles` | `{ tokens }` | `TokenHandle[]` | Read metadata, wrapper and balance handles without decrypting or signing. Preserve input order. |
All methods return promises. Empty batches return empty results; record keys preserve caller casing.
```ts theme={null}
type ExactBalance = {
raw: bigint;
formatted: string;
decimals: number;
};
type BalanceResult = {
value: number | null; // display only
raw: bigint | null;
formatted: string | null;
decimals: number | null;
pending: boolean;
error?: CTokenError;
};
type TokenHandle = {
token: Address; // underlying ERC-20
cToken: Address | null;
handle: Hex | null;
decimals: number;
error?: CTokenError;
};
```
Treat failed or pending reads as unavailable, never zero. Ignore placeholder metadata on `TokenHandle` rows with `error`.
## Exact Max
```ts theme={null}
const balance = await ctoken.publicBalanceExact({ token: USDC });
if (balance.raw > 0n) {
await ctoken.deposit({ token: USDC, amount: balance.raw });
}
const rows = await ctoken.balancesSettled({ tokens: [USDC, USDT] });
for (const [token, row] of Object.entries(rows)) {
if (row.error) console.log(token, row.error.message);
else if (row.pending) console.log(token, "Processing ciphertext");
else console.log(token, row.formatted);
}
```
Use exact `raw` or `formatted` values for writes. Converting a display number back to a string can lose precision or produce unsupported exponent notation.
## Token resolution
| Method | Arguments | Result | Meaning |
| ---------------- | ------------ | -------------------------- | -------------------------------------------------------------- |
| `wrapperOf` | `{ token }` | `Promise` | Registered cToken address; null if absent. |
| `confidentialOf` | `{ token }` | `Promise` | Registered address, otherwise deterministic predicted address. |
| `underlyingOf` | `{ cToken }` | `Promise` | Underlying ERC-20 of a deployed cToken. |
Use `wrapperOf` to check registration and [ensureWrapper](/ctoken/transactions) to deploy. A predicted address does not establish deployment.
## Shared helpers and types
| Export | Signature / purpose |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `toBaseUnits` | `(amount: Amount, decimals: number): bigint`; validates positive uint256 amounts. |
| `fromBaseUnits` | `(value: bigint, decimals: number): number`; display conversion only. |
| `sanitizeAmountInput` | `(raw: string): string`; currently preserves text exactly so signs/exponents cannot silently change intent. |
| `isRealHandle` | Nonzero 32-byte hex check. |
| `getTokenMeta` | `(network, erc20): TokenMeta or undefined`; built-in symbol/name/icon/decimals. |
| `enrichToken` | `(network, token): TokenConfig`; fills missing metadata from the registry. |
| `DEFAULT_TOKEN_META` | Metadata lookup keyed by network and lowercase ERC-20 address. |
| `Address`, `Hex` | Template string types starting with `0x`; not a substitute for runtime validation. |
| `Amount` | Decimal string or bigint base units. |
| `NetworkName` | `base` or `baseSepolia`. |
| `DepositStep` | `creating`, `approving`, `wrapping`. |
| `TokenConfig` | Required `erc20`, `symbol`; optional `name`, `decimals`, `icon`. Tokens appear in array order; there is no numeric priority. |
| `TokenMeta` | Optional `symbol`, `name`, `icon`, `decimals`. |
Amounts must be positive uint256 values: no signs, whitespace, exponents, or excess nonzero fractional digits. Trailing fractional zeros are accepted. Decimals: integer 0–255; amount strings: at most 335 characters.
# Browser & raw JavaScript
Source: https://docs.inco.org/ctoken/browser
Use the core SDK with an injected wallet or a caller-owned wallet client.
## Create a wallet-backed client
Call this from a connect action using your injected EIP-1193 provider:
```ts theme={null}
import { createPublicClient, createWalletClient, custom, http } from "viem";
import { baseSepolia } from "viem/chains";
import { CTokenClient } from "@inco/ctoken";
// readRpcUrl is your application's configured read endpoint (or HTTP proxy).
const publicClient = createPublicClient({
chain: baseSepolia,
transport: http(readRpcUrl),
});
// ethereum is your injected EIP-1193 provider.
const connection = createWalletClient({
chain: baseSepolia,
transport: custom(ethereum),
});
const [account] = await connection.requestAddresses();
if (!account) throw new Error("Connect a wallet first.");
const walletClient = createWalletClient({
account,
chain: baseSepolia,
transport: custom(ethereum),
});
const ctoken = new CTokenClient({
network: "baseSepolia",
publicClient,
walletClient,
});
```
Switch the wallet to the required chain before writing. Recreate the client on account/network changes; React handles this automatically.
## Read without a wallet
```ts theme={null}
const ctoken = new CTokenClient({ network: "baseSepolia", publicClient, indexer: true });
const token = "0x036CbD53842c5426634e7929541eC2318f3dCF7e";
const owner = "0x0000000000000000000000000000000000000001";
const wrapper = await ctoken.wrapperOf({ token });
const prices = await ctoken.prices([token]);
const assets = await ctoken.assets({ address: owner });
const history = await ctoken.history({ address: owner, page: 1, limit: 10 });
```
Indexer reads accept an explicit address. Balance methods use the connected owner; use viem `balanceOf(owner)` for another public address.
# Configuration & networks
Source: https://docs.inco.org/ctoken/configuration
Required read clients, wallet clients, deployment defaults, and optional indexing.
## Supply the network and your read client
```tsx theme={null}
{children}
```
Supply a viem `publicClient` for the selected chain. Deployments and USDC are preconfigured; indexing defaults off. React uses your `walletClient` prop or the surrounding wagmi connection.
| Setting | Base Sepolia | Base |
| ---------------------------- | -------------------------------------------- | -------------------------------------------- |
| `network` | `baseSepolia` | `base` |
| Chain ID | 84532 | 8453 |
| Factory | `0x6f9a0ECD77C3Dade8Dc14a507cAbABFD746575f8` | Same address, on Base |
| Vault | `0x35A38eFec618cD1924CBf4FB84bE187323Fa7E55` | Same address, on Base |
| Session verifier | `0x8D762303c41F822D3f38f8CE0f0fD1855d602c2A` | Same address, on Base |
| Default USDC | `0x036CbD53842c5426634e7929541eC2318f3dCF7e` | `0x833589fcd6edb6e08f4c7c32d4f71b54bda02913` |
| Hosted indexer, after opt-in | `https://api.ctoken.testnet.inco.org/api` | `https://api.ctoken.inco.org/api` |
| Explorer | `https://sepolia.basescan.org` | `https://basescan.org` |
Use the matching HTTPS indexer URL, including `/api`. Only price responses carry a chain ID; history and assets rely on your URL selecting the correct chain.
## All client options
`CTokenClientOptions` applies in both Node and browsers.
| Option | Type | Default / behavior |
| ------------------- | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `network` | `NetworkName` | Required: `base` or `baseSepolia`. |
| `walletClient` | viem `WalletClient` | Optional for public metadata; required for wallet balance reads, signatures, and writes. Account belongs on this client. |
| `contracts` | `ContractsOverride` | Optional `{ wrapperFactory?, vault? }`; each missing field retains its network default. |
| `sessionVerifier` | `Address` | Network verifier above. Override for your deployment. |
| `publicClient` | viem `PublicClient` | Required. SDK contract reads, multicalls, explicit unwrap gas estimation, and receipt polling use this client. Must declare the expected chain. |
| `indexer` | boolean or `IndexerOptions` | Omitted/false: off. true or `{}`: hosted default. `{ url, timeoutMs? }`: custom service. Include `/api` in the URL if your ingress requires it. |
| `indexer.timeoutMs` | positive integer | 15000; maximum 120000. Total deadline per indexer HTTP request, including retries and body parsing. |
| `incoRpcUrls` | HTTP(S) string array | Lightning extracts HTTP URLs from the public transport, including fallback transports. Required explicitly when none can be extracted. |
| `confirmations` | positive integer | 5 for final wrap/send/unwrap receipts. Approval and wrapper creation wait for 1 inclusion. |
| `sessionTtlHours` | positive finite number | 4 hours. |
Configure your paid read endpoint in `publicClient`; keep server credentials behind an application proxy. The wallet signs and submits transactions and may use its transport for transaction preparation.
Pass an application-owned wallet client. Raw `privateKey` and standalone `account` options reject with `INVALID_CONFIG`.
## Optional React overrides
```tsx theme={null}
{children}
```
Override only what you need. `tokens={[]}` disables built-in tokens. Changed contract addresses appear in the widget’s **Custom contracts** panel with explorer links; RPC/indexer URLs stay out of that panel.
# Build a compatible indexer
Source: https://docs.inco.org/ctoken/custom-indexer
The three endpoints, response schemas, pagination, and CORS your service needs.
OpenAPI 3.0 for assets, wallet transactions, and prices.
Implement these **three GET routes** relative to `indexer.url`. Additional [hosted endpoints](/ctoken/indexer-api) are optional.
| Route | Query parameters | Successful JSON body |
| --------------------------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| `/wallets/{address}/assets` | None | Bare array of Asset records, including `[]` for no holdings. |
| `/wallets/{address}/transactions` | `page` defaults 1; `limit` defaults 10, range 1–100 | TxPage object with `items`, `total`, `page`, `pages`, `limit`. |
| `/prices` | Optional `tokens`: comma-separated underlying ERC-20 addresses, at most 200 | Prices object for the client's chain. Omitted tokens requests your available priced set. |
The SDK appends paths to your base URL and lowercases addresses. Each URL must serve one chain: `chainId` 84532 for Base Sepolia or 8453 for Base. No chain query parameter is sent.
Return HTTP 200 JSON in the shapes below, without a `{ data: ... }` envelope. Unknown wallets return empty results. Use 400 for invalid requests, 429 for rate limits, and 503 for temporary failures. Allow your app’s origin through CORS for GET/OPTIONS.
Custom headers/fetch are unsupported. For authenticated backends, use a same-origin proxy that supplies server credentials.
Asset response example:
```json theme={null}
[
{
"address": "0x3333333333333333333333333333333333333333",
"base_erc20": "0x036cbd53842c5426634e7929541ec2318f3dcf7e",
"name": "Confidential USDC",
"symbol": "cUSDC",
"decimals": 6,
"balance_handle": null,
"handle_block": null,
"last_activity_block": "123456"
}
]
```
Transaction response example (one public wrap):
```json theme={null}
{
"items": [
{
"type": "flow",
"token": "0x3333333333333333333333333333333333333333",
"symbol": "cUSDC",
"decimals": 6,
"kind": "wrap",
"from_addr": "0x1111111111111111111111111111111111111111",
"to_addr": "0x1111111111111111111111111111111111111111",
"handle": null,
"amount": "1000000",
"block_number": "123456",
"block_time": "1788825600",
"log_index": 2,
"tx_hash": "0x4444444444444444444444444444444444444444444444444444444444444444"
}
],
"total": 1,
"page": 1,
"pages": 1,
"limit": 10
}
```
Confidential transfers use `type: "transfer"`, `kind: "transfer"`, a 32-byte `handle`, sender/recipient addresses, and `amount: null`. Public `flow` rows use `wrap`/`unwrap`, base-unit amount strings, and `handle: null`. Exclude zero-address confidential mint/burn legs and public `burn` rows. Sort by descending block/log index, count after filtering, and return `pages = Math.ceil(total / limit)`.
Price response example:
```json theme={null}
{
"chainId": 84532,
"ttl": 60,
"count": 1,
"prices": {
"0x036cbd53842c5426634e7929541ec2318f3dcf7e": {
"usd": 1,
"confidence": null,
"source": "your-price-source",
"updated_at": 1788825600,
"stale": false
}
}
}
```
Empty transactions: `{ "items": [], "total": 0, "page": 1, "pages": 0, "limit": 10 }`. Empty assets: `[]`. Empty prices: `{ "chainId": 84532, "ttl": 60, "count": 0, "prices": {} }`. Keep missing quotes absent from `prices`; zero is a real quote. `count` should equal the number of returned entries.
Follow the OpenAPI field types and nullability. Only Tx `block_time` and `log_index` may be omitted. Use 20-byte hex addresses, 32-byte hashes/handles, decimals 0–255, and decimal strings for amounts, blocks, and transaction timestamps. Return native JSON numbers for pagination and price values. Extra keys are ignored.
Validate all three SDK calls against your service, including empty results, pagination, missing quotes, 429 retries, aborts, malformed payloads, and chain mismatch.
## HTTP failure policy
Network errors, 429, and 5xx receive up to three attempts. Other 4xx and invalid payloads fail immediately. `Retry-After` waits are capped at five seconds within the total timeout. Aborts preserve the caller’s reason; timeouts raise `INDEXER_UNAVAILABLE`.
# Errors & recovery
Source: https://docs.inco.org/ctoken/errors
Handle wallet declines, unavailable ciphertexts, quorum failures, and HTTP errors.
## Error reference
```ts theme={null}
import { CTokenError, humanizeError, isUserRejection } from "@inco/ctoken";
try {
await ctoken.deposit({ token: USDC, amount: "1" });
} catch (error) {
if (isUserRejection(error)) return;
if (error instanceof CTokenError) console.log(error.code);
console.error(humanizeError(error));
}
```
| Code | Meaning / recovery |
| -------------------------- | ----------------------------------------------------------------------------------- |
| `WALLET_REQUIRED` | Supply/connect a wallet client. |
| `NOT_CONNECTED` | The supplied wallet has no selected account. |
| `UNSUPPORTED_NETWORK` | Use a supported NetworkName. |
| `WRONG_NETWORK` | Wallet/public-client/source chain mismatch; switch or configure the matching chain. |
| `INVALID_CONFIG` | Invalid URL/TTL or removed raw signer input, among other configuration failures. |
| `INVALID_ARGUMENT` | Invalid limits, pagination, handle shape, or option bounds. |
| `INVALID_ADDRESS` | Malformed address or invalid recipient. |
| `INVALID_AMOUNT` | Unsupported amount syntax, precision, zero/negative value, or overflow. |
| `WRAPPER_NOT_FOUND` | No registered wrapper/configuration where a deployed wrapper is required. |
| `READ_FAILED` | Batched metadata/balance/scope read failed. |
| `BALANCE_PENDING` | Numeric/exact balance API cannot produce a settled plaintext yet. |
| `TOKENS_REQUIRED` | Scoped reveal needs resolvable cToken scope. |
| `SESSION_FAILED` | Session creation/adoption state failed or changed during signing. |
| `DECRYPT_FAILED` | Pending batch could not settle, or invalid plaintext results. |
| `INDEXER_NOT_CONFIGURED` | Configure an indexer for the selected network or enable it. |
| `INDEXER_UNAVAILABLE` | HTTP failure, retry exhaustion, or timeout. |
| `INDEXER_INVALID_RESPONSE` | JSON/schema validation failed. |
| `TX_REVERTED` | Confirmed receipt reverted. |
| `TX_CANCELLED` | Original transaction was cancelled. |
| `TX_REPLACED` | Original transaction was replaced with a different operation. |
`CTokenErrorCode` contains these codes. Wallet/RPC errors may propagate directly; retain their causes for diagnostics. `humanizeError(null/undefined)` returns null. Never automatically retry a declined signature.
## Confidential-network failures
`humanizeError` converts threshold/quorum and failed KMS-client errors into: **The confidential network couldn’t complete the request. Please try again shortly.**
Original errors remain available for diagnostics. Wallet declines, timeouts, and rate limits also receive concise messages.
Widgets offer explicit balance retries and keep failed balances unavailable. Persistent failures need investigation of the original cause; do not automatically resubmit transactions.
# React hooks
Source: https://docs.inco.org/ctoken/hooks
Read balances, submit transactions, and switch networks.
## Read hooks
Query hooks return React Query results (`data`, `error`, `isFetching`, `isError`, `refetch`). Use `isFetching` for network spinners; disabled queries can be pending without fetching.
| Hook | Arguments | Data | Auto-enabled? |
| ---------------------------------------- | --------------------------------------------- | -------------------------------- | ----------------------------------------- |
| `useCToken()` | None | `CTokenClient` | Context access; throws outside provider. |
| `useTokens()` | None | `TokenConfig[]` | Context access. |
| `useResolvedTokens()` | Optional token list and single-token shortcut | Enriched `TokenConfig[]` | Context access, no network. |
| `usePublicBalance(token, options?)` | `{ enabled? }` | `number` | Yes when wallet owner exists. |
| `usePublicBalanceExact(token, options?)` | `{ enabled? }` | `ExactBalance` | Yes when wallet owner exists. |
| `usePublicBalances(tokens, options?)` | `{ enabled? }` | `Record` | Yes with owner and nonempty list. |
| `useBalance(token, options?)` | `{ enabled? }` | `number` | No; enable or refetch intentionally. |
| `useBalanceExact(token, options?)` | `{ enabled? }` | `ExactBalance` | No; enable or refetch intentionally. |
| `useBalances(tokens, options?)` | `{ enabled? }` | `Record` | No. |
| `useBalancesSettled(tokens, options?)` | `{ enabled? }` | `Record` | No. |
| `useHistory(args?, options?)` | `HistoryArgs`, `ReadOptions` | `TxPage` | No; needs an explicit or connected owner. |
| `useAssets(args?, options?)` | `AssetsArgs`, `ReadOptions` | `Asset[]` | No; needs an explicit or connected owner. |
Confidential queries disable automatic retry and focus/reconnect refetching; stale time is 15 seconds. Public queries inherit host policies. History/assets retry through the core HTTP layer.
`ReadOptions` applies to history/assets: `enabled?`, `refetchInterval?` (ms), `keepPreviousData?` (same-owner page transitions). Hooks supply React Query’s cancellation signal.
```tsx theme={null}
function BalanceAndActivity({ token }: { token: Address }) {
const [revealed, setRevealed] = useState(false);
const balance = useBalanceExact(token, { enabled: revealed });
const history = useHistory({ limit: 10 }, { enabled: true });
return (
);
}
```
Import the referenced hooks, types, and helpers; render under [React providers](/ctoken/react).
## Mutation hooks
| Hook | `mutate` / `mutateAsync` input | Success data |
| ------------------------------- | ------------------------------ | -------------------------- |
| `useDeposit(options?)` | `DepositArgs` | `{ hash, amount: bigint }` |
| `useApprove(options?)` | `ApproveArgs` | `{ hash }` |
| `useConfidentialSend(options?)` | `SendArgs` | `{ hash }` |
| `useWithdraw(options?)` | `WithdrawArgs` | `{ hash, amount: bigint }` |
| `useDecrypt()` | `DecryptArgs` | `number` |
`WriteOptions`: `onSuccess(data, variables)?`, `onError(error, variables)?`. Transaction hooks invalidate client queries on success. `useDecrypt()` supports per-call callbacks only. Disable automatic retries for signing mutations in your QueryClient.
```tsx theme={null}
const deposit = useDeposit({
onSuccess: ({ hash }) => console.log("Confirmed:", hash),
onError: (error) => console.error(humanizeError(error)),
});
```
## Network guard
```tsx theme={null}
const guard = useChainGuard();
if (guard.wrongNetwork) {
return (
);
}
```
`ChainGuard` exposes `wrongNetwork`, `chainId`, `chainName`, `switching`, and `switchNetwork()`. Switching does not submit a transaction.
# HTTP endpoint reference
Source: https://docs.inco.org/ctoken/indexer-api
Public REST routes for tokens, wallets, activity, consent, and pricing.
## Base URLs and conventions
| Network | Base URL |
| ------------ | ----------------------------------------- |
| Base | `https://api.ctoken.inco.org/api` |
| Base Sepolia | `https://api.ctoken.testnet.inco.org/api` |
Routes are relative to these URLs. GET requires no signature; POST consent does. Amounts/blocks are decimal strings. Token paths take cToken addresses except `/icon`, which takes the underlying asset.
Pagination: `page=1`, `limit=10`, maximum 100. Send positive integers.
```bash theme={null}
API=https://api.ctoken.testnet.inco.org/api
OWNER=0x0000000000000000000000000000000000000001
USDC=0x036CbD53842c5426634e7929541eC2318f3dCF7e
curl -sS "$API/factory"
curl -sS "$API/wallets/$OWNER/assets"
curl -sS "$API/wallets/$OWNER/transactions?page=1&limit=10"
curl -sS "$API/prices?tokens=$USDC"
```
## GET /tokens
Lists all indexed wrappers, newest created first. No pagination parameters. Returns `TokenRow[]`:
```ts theme={null}
type TokenRow = {
address: string; // cToken
base_erc20: string;
name: string;
symbol: string;
decimals: number;
created_blk: string | null;
};
```
Missing metadata defaults to empty name/symbol and 18 decimals. Read on-chain decimals for transaction precision. No SDK `tokens()` method.
## GET /tokens/:address
Returns `TokenRow` or HTTP 200 JSON `null` if unindexed. A missing record does not prove non-deployment.
## GET /tokens/:address/flows
Public flow feed for a cToken. Query `page`, `limit`. Returns the common page envelope with items containing `kind`, `account`, `amount`, `success_handle`, `block_number`, `block_time`, and `tx_hash`. Amounts are base-unit decimal strings; nullable fields can occur. Ordered by block/log descending.
## GET /tokens/:address/activity
Confidential event feed for a cToken. Query `page`, `limit`. Page item fields: `kind`, `from_addr`, `to_addr`, `handle`, `block_number`, `block_time`, `tx_hash`. This feed exposes handles, not decrypted amounts. Addresses/handles may be null depending on the event.
## GET /tokens/:address/disclosures
Disclosure feed for a cToken. Query `page`, `limit`. Page item fields: `handle`, `amount`, `block_number`, `block_time`, `tx_hash`. Amounts are publicly disclosed base-unit values; this endpoint does not authorize new disclosure. Ordered by block descending.
```json theme={null}
{
"items": [],
"total": 0,
"page": 1,
"pages": 1,
"limit": 10
}
```
Token feeds and wallet transactions share this envelope. Hosted responses keep `pages` at least 1, including empty results.
## GET /wallets/:address/assets
Lists indexed holdings for a wallet, descending last activity block. Returns the [`Asset[]` schema](/ctoken/indexer-sdk#asset). Empty wallet: `[]`. There is no pagination. SDK equivalent: `ctoken.assets({ address })`.
## GET /wallets/:address/transactions
Combined cross-token wallet activity. Query `page`, `limit`. Returns `TxPage`. Confidential transfers and public flows share the [normalized transaction schema](/ctoken/indexer-sdk#tx-and-txpage); internal mint/burn legs are excluded. SDK equivalent: `ctoken.history({ address, page, limit })`.
## GET /wallets/:address/operators
Unpaginated array: `token`, `operator`, `until` (Unix seconds string), `active` (expiry > server time), `block_number`, `tx_hash`. Newest block first; expired approvals remain with `active: false`. No SDK wrapper.
## GET /factory
Indexed deployment state:
| Field | Meaning |
| ------------------------------- | -------------------------------------------------------------------------------------------------- |
| `chainId`, `network` | Source deployment identity; server `network` label is not necessarily the SDK's NetworkName value. |
| `factory`, `vault` | Indexed deployment addresses. |
| `paused` | Latest indexed pause state, false before a state row is present. |
| `blocklist`, `blocklistEnabled` | Indexed restriction configuration; null/false defaults. |
| `implementation` | Current indexed implementation address or null. |
| `updatedBlock` | Last indexed state-update block string or null. |
These snapshots can lag chain state. The SDK does not fetch them before operations.
## GET /tokens/:address/icon
Underlying token/price-reference icon: HTTP 302 to a CDN image, cached 86400 seconds. Invalid address: 400; unknown icon: 404. Supply an image fallback.
## GET /prices
Query `tokens`: comma-separated underlying addresses, at most 200; omit for available cached prices. Returns [Prices](/ctoken/indexer-sdk#prices). Hosted TTL defaults to 600 seconds; read the response’s `ttl`.
## GET /consent/:address
Returns `{ consented: boolean, version: string, signedAt: number | null }` for current terms; timestamp is Unix seconds. Consent is separate from allowances and reveal sessions.
## POST /consent
JSON body: `{ address: string, signedAt: number, signature: string }`. Unix timestamp must be nonnegative and at most 300 seconds ahead. A valid signature records acceptance; success is HTTP 200 `{ "ok": true }`.
| Status | Body | Meaning |
| ------ | ----------------------------------------- | ------------------------------------------------- |
| 400 | `{ "error": "bad json" }` | Body cannot be parsed. |
| 400 | `{ "error": "bad body" }` | Required primitive fields missing/wrong type. |
| 400 | `{ "error": "bad timestamp" }` | Timestamp outside the accepted range. |
| 401 | `{ "error": "bad signature" }` | Signature cannot establish acceptance. |
| 503 | `{ "error": "verification unavailable" }` | Verification service/RPC temporarily unavailable. |
Canonical message (newline-separated, lowercase address):
```text theme={null}
CToken - Terms Acceptance
I have read and agree to the Inco Terms of Service (https://www.inco.org/terms-of-services) and Privacy Notice (https://www.inco.org/privacy).
Version: 2
Terms Hash: f2b10bc5e255454136696a9d007725af4920596ce78e2cc551d6e91d94bca018
Address:
Signed At:
```
Replace placeholders and sign with `walletClient.signMessage({ account: walletClient.account, message })`; POST the address, timestamp, and signature. Confirm the service’s current terms version/hash before signing. No SDK consent helper.
## Operational routes and CORS
| Route / method | Behavior |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /obs/metrics` | Indexer-owned Prometheus exposition combining Ponder metrics and application observations. Returns 500 text if local Ponder metrics cannot be read. |
| GET `/health` | Framework-owned Ponder endpoint; exposure and exact response follow the deployed framework/ingress. |
| GET `/ready` | Framework-owned readiness endpoint. |
| GET `/metrics` | Framework-owned metrics endpoint. |
| GET `/status` | Framework-owned indexing/status endpoint. |
| OPTIONS on application routes | CORS middleware handles browser preflight. Allowed origins depend on the service configuration; production access is described below. |
Hosted ingress does not expose these five operational paths. Use internal monitoring URLs; their public 404s do not indicate API failure.
Other failures: 500 (`internal error`), 429 (`rate limited`), or 503 (busy). Honor `Retry-After` on rate limits/load shedding. GET responses may be cached or stale; capacity limits vary by deployment.
## Production origins
Request hosted access through the [origin whitelist form](https://docs.google.com/forms/d/e/1FAIpQLSe_lJoMc203TEgdQlL6PhPywG2EW3jdWIOo6QwvoBK0n1QCJQ/viewform?usp=header). For your backend, see [compatibility and CORS](/ctoken/custom-indexer).
# Optional indexing
Source: https://docs.inco.org/ctoken/indexer-sdk
Opt into hosted history, discovery, and prices, or use your own backend.
## Opt in explicitly
Indexing is **off by default**. Enable it for history, discovery, and prices. Chain operations and Lightning encryption/attestations work independently.
```ts theme={null}
// Default: on-chain features, no indexer requests.
const ctoken = new CTokenClient({ network: "baseSepolia", publicClient, walletClient });
// Opt in to Inco's hosted Base Sepolia service.
const withHistory = new CTokenClient({
network: "baseSepolia", publicClient, walletClient, indexer: true,
});
// Opt in to your compatible service. The URL is a base prefix, not a route.
const custom = new CTokenClient({
network: "baseSepolia", publicClient, walletClient,
indexer: { url: "https://your-indexer.example/api", timeoutMs: 15_000 },
});
```
```tsx theme={null}
```
`false`/omitted: off. `true`/`{}`: hosted service for the selected network. `{ url }`: your compatible service.
When off, widgets hide history/discovery and retain configured tokens and chain balances. History/assets hooks do not auto-fetch; direct calls and manual refetches raise `INDEXER_NOT_CONFIGURED`. Custom UI can check `Boolean(useCToken().context.indexerUrl)`.
## Three HTTP-backed methods
| SDK call | HTTP request | Defaults |
| ----------------------------------------------- | ------------------------------------ | ------------------------------------------------------------------------------------------- |
| `history({ address?, page?, limit?, signal? })` | GET `/wallets/:address/transactions` | Current owner, page 1, limit 10; integer limit 1–100. |
| `assets({ address?, signal? })` | GET `/wallets/:address/assets` | Current owner; unpaginated. |
| `prices(tokens?, { signal }?)` | GET `/prices?tokens=...` | Empty/omitted tokens means the indexer's available priced set; at most 200 input addresses. |
An explicit address allows history/assets without a wallet. Missing prices remain absent, never zero.
```ts theme={null}
const controller = new AbortController();
const page = await ctoken.history({
address: owner, page: 2, limit: 20, signal: controller.signal,
});
const prices = await ctoken.prices([USDC], { signal: controller.signal });
const usd = prices.prices[USDC.toLowerCase()]?.usd;
// controller.abort() cancels outstanding requests using this signal.
```
## Asset
| Field | Type | Meaning |
| --------------------- | ------------------- | -------------------------------------------------- |
| `address` | string address | cToken contract. |
| `base_erc20` | string address | Underlying token. |
| `name`, `symbol` | string | Indexed wrapper metadata. |
| `decimals` | number | Token precision. |
| `balance_handle` | 32-byte hex or null | Encrypted balance handle; not a plaintext balance. |
| `handle_block` | string or null | Block associated with handle update. |
| `last_activity_block` | string | Most recent indexed activity. |
Indexed holdings do not prove a spendable balance. Read and decrypt chain state for exact amounts.
## Tx and TxPage
```ts theme={null}
type TxPage = {
items: Tx[];
total: number;
page: number;
pages: number;
limit: number;
};
type Tx = {
type: "transfer" | "flow";
token: string; // cToken
symbol: string;
decimals: number;
kind: string;
from_addr: string | null;
to_addr: string | null;
handle: string | null;
amount: string | null; // integer base units, public flow only
block_number: string;
block_time?: string; // Unix seconds; raw API null becomes undefined
log_index?: number;
tx_hash: string;
};
```
Transfers expose handles with null amounts; flows expose base-unit amount strings. History excludes zero-address confidential mint/burn legs and public `burn` rows, ordered by descending block/log index.
## Prices
```ts theme={null}
type Prices = {
chainId: number;
ttl: number; // seconds
count: number;
prices: Record;
};
```
Display the `stale` flag. Missing quotes are unknown. Keys are lowercase underlying addresses; testnet assets may use mainnet price references.
Implement the three SDK routes with the exact schemas and pagination rules.
# Migrate to 0.2.0
Source: https://docs.inco.org/ctoken/migration
One constructor, required public clients, wallet-client signing, and opt-in indexing.
These changes apply to core, React, and widgets.
```bash theme={null}
npm install @inco/ctoken@^0.2.0
```
## Configuration changes
| Previous API | 0.2.0 |
| ----------------------------------------------- | ------------------------------------------------------------------- |
| `CTokenClient.browser(options)` | `new CTokenClient(options)` |
| `CTokenClient.node(options)` | `new CTokenClient(options)` |
| Optional `publicClient` / SDK `rpcUrl` | Required caller-owned `publicClient` |
| Raw `privateKey` or standalone `account` option | Supply an application-owned `walletClient` with its account set |
| `indexerUrl`, `indexerTimeoutMs` | Opt in with `indexer: { url, timeoutMs }` |
| Automatic indexer use | Off by default; `indexer: true` selects the matching hosted service |
| Numeric token `priority` | Put tokens in their intended array order |
| Numeric balance used for Max | Use `ExactBalance.raw` or `.formatted` |
| `onMax(number)` | `onMax(exactDecimalString)` |
Removed constructor options reject with `INVALID_CONFIG` in JavaScript and type errors in TypeScript object literals.
## Unified client
```ts theme={null}
const ctoken = new CTokenClient({
network: "baseSepolia",
publicClient,
walletClient,
indexer: true, // optional; omit to keep indexing off
});
```
Keep clients stable; rebuild when account, chain, or configuration changes.
Node and browsers share [scoped sessions](/ctoken/sessions). Include cToken addresses when decrypting handles.
## React setup
```tsx theme={null}
{children}
```
Keep `QueryClientProvider`. Omit `walletClient` for wagmi; pass a client for another wallet, or null/undefined to disconnect. See [React setup](/ctoken/react).
With indexing off, widgets hide history/discovery. Indexer methods and manual refetches raise `INDEXER_NOT_CONFIGURED`.
## Balance and error behavior
Failed/pending balances throw instead of returning zero. Use `balanceExact()` for writes and `balancesSettled()` for per-token pending/error states.
```ts theme={null}
const balance = await ctoken.balanceExact({ token });
await ctoken.withdraw({ token, amount: balance.raw });
```
`onMax` now receives an exact decimal string. Indexer `block_time: null` becomes `undefined`.
Receipts return the final mined hash after repricing. Cancellation and different-operation replacement raise distinct errors. Use [error helpers](/ctoken/errors) for display; retain original causes.
# Node.js
Source: https://docs.inco.org/ctoken/node
Use the same client and session flow in services, scripts, native ESM, and CommonJS.
## Run a standalone example
Requires Node.js 20+.
```bash theme={null}
mkdir ctoken-example
cd ctoken-example
npm init -y
npm install @inco/ctoken@^0.2.0 viem @inco/lightning-js
```
Save the following as `ctoken.mjs`:
```js theme={null}
import { createPublicClient, http } from "viem";
import { baseSepolia } from "viem/chains";
import { CTokenClient } from "@inco/ctoken";
const rpcUrl = process.env.RPC_URL;
if (!rpcUrl) throw new Error("Set RPC_URL to your Base Sepolia read endpoint.");
const publicClient = createPublicClient({
chain: baseSepolia,
transport: http(rpcUrl),
});
const ctoken = new CTokenClient({ network: "baseSepolia", publicClient });
const token = "0x036CbD53842c5426634e7929541eC2318f3dCF7e";
console.log("USDC wrapper:", await ctoken.wrapperOf({ token }));
```
Run it with your own Base Sepolia read endpoint:
```bash theme={null}
RPC_URL="https://your-read-endpoint.example" node ctoken.mjs
```
This wrapper lookup needs no wallet or indexer.
## Supply your own wallet client
```ts theme={null}
const ctoken = new CTokenClient({ network: "baseSepolia", publicClient, walletClient });
```
Add a wallet client with an account for owner balances, signing, and transactions. Node uses the same constructor and [sessions](/ctoken/sessions) as browsers.
## Example: an external signing RPC
```ts theme={null}
import { createPublicClient, createWalletClient, getAddress, http } from "viem";
import { baseSepolia } from "viem/chains";
import { CTokenClient } from "@inco/ctoken";
const readRpc = process.env.RPC_URL;
if (!readRpc) throw new Error("Configure your read RPC endpoint.");
const publicClient = createPublicClient({ chain: baseSepolia, transport: http(readRpc) });
const address = process.env.WALLET_ADDRESS;
const signingRpc = process.env.WALLET_RPC_URL;
if (!address || !signingRpc) throw new Error("Configure your signing service.");
const walletClient = createWalletClient({
account: getAddress(address),
chain: baseSepolia,
transport: http(signingRpc),
});
const ctoken = new CTokenClient({
network: "baseSepolia",
publicClient,
walletClient,
});
const token = "0x036CbD53842c5426634e7929541eC2318f3dCF7e";
const balance = await ctoken.publicBalanceExact({ token });
console.log(balance.formatted);
```
The signing RPC must sign and submit for your account; a public read RPC cannot. Keep signing credentials in your wallet integration.
Next: [transactions](/ctoken/transactions) · [testnet faucets](/ctoken/overview#testnet-tokens).
## CJS and ESM
```js theme={null}
// CommonJS
const { CTokenClient } = require("@inco/ctoken");
const ctoken = new CTokenClient({ network: "baseSepolia", publicClient, walletClient });
```
The standalone example above uses ESM.
# Confidential Token (cToken)
Source: https://docs.inco.org/ctoken/overview
Private balances and transfers for ERC-20 tokens on Base and Base Sepolia.
Shield ERC-20s, send encrypted amounts, and reveal balances with your wallet’s authorization.
Preview widgets and copy integration code.Start with JavaScript, React, or widgets.
## Choose your integration
| Layer | Import | Guide |
| ------------------------ | ------------------------ | ------------------------------------------------- |
| JavaScript | `@inco/ctoken` | [Browser](/ctoken/browser) · [Node](/ctoken/node) |
| React | `@inco/ctoken/react` | [Provider & hooks](/ctoken/react) |
| Widgets | `@inco/ctoken/ui` | [UI reference](/ctoken/ui) |
| HTTP | Hosted or custom indexer | [Optional indexing](/ctoken/indexer-sdk) |
| Contracts & covalidators | viem + Lightning | [Raw APIs](/ctoken/raw) |
## How it works
| Action | Result |
| -------- | ----------------------------------------- |
| Shield | Wrap ERC-20s into a confidential balance. |
| Send | Transfer an encrypted amount. |
| Unshield | Withdraw ERC-20s to your wallet. |
| Reveal | Authorize a session to view your balance. |
Indexing is **off by default**. Opt in for history, token discovery, and prices; widgets hide those features when disabled.
## Networks
| Network | `network` | App |
| ------------ | ------------- | ----------------------------------------------- |
| Base | `base` | [Open app](https://ctoken.inco.org) |
| Base Sepolia | `baseSepolia` | [Open testnet](https://ctoken.testnet.inco.org) |
## Testnet tokens
The playground lists USDC, USDT, and EURC in that order.
| Token | Base Sepolia address (6 decimals) | Faucet |
| ----- | -------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| USDC | `0x036CbD53842c5426634e7929541eC2318f3dCF7e` | [Circle](https://faucet.circle.com/): select USDC → Base Sepolia, enter your wallet address. |
| USDT | `0x0a215D8ba66387DCA84B284D18c3B4ec3de6E54a` | [Aave](https://app.aave.com/): connect → Settings → Testnet mode → Base Sepolia → Faucet → USDT. |
Use Circle’s USDC; Aave’s test USDC has a different address. Keep Base Sepolia ETH for gas. [Verify the Aave USDT address](https://sepolia.basescan.org/tx/0x6551284ed7947e639a2017d6379edeac009e4033e15df8275cad2dae6ef35385).
## Addresses
Deployment addresses are built in. Supply your `publicClient`; add `walletClient` for balances and transactions. See [network defaults and overrides](/ctoken/configuration).
## Continue building
[Quickstart](/ctoken/sdk) · [Standalone Node example](/ctoken/node#run-a-standalone-example) · [Migrate to 0.2.0](/ctoken/migration)
# Performance
Source: https://docs.inco.org/ctoken/performance
Reduce requests and keep portfolio updates responsive.
* **Batch token reads:** use `publicBalances` or `balancesSettled`; duplicate addresses/handles are deduplicated.
* **Keep clients stable:** reuse the client and session until account, chain, or configuration changes.
* **Reveal on demand:** enable confidential queries only after user interaction.
* **Limit background work:** paginate history, avoid frequent polling, and cancel obsolete requests.
* **Keep pagination smooth:** use `keepPreviousData` for same-wallet page changes.
* **Measure first:** track RPC counts and p95 latency before adjusting multicall limits, concurrency, or timeouts.
# Contracts, RPC & covalidators
Source: https://docs.inco.org/ctoken/raw
Map SDK operations to contract calls and signed Lightning requests.
## Which service does what?
| Operation | Destination | Typical mechanism |
| ----------------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------- |
| Account access / signatures | Wallet provider | `eth_requestAccounts`, typed-data/message signing through viem. |
| Chain identity | Wallet or public RPC | `eth_chainId`. |
| Contract state | Public RPC | `eth_call`, batched Multicall where applicable. |
| Gas estimation | Public RPC / wallet | `eth_estimateGas`. |
| Transaction submission | Caller-owned wallet | Usually `eth_sendTransaction` for JSON-RPC accounts; local/custom signers may submit signed raw transactions. |
| Confirmation / replacement tracking | Public RPC | Receipts and block/transaction polling through viem. |
| Encryption / attestation | Lightning / covalidators | Network discovery, encryption, signed proof requests. |
RPC sequences depend on your wallet and transport; viem handles these calls.
## Contract mapping
| Contract | Function | Used by |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| Wrapper factory | `getWrapper(address)` | Deployed/registered wrapper resolution. |
| Wrapper factory | `computeWrapperAddress(address)` | Predicted wrapper resolution and pre-approval. |
| Wrapper factory | `createWrapper(address)` | `ensureWrapper` / deposit setup. |
| Underlying ERC-20 | `decimals()`, `balanceOf(address)`, `allowance(address,address)`, `approve(address,uint256)` | Amount precision, public balance, allowance, approval. |
| cToken | `underlying()`, `confidentialBalanceOf(address)` | Reverse lookup and encrypted balance handle. |
| cToken | `wrap(address,uint256)` | Shield tokens to owner. |
| cToken | `confidentialTransfer(address,bytes)` payable overload | Encrypted transfer with ciphertext fee. |
| cToken | `periodOfIncreasingBalanceCounter(address)`, `lastIncomingTransferCounter(address,uint256)`, `balanceCheckpoint(address,uint256,uint256)` | Withdrawal checkpoint selection. |
| cToken | `unwrap(...)` | Owner, amount, period, counter, attestation tuple, signatures. |
| Inco executor | `getFee()` | Current ciphertext fee. |
| Session verifier | `wrapperFactory()` probe on unknown deployments | Determine scoped versus generic verifier dialect. |
Deposit targets the cToken. For raw reads, declare required functions with viem `parseAbi`; the SDK does not export ABIs.
## Minimal raw read
```ts theme={null}
import { createPublicClient, http, parseAbi } from "viem";
import { baseSepolia } from "viem/chains";
const rpc = createPublicClient({ chain: baseSepolia, transport: http() });
const factory = "0x6f9a0ECD77C3Dade8Dc14a507cAbABFD746575f8";
const token = "0x036CbD53842c5426634e7929541eC2318f3dCF7e";
const wrapper = await rpc.readContract({
address: factory,
abi: parseAbi(["function getWrapper(address) view returns (address)"]),
functionName: "getWrapper",
args: [token],
});
```
Raw JSON-RPC health example:
```bash theme={null}
curl -sS https://sepolia.base.org \
-H 'content-type: application/json' \
--data '{"jsonrpc":"2.0","id":1,"method":"eth_chainId","params":[]}'
# Expected Base Sepolia chain ID: 0x14a34
```
Raw writes require amount validation, wrapper/allowance checks, confirmation handling, and Lightning encryption/attestations. The [core transaction methods](/ctoken/transactions) handle these steps.
## Covalidator endpoints
### Discovery and transport
Lightning discovers covalidators for the selected network. RPC URLs come from `publicClient` or `incoRpcUrls`; initialization is lazy.
KMS requests use Lightning’s quorum/retry policy, independent of indexer timeouts.
| Method | Path | Input and result |
| ------ | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| POST | `/inco.kms.lite.v1.KmsService/IsReady` | Readiness request `{}`; successful observed response `{ "ready": true }`. |
| POST | `/inco.kms.lite.v1.KmsService/AttestedDecrypt` | Signed handle/ACL/reencryption request; returns encrypted or plaintext attestation material processed by Lightning. |
| POST | `/inco.kms.lite.v1.KmsService/AttestedCompute` | Signed operation, lhs handle, rhs value and ACL request; SDK withdrawal uses greater-than-or-equal attestation. |
## Readiness probe
```bash theme={null}
# Use a covalidator URL discovered for your network.
curl -sS "$COVALIDATOR_URL/inco.kms.lite.v1.KmsService/IsReady" \
-H 'content-type: application/json' \
-H 'connect-protocol-version: 1' \
--data '{}'
```
## Signed request structure
Lightning builds protobuf requests. `AttestedDecrypt`: `userAddress`, `handlesWithProofs`, `eip712Signature`, `reencryptPubKey`. `AttestedCompute`: `userAddress`, `op`, `lhsHandle`, `rhsPlaintext` (hex), `eip712Signature`, `reencryptPubKey`, `aclProof`.
Use Lightning to encode proofs, signatures, session scope, and reencryption keys and verify the quorum. These field lists are not unsigned JSON templates; possessing a handle does not authorize decryption.
Use `decryptHandles()` and `withdraw()` through the SDK. There are no top-level `encrypt()` or `attestedCompute()` methods.
# React setup & wallet adapters
Source: https://docs.inco.org/ctoken/react
Use wagmi or supply your own wallet client, with customizable tokens and images.
## Install React peers
```bash theme={null}
npm install @inco/ctoken viem @inco/lightning-js react react-dom wagmi @tanstack/react-query
# Add motion when using @inco/ctoken/ui:
npm install motion
```
## Complete provider tree
```tsx theme={null}
"use client";
import { useState, type ReactNode } from "react";
import { WagmiProvider, createConfig, usePublicClient, http } from "wagmi";
import { injected } from "wagmi/connectors";
import { baseSepolia } from "wagmi/chains";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { CTokenProvider } from "@inco/ctoken/react";
import { ConfidentialWallet } from "@inco/ctoken/ui";
import "@inco/ctoken/ui/styles.css";
const config = createConfig({
chains: [baseSepolia],
connectors: [injected()],
transports: { [baseSepolia.id]: http("https://your-app.example/api/rpc") },
ssr: true,
});
export function Providers({ children }: { children: ReactNode }) {
const [queryClient] = useState(() => new QueryClient());
return (
{children}
);
}
// Replace the URL above with your paid read endpoint or application proxy.
function TokenProvider({ children }: { children: ReactNode }) {
const publicClient = usePublicClient({ chainId: baseSepolia.id });
if (!publicClient) throw new Error("Configure your read client.");
return
{children}
;
}
export function TokenWallet() {
return ;
}
```
Connect through your existing wagmi/RainbowKit button, or use:
```tsx theme={null}
import { useAccount, useConnect } from "wagmi";
export function ConnectWallet() {
const { address } = useAccount();
const { connect, connectors, isPending } = useConnect();
if (address) return {address};
return (
);
}
```
## CTokenProvider props
Required: `network`, `publicClient`, and `children`. Optional: `walletClient`, `tokens`, and the [core configuration options](/ctoken/configuration#all-client-options). In Next.js, create clients inside a Client Component.
Tokens display in array order; discovered holdings append when indexing is enabled. `tokens={[]}` disables defaults. See [token hooks](/ctoken/hooks#read-hooks) for resolution helpers.
## Token images
```tsx theme={null}
import type { TokenConfig } from "@inco/ctoken";
const TOKENS: TokenConfig[] = [
{ erc20: "0x036CbD53842c5426634e7929541eC2318f3dCF7e", symbol: "USDC", icon: "/tokens/usdc.svg" },
{ erc20: "0x0a215D8ba66387DCA84B284D18c3B4ec3de6E54a", symbol: "USDT", icon: "/tokens/usdt.png" },
{ erc20: "0x808456652fdb597867f38412077A9182bf77359F", symbol: "EURC", icon: "/tokens/eurc.svg" },
];
{children}
```
`icon` accepts an image URL or app-served path; place these files in `public/tokens`. Omit it for built-in metadata. Missing/broken images use generated avatars. Indexing is unnecessary.
## Supply your wallet client
An explicit `walletClient` works without `WagmiProvider`. Keep `QueryClientProvider` around hooks and widgets:
```tsx theme={null}
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useState, type ReactNode } from "react";
import { CTokenProvider, type CTokenProviderProps } from "@inco/ctoken/react";
export function AppProviders({ publicClient, walletClient, children }: {
publicClient: CTokenProviderProps["publicClient"];
walletClient: CTokenProviderProps["walletClient"];
children: ReactNode;
}) {
const [queryClient] = useState(() => new QueryClient());
return
{children}
;
}
```
| Wallet prop | Source and behavior |
| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| Omitted | Use the connected wallet from wagmi. Requires `WagmiProvider`. |
| `walletClient={yourClient}` | Use that client for owner identity, sessions, signing, writes, and chain switching. Overrides any connected wagmi wallet. |
| `walletClient={undefined}` or `walletClient={null}` | Explicitly disconnected. Does not fall back to a different wagmi wallet while connecting or after disconnecting. |
Set the client’s `account`, keep it stable between renders, replace it on account/chain changes, and pass null/undefined on disconnect. Use your own connect/disconnect UI.
Keep the wagmi peer dependency installed even when supplying your own wallet.
The public client handles reads and receipts; the wallet client signs and submits transactions. Session vouchers authorize reveals but cannot replace the wallet for writes.
## Ethers or another wallet library
Adapt an ethers v6 `BrowserProvider` to the required viem `WalletClient`:
```ts theme={null}
import type { BrowserProvider } from "ethers";
import { createWalletClient, custom, getAddress } from "viem";
import { baseSepolia } from "viem/chains";
// Call after the user's connect action; retain the result in app state.
export async function walletClientFromEthers(provider: BrowserProvider) {
const signer = await provider.getSigner();
return createWalletClient({
account: getAddress(await signer.getAddress()),
chain: baseSepolia,
transport: custom({
request: ({ method, params }) => provider.send(method, params ?? []),
}),
});
}
// Pass the result to .
```
For an existing EIP-1193 provider, use `custom(walletProvider)` directly. Refresh the adapter on account/chain changes and clear it on disconnect. Other signers need a compatible signing adapter. See [ethers BrowserProvider](https://docs.ethers.org/v6/api/providers/#BrowserProvider) and [viem WalletClient](https://viem.sh/docs/clients/wallet).
# SDK quickstart
Source: https://docs.inco.org/ctoken/sdk
Install cToken 0.2.0 and choose core, React, or widgets.
Use the same client in Node and browsers. Deployment addresses are built in.
```bash theme={null}
npm install @inco/ctoken@^0.2.0 viem @inco/lightning-js
```
Supports Node 20+, ESM, and CommonJS. Core does not require React.
```ts theme={null}
import { createPublicClient, http } from "viem";
import { baseSepolia } from "viem/chains";
import { CTokenClient } from "@inco/ctoken";
// Your app supplies its configured RPC URL or proxy.
const publicClient = createPublicClient({
chain: baseSepolia,
transport: http(readRpcUrl),
});
const ctoken = new CTokenClient({
network: "baseSepolia",
publicClient,
});
const wrapper = await ctoken.wrapperOf({
token: "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
});
```
Add `walletClient` for wallet balances and transactions: [browser setup](/ctoken/browser) · [Node setup](/ctoken/node).
## Add a confidential wallet
Install the React and UI peers:
```bash theme={null}
npm install react react-dom wagmi @tanstack/react-query motion
```
Inside the [React provider tree](/ctoken/react):
```tsx theme={null}
import { CTokenProvider } from "@inco/ctoken/react";
import { ConfidentialWallet } from "@inco/ctoken/ui";
import "@inco/ctoken/ui/styles.css";
```
Omit `walletClient` for wagmi, pass your client for another wallet, or null/undefined to disconnect.
## Optional features
| Feature | Configuration |
| -------------------------- | ------------------------------------------------------------------------------------------- |
| History, discovery, prices | [Opt in](/ctoken/indexer-sdk) with `indexer: true` or `indexer: { url }`. Default: off. |
| Token order and images | [Pass tokens](/ctoken/react#token-images) in display order with optional `icon` paths/URLs. |
| Custom deployments | [Override](/ctoken/configuration) `contracts` and `sessionVerifier`. |
## Run the examples
[Standalone Node script](/ctoken/node#run-a-standalone-example) · [Live playground](https://ctoken-tze4f72wfa-ew.a.run.app/) · [Testnet faucets](/ctoken/overview#testnet-tokens) · [0.2.0 migration](/ctoken/migration)
# Decryption & sessions
Source: https://docs.inco.org/ctoken/sessions
Reveal through scoped sessions in both Node and browsers.
## Reveal handles
| Method | Input | Result |
| ---------------- | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `decrypt` | `{ handle: Hex, decimals?: number, token?: Address }` | `Promise`; decimals defaults to 18. Here `token` is the cToken address. |
| `decryptHandles` | `{ handles: Hex[], tokens?: Address[] }` | `Promise`; raw values in input order. Here `tokens` are cToken addresses for scope resolution. |
| `setSession` | `Session` or null | Synchronous boolean: true when adopted, false when unusable or cleared. |
```ts theme={null}
const rows = await ctoken.preflightHandles({ tokens: [USDC] });
const row = rows[0];
if (row.error) throw row.error;
if (row.handle && row.cToken) {
const [raw] = await ctoken.decryptHandles({
handles: [row.handle],
tokens: [row.cToken],
});
console.log(raw);
}
```
Pass the cToken addresses for authorization scope. Results follow handle order.
Zero handles resolve locally to zero; duplicates decrypt once. Malformed handles fail locally.
`decryptHandles` rejects if any handle remains pending; `balancesSettled` exposes pending rows. A declined signature ends the operation.
## Session lifecycle
The first reveal may request a temporary session signature, reused for subsequent reveals. Sessions bind to owner, chain, and verifier; default expiry is four hours.
```ts theme={null}
// Adopt a session created by a compatible host integration.
const adopted = ctoken.setSession(hostSession);
// Clear the session and invalidate outstanding grants.
ctoken.setSession(null);
```
`Session` contains `account` (temporary signer), `voucher`, `expiresAt` (Unix milliseconds), and `dialect` (`generic` or `ctoken`). Adoption checks expiry, dialect, and owner. Normal use creates the session internally.
Node and browsers share this flow. A Node signer may still require user interaction.
To change accounts or transports, construct a new client.
## Scoped authorization and smart accounts
The default verifier restricts requests to its factory’s cTokens. The SDK encodes the underlying token scope; an empty voucher allowlist permits future holdings. Custom verifiers may apply different policies.
Sessions authorize confidential reads and attestations. Transactions still need the wallet. Keep session signers in memory and clear them on disconnect.
Smart accounts use the same session flow and must produce signatures accepted by their ERC-1271 contract. For direct Lightning integration, see [raw requests](/ctoken/raw).
# Transactions
Source: https://docs.inco.org/ctoken/transactions
Approve, deploy wrappers, shield, send, and unshield with exact amounts.
`token` means the underlying ERC-20. Pass `amount` as a decimal string or bigint base units; numbers are unsupported.
| Method | Arguments | Resolves to | Work performed |
| ------------------ | ---------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| `deposit` | `{ token, amount, onStep? }` | `{ hash: Hex, amount: bigint }` | Resolve/create wrapper, check allowance, approve if needed, then wrap. |
| `approve` | `{ token, amount }` | `{ hash: Hex }` | ERC-20 approval to the cToken address. Does not wrap or deploy the wrapper. |
| `allowanceOf` | `{ token, amount }` | `boolean` | Check whether the current owner's allowance to the resolved cToken covers the requested amount. No signature. |
| `ensureWrapper` | `{ token, onStep? }` | `Address` | Return registered wrapper; deploy and confirm if absent. Returns the wrapper address, not a transaction hash. |
| `confidentialSend` | `{ token, to, amount }` | `{ hash: Hex }` | Require registered wrapper, encrypt amount, read Inco fee, call payable confidential transfer. |
| `withdraw` | `{ token, amount }` | `{ hash: Hex, amount: bigint }` | Read owner's balance checkpoint, attest checkpoint ≥ amount, estimate gas, unwrap to the current owner. |
| `networkFee` | No arguments | `bigint` | Read current ciphertext-ingest fee in wei; separate from gas. |
## Shield / deposit
```ts theme={null}
const result = await ctoken.deposit({
token: USDC,
amount: "1.25",
onStep: (step) => console.log(step),
});
console.log(result.hash, result.amount); // bigint base units
```
Steps: `creating` → `approving` → `wrapping`, skipping completed setup. Each transaction is independent: approval/deployment persists if wrapping is declined. Approval targets the cToken.
```ts theme={null}
// Optional two-step UI.
if (!(await ctoken.allowanceOf({ token: USDC, amount: "1.25" }))) {
await ctoken.approve({ token: USDC, amount: "1.25" });
}
await ctoken.deposit({ token: USDC, amount: "1.25" });
```
`approve()` requires a positive amount; it cannot revoke with zero. Pre-approval may use a predicted wrapper address before deployment.
## Send confidential tokens
```ts theme={null}
const { hash } = await ctoken.confidentialSend({
token: USDC,
to: recipient,
amount: "0.5",
});
```
Requires a nonzero recipient and registered wrapper. Encryption binds to the sender/cToken; ETH covers `networkFee()` plus gas. Confirmation alone does not prove the recipient’s decrypted balance.
## Unshield / withdraw
```ts theme={null}
const result = await ctoken.withdraw({ token: USDC, amount: "0.25" });
console.log(result.hash, result.amount);
```
Withdraws to the current owner. If incoming transfers invalidate the checkpoint, let the user retry from fresh state.
## Confirmation semantics
Final writes wait for configured confirmations and return the mined hash, including fee-only replacements. Errors: `TX_CANCELLED` for cancellation, `TX_REPLACED` for a different operation, `TX_REVERTED` for reverts. Wallet/RPC causes can propagate.
# Widgets & UI reference
Source: https://docs.inco.org/ctoken/ui
Drop in a confidential wallet or compose your own views and primitives.
[Open the live playground](https://ctoken-tze4f72wfa-ew.a.run.app/) to try each component and copy its setup.
## Ready-made widgets
Import `@inco/ctoken/ui/styles.css` once and mount widgets inside the [React providers](/ctoken/react). Client components inherit your HSL theme variables.
```tsx theme={null}
import {
ConfidentialWallet, DepositWidget, SendWidget, WithdrawWidget,
BalanceCard, HistoryList,
} from "@inco/ctoken/ui";
```
| Component | Required props | Optional props / behavior |
| -------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `ConfidentialWallet` | None beyond provider | `tokens`, `token`, `symbol`, `maxVisibleTokens`, `discoverTokens`, and trigger props. Portfolio + shield/send/unshield/activity/token selection. |
| `DepositWidget` | None if provider has tokens | `tokens`, `token`, `symbol`, `onSuccess(hash)`, trigger props. Opens shielding flow. |
| `SendWidget` | None if provider has tokens | Same action props; confidential send. |
| `WithdrawWidget` | None if provider has tokens | Same action props; unshield to owner. |
| `BalanceCard` | `token` | `symbol` defaults to `token`; hidden until reveal. |
| `PortfolioCard` | `tokens` | `selected`, `onSelect`, `maxVisible`, `discover`, `onDiscovered`, `onShowAll`, controlled `revealed`, `onToggleReveal`. |
| `HistoryList` | None | `address`, `limit`, `pollMs`. `limit` controls page size; polling is off by default. |
`TriggerProps`: `trigger?: ReactNode`, `triggerLabel?: ReactNode`, `triggerClassName?: string`. Transaction callbacks belong on action widgets/views; `ConfidentialWallet` has no `onSuccess`.
With indexing enabled, discovery defaults on and appends holdings after configured tokens. For controlled reveal, pair `revealed` with `onToggleReveal`.
## Action and navigation views
| Export | Props / purpose |
| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ShieldView`, `SendView`, `UnshieldView` | `ViewProps`: required `token`; optional `symbol`, `icon`, `onSuccess(hash)`, `onDone()`, `onChangeToken()`, `onBusyChange(busy)`. |
| `HomeView` | Required `tokens`, `selected: TokenConfig`, `onSelect(address)`, `onNavigate(view)`; optional `maxVisibleTokens`, `discoverTokens`, `onDiscovered`, `onShowAll`, `revealed`, `onToggleReveal`. |
| `HistoryView` | Optional `address`, `pageSize`, `pollMs`. Includes pagination and reveal controls. |
| `TokenSelectView` | Required `tokens`, `onSelect(address)`; optional `selected`, `showBalances`, `balanceKind` (`public` or `shielded`), `revealed`, `onToggleReveal`. |
| `AnimatedView` | Required `viewKey` and children; optional `direction`, default 1. Transition wrapper respecting reduced motion. |
`WalletView`: `home`, `shield`, `unshield`, `send`, `history`, `select`. Use `onBusyChange` to prevent modal dismissal during operations.
## Display and modal primitives
| Export | Props / behavior |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Modal` | Required `open`, `onClose`, children. Optional `title`, `onBack`, `footer`, `dismissDisabled`. Portal dialog with focus trap, escape/overlay dismissal and focus restoration. |
| `DeploymentOverrides` | No props. Displays only active factory/vault/verifier values different from network defaults. Included in wallet and transaction modals. |
| `TokenPicker` | `tokens`, `selected`, `onSelect(address)`. |
| `TokenIcon` | `symbol`; optional `icon`, `seed`, `size`. Falls back to a generated avatar if an icon is unavailable. |
| `TokenCard` | `symbol`; optional `icon`, `seed`, `meta`, `action`, `onChangeToken`. |
| `ShieldedTokenCard` | `token`, `symbol`; optional `icon`, `onMax(decimalString)`, `onChangeToken`. |
| `PublicBalance` | `token`, `symbol`; optional `onMax(decimalString)`. |
| `ShieldedBalance` | `token`, `symbol`; optional `onMax(decimalString)`. |
| `FormError` | Optional string/null children; renders form feedback. |
Keep Max’s exact decimal string unchanged in state and pass it as `amount`.
```tsx theme={null}
const [amount, setAmount] = useState("");
setAmount(event.target.value)} />
```
# The ConfidentialDeck Kit
Source: https://docs.inco.org/games/confidential-deck
The five confidential moves behind any hidden-information game
`ConfidentialDeck` is the base contract you inherit. It wraps the five
confidential moves every hidden-card game needs. Everything else in your game is
plain Solidity.
The raw `e.*` calls are shown next to each move so you know what runs. Reach for
the kit call to get all of them at once.
Setup, once per file:
```solidity theme={null}
import {euint256, elist, ETypes, e, inco} from "@inco/lightning/src/Lib.sol";
using e for *;
```
## 1. Shuffle a deck
One Inco op produces the values 1 to n in a secret permutation. No per-card RNG,
no bias, no `blockhash` to front-run.
```solidity theme={null}
elist deck = e.shuffledRange(1, n + 1, ETypes.Uint256); // values 1..n, secret order
e.allow(deck, address(this)); // keep access across txs (required)
```
* Cost: `2 * inco.getEListFee(n, ETypes.Uint256)`, the range plus the shuffle. It
comes from the contract balance. Forward it as `msg.value` or pre-fund the
contract to sponsor players.
* Secret: the order. Public: `n`. List length is always public on Inco.
The kit call `_newShuffledDeck(n)` does exactly this and resets the draw pointer.
## 2. Draw the next card
Reading a card returns an opaque handle. It does not reveal the value. Disclosure
is a separate, deliberate step (moves 3 and 4).
```solidity theme={null}
euint256 card = e.getEuint256(deck, index); // free; index is a public position
```
The kit call `_draw()` returns the next card and advances a public pointer. It
also calls `allowThis()` for you, which is load-bearing: `getEuint256` alone
gives only this-tx access, so a card you store and reveal in a later tx would
otherwise be lost.
## 3. Deal a card only its owner can see
Use this for a private hand or a secret role. The `allow` grant is the privacy
boundary. Only `player` can decrypt it. The contract never emits the value.
```solidity theme={null}
card.allowThis(); // contract keeps access (needed if you reveal it later)
card.allow(player); // ONLY this address can decrypt it off-chain
```
Secret from everyone except `player`. A grant is one-way and cannot be revoked,
so never `allow` a hand to the wrong address. That is a one-line leak.
The kit call `_dealTo(player)` draws and does both grants.
The owner peeks their card from the frontend, signing once:
```ts theme={null}
const [card] = await peekMyCards(zap, walletClient, [handle]); // attestedDecrypt under the hood
```
## 4. Put a card face-up
Use this for a board card or a dice roll. It makes the value publicly decryptable
forever. This is irreversible, so reveal only what the rules force open, at the
latest safe moment.
```solidity theme={null}
card.allowThis();
e.reveal(card);
```
The kit call `_revealCard(card)` does this, or `_dealFaceUp()` draws and reveals
in one call.
Anyone reads a revealed card from the frontend, no wallet needed:
```ts theme={null}
const cards = await readRevealed(zap, handles); // attestedReveal under the hood
```
## 5. Settle on a revealed card
At settlement the contract needs the plaintext value on-chain. The frontend
brings a covalidator-signed attestation. The contract verifies it against the
stored handle, so a signed value for any other card cannot be substituted.
```solidity theme={null}
// values[i] and sigs[i] come from the frontend
require(e.verifyDecryption(card, value, sigs), "bad attestation");
uint8 id = CardLib.toId(value); // -> rank/suit for a 52-card game
```
The kit call `_verifyValue(card, value, sigs)` returns the verified raw value.
Package a batch for the on-chain `settle(...)`:
```ts theme={null}
const revealed = await readRevealed(zap, handles);
const { values, sigs } = packForSettle(revealed);
await wallet.writeContract({ address, abi, functionName: "settle", args: [values, sigs] });
```
## Adding a new game
1. `contract MyGame is ConfidentialDeck { ... }`.
2. Shuffle with `_newShuffledDeck`. Deal with `_dealTo` (private) or
`_dealFaceUp` (public). Read at settlement with `_verifyValue`.
3. Expose the card handles through a view so the frontend can decrypt or reveal
them.
4. Add an Ignition module, a deploy script, and a frontend page. Copy the closest
example.
## The three rules that break every new Inco project
* Call `allowThis()` on every stored handle. A handle you cannot re-access is
lost forever.
* Pay the fee for `shuffledRange` with `deckFee(n)`, from `msg.value` or a
pre-funded contract.
* Never `if` or `require` on an encrypted value, and never `e.reveal` a card
before the rules open it.
# Worked Examples
Source: https://docs.inco.org/games/examples
Four full games built on ConfidentialDeck
Each game is small, tested, and built only on the kit. Read them to see the moves
assembled into a real flow. The privacy model differs per game, which is the
point: the kit covers private hands, public reveals, hidden winners, and
per-player secrets.
## War
The smallest game. One private card each, higher rank wins.
* Each player's card is dealt with `_dealTo`, so only they can peek it.
* Both cards reveal at showdown, then settle by comparing verified values.
* Matchmaking uses a rooms array. `join()` seats you at an open table or opens a
new one, so a busy table never blocks a newcomer.
Source: [`contracts/examples/War.sol`](https://github.com/Inco-fhevm/confidential-deck-template/blob/main/contracts/examples/War.sol)
## Blackjack
Solo play against the house. Private hand, hit loop, public dealer upcard,
reveal-all, attested settle, and a pull payout.
* The player's hand is dealt face-up on purpose. There is no opponent to hide it
from, and it keeps the UI free of signature prompts.
* The confidential part is the dealer's hole card and the undealt shoe, hidden
with `_draw` until the player stands.
* Scoring lives in `BlackjackMath.sol`, pure Solidity with no Inco calls, so it
unit-tests without a covalidator.
Source: [`contracts/examples/Blackjack.sol`](https://github.com/Inco-fhevm/confidential-deck-template/blob/main/contracts/examples/Blackjack.sol)
## Raffle
The kit is not just for cards. One shuffle picks a hidden winner, revealed at the
draw.
* The winning ticket is a hidden draw, unknowable even to the deployer until
`draw()` reveals it.
* Entrant addresses and ticket numbers are public by nature. Only the outcome is
secret until reveal.
* `newRound()` reopens for a fresh draw.
Source: [`contracts/examples/Raffle.sol`](https://github.com/Inco-fhevm/confidential-deck-template/blob/main/contracts/examples/Raffle.sol)
## Mafia
Selective reveal. Each player privately learns only their own role.
* Each role is dealt with `_dealTo` to its owner, so only that player can decrypt
it.
* No role is ever revealed on-chain. Social play happens off-chain.
* `reset()` reopens for a fresh round.
Source: [`contracts/examples/Mafia.sol`](https://github.com/Inco-fhevm/confidential-deck-template/blob/main/contracts/examples/Mafia.sol)
## What stays secret
No plaintext card or role value is ever emitted in an event or stored in the
clear. Contracts hold only `bytes32` handles. Plaintext appears on-chain only at
a deliberate `e.reveal` or `_verifyValue` settlement point. `e.verifyDecryption`
binds the signed value to the stored handle, so a valid attestation for a
different handle cannot be substituted.
| Game | Secret | Public |
| --------- | --------------------------------- | --------------------------- |
| War | each player's card until showdown | table state, the winner |
| Blackjack | dealer hole card, undealt shoe | player hand, settled result |
| Raffle | the winning ticket until the draw | entrants, ticket numbers |
| Mafia | each player's role, always | who is playing |
# Hangman
Source: https://docs.inco.org/games/hangman
Word-guessing game with the secret word encrypted on-chain
[Hangman](https://github.com/Inco-fhevm/hangman) is the classic word game with
the secret word kept encrypted on-chain. The player guesses letters, the contract
checks each guess against the hidden word, and only the player can decrypt their
own progress. No one, including the contract deployer, can read the word from
chain state.
Where [Mines](/games/mines) leans on the shuffle primitive, Hangman is a good
look at the core encrypted operations. Every guess is resolved with `e.eq`,
`e.or`, `e.and`, and `e.select` on encrypted values. The contract never branches
on a plaintext letter.
## How it works
A `HangmanFactory` holds a list of encrypted words. A master account seeds them
with `addWord` or `seedWords`, paying one `inco.getFee()` per word. Each word is a
4-character string packed into one `euint256` and stored encrypted.
To start a game, the factory picks a word and deploys a per-player
`HangmanGame`, granting that game access to the chosen word. The word index is
chosen pseudo-randomly from block data, but that only picks which entry to use.
The word itself stays encrypted, so the selection never leaks it.
The game holds all state encrypted, readable only by the player:
| State | Type | Meaning |
| ------------------- | ---------- | ------------------------------------ |
| `encryptedChars[4]` | `euint256` | the four letters of the word |
| `revealed[4]` | `ebool` | which positions the player has found |
| `lives` | `euint256` | starts at 8 |
| `hasWon` | `ebool` | all four positions revealed |
## Guessing a letter
`guessLetter` runs entirely on encrypted data:
```solidity theme={null}
// compare the guessed letter to every position, encrypted
ebool f = e.eq(encryptedChars[i], e.asEuint256(charCode));
// mark a position found if it matches (never overwrite a hit)
revealed[i] = e.or(revealed[i], f);
// won when all four positions are revealed
hasWon = e.and(e.and(revealed[0], revealed[1]), e.and(revealed[2], revealed[3]));
// lose a life only if the guess did not complete the word
lives = e.select(hasWon, lives, e.sub(lives, e.asEuint256(1)));
```
Every result handle is granted to the player with `e.allow`. The frontend
decrypts them off-chain to paint the board and show remaining lives. The contract
stores only handles, so the word and the running state never appear in the clear.
## Running it
The repo is a Next.js frontend plus a Hardhat contracts folder. It targets Base
Sepolia testnet.
```bash theme={null}
git clone https://github.com/Inco-fhevm/hangman.git
# contracts
cd hangman/contracts && bun install
bun hardhat compile
bun hardhat test --network baseSepolia
# frontend
cd .. && npm install && npm run dev # http://localhost:3000
```
Set `PRIVATE_KEY`, `SEED_PHRASE`, and `BASE_SEPOLIA_RPC_URL` in `contracts/.env`
before deploying or testing.
## Honest note
This is a reference build, not a template. Words are fixed at 4 characters and a
game starts with 8 lives. The word list is seeded by a trusted master account.
Treat it as a worked example of doing game logic on encrypted values, not as
production code.
# Incasino
Source: https://docs.inco.org/games/incasino
A confidential on-chain casino with six games, powered by e.rand()
[Incasino](https://github.com/Inco-fhevm/incasino) is a confidential on-chain
casino built on Inco Lightning. Six games in one contract: Coin Flip, Dice,
Mines, Plinko, Rock Paper Scissors, and Slots. You bet native test ETH on Base
Sepolia, with no token or deposit step.
incasino.vercel.app, running on Base Sepolia.
Where the [ConfidentialDeck template](/games/confidential-deck) shuffles a deck,
Incasino leans on the other core randomness primitive: `e.rand()`. It is the
cleanest place to see the play-then-settle pattern that every asynchronous Inco
game uses.
## The play-then-settle pattern
Inco has no synchronous on-chain decryption, so a round is always two
transactions:
```
play...(...) lock the wager (sent as ETH), draw a secret seed with e.rand()
settle(gameId, attestation, signatures)
submit the covalidator attestation, decode the seed, pay out
```
The seed is drawn confidentially and revealed only at settlement, so the outcome
cannot be known or front-run while the bet is live. The contract verifies the
covalidator-signed attestation before paying, so a player cannot forge a win.
## The six games
One `Casino.sol` holds the ETH bankroll and all six games. Each has its own
`play*` entry point; a single `settle` routes by game kind.
| Game | Entry point |
| ------------------- | ------------------------------------------------ |
| Coin Flip | `playCoinFlip(wagerPerRound, isHeads, rounds)` |
| Dice | `playDice(guess, isOver, wagerPerRound, rounds)` |
| Mines | `playMines(points, numMines, wager)` |
| Plinko | `playPlinko(wagerPerRound, rounds)` |
| Rock Paper Scissors | `playRPS(action, wagerPerRound, rounds)` |
| Slots | `playSlots(wagerPerRound, rounds)` |
Bets are capped at `MAX_WAGER_PER_ROUND = 0.0005 ether`, and quick games run up to
`MAX_ROUNDS = 10` rounds in one transaction. Payouts carry a small house edge
baked into the multiplier (for example Coin Flip pays 1.98x, a 2% edge).
## Deployed contract (Base Sepolia)
One verified contract holds the bankroll and every game. Chain id 84532.
| Contract | Address |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| Casino | [`0x5b5d7d4ad82bac6419c205c395fd208901592357`](https://sepolia.basescan.org/address/0x5b5d7d4ad82bac6419c205c395fd208901592357#code) |
The owner funds and withdraws the bankroll from the `/owner` page.
## Running it
```
contracts/ Solidity Casino contract, tests, deploy script
client/ Next.js frontend (wagmi + RainbowKit + viem)
```
```bash theme={null}
git clone https://github.com/Inco-fhevm/incasino.git
# contracts
cd incasino/contracts && npm install
cp .env.example .env # set PRIVATE_KEY_BASE_SEPOLIA
npm run compile
npm run deploy:baseSepolia # deploys and funds the bankroll
npm test
# frontend
cd ../client && npm install && npm run dev
```
Connect a wallet on Base Sepolia, grab test ETH from a faucet, and play.
## Honest note
This is a testnet build. Bets are capped low and the bankroll is a single
owner-funded contract, so it is a worked example of the play-then-settle pattern
and confidential randomness, not a production casino.
# Mines
Source: https://docs.inco.org/games/mines
Confidential on-chain Minesweeper with an encrypted board
[Mines](https://github.com/Inco-fhevm/mines) is a Minesweeper-style casino game
where the whole board is encrypted on-chain. Nobody can read the bomb map, not
even by reading storage. Built on Inco's confidential EVM.
The interesting part is how it keeps the board secret without paying for it on
every click. A naive version stores one encrypted `uint` per bomb, which gives
biased placement, O(N) cost per click, and a packing cap that limits board size.
## How it keeps the board secret
* The board is an elist of `ebool`, length N squared. One entry per tile, `true`
means bomb.
* Bombs are placed with a single `shuffle`. That gives a uniform distribution in
one Inco op, with no per-bomb bias.
* Each click is O(1). `e.getEbool(board, pos)` reads one cell instead of scanning
every bomb.
* A sticky encrypted accumulator tracks the whole game. `ebool everHitBomb` is
updated with `e.or` on every pick, so cashout verifies exactly one attestation
no matter how many tiles the player opened.
## The flow
```
createMinesContract deploy a game, shuffle the board (one Inco fee), reserve max payout
pickTile(pos) ebool hit = e.getEbool(board, pos); e.reveal(hit)
everHitBomb = e.or(everHitBomb, hit); e.reveal(everHitBomb)
frontend attestedReveal([hit, accumulator]) with no wallet signature
cashOut(sig) contract verifies the covalidator signature, requires no bomb was hit
```
Settlement is attestation-based, so there is no on-chain callback. Every
encrypted result is revealed publicly, the frontend pulls the attested
decryption with `attestedReveal` (no signature needed), and the contract verifies
the covalidator-signed attestation at cashout. The player sees one wallet popup
per pick and one at cashout.
## Contracts
| File | Role |
| ------------------ | ---------------------------------------------------------------- |
| `Mines.sol` | per-game contract: elist board, accumulator, attested settlement |
| `MinesFactory.sol` | deploys games, holds bets, pays out winners |
| `MinesMath.sol` | hypergeometric multiplier plus a 1% house edge |
Solidity 0.8.30, `@inco/lightning` and `@inco/lightning-js` at 1.0.2. EList is
built into core as of v1.
## Running it
The repo has a Hardhat contracts side and a Next.js frontend. It runs against
Base Sepolia testnet or a fully local Inco node.
```bash theme={null}
git clone https://github.com/Inco-fhevm/mines.git
# contracts (pnpm)
cd contract && pnpm install
pnpm hardhat test test/Mines.multiplier.test.ts # pure math, no chain
pnpm hardhat run scripts/deployForFrontend.ts --network baseSepolia
# local Inco node instead of testnet
pnpm node:up # anvil (8545) + covalidator (50055)
pnpm test:anvil
pnpm node:down
# frontend (npm)
cd ../interface && npm install && npm run dev
```
Use `Lightning.localNode("mainnet")` to point the SDK at the local node. The
`mainnet` pepper matches the local image executor. Node 22 LTS is pinned;
Node 25+ breaks wagmi connectors during SSR.
## Honest limitations
This is a testnet build with two things to know before real money.
* The factory must hold enough ETH to cover the max payout of every active game.
Mines multipliers explode at higher mine counts, so a 5 by 5 board with 5 mines
needs about 53 ETH in reserves per 0.001 ETH bet. Boards with 7 or more mines
are effectively unusable on testnet.
* After the timeout fix, `expireGame` refunds the bet on timeout. That is correct
for a winning player who could not cash out in time, but it also refunds a
player who hit a bomb and walked away. A real product would require an
attestation proving no bomb was hit before refunding.
A multi-agent security audit was run and the high-confidence findings were fixed.
The report and rationale live in the repo under `docs/plans/`.
# Inco for Games
Source: https://docs.inco.org/games/overview
Build hidden-information games on Inco with the ConfidentialDeck template
Card games, raffles, and hidden roles all need the same thing: state that stays
secret until the rules say otherwise. A deck no one can predict. A hand only its
owner sees. A reveal at showdown that everyone can trust.
The [ConfidentialDeck template](https://github.com/Inco-fhevm/confidential-deck-template)
gives you that as one base contract. You inherit it and write only your game
rules. The shuffle, the private deals, the public reveals, and trustless
settlement come with it.
All four games running on Base Sepolia. Connect a wallet and play.
It is built on Inco Lightning v1. Inco is confidential compute for the EVM, not
FHE and not zk. "Secret" means the value is decrypted by Inco. "Provably fair"
means a covalidator attestation, not a proof.
## The five moves
Everything confidential is one call on `ConfidentialDeck`.
| Move | Kit call | Under the hood |
| --------------- | ---------------------------------- | ------------------------------------------------------ |
| Shuffle | `_newShuffledDeck(n)` | `e.shuffledRange(1, n+1, ETypes.Uint256)`, one Inco op |
| Draw | `_draw()` | `e.getEuint256(deck, i)` plus auto `allowThis` |
| Deal (private) | `_dealTo(player)` | `card.allow(player)`, only they can decrypt it |
| Reveal (public) | `_revealCard(c)` / `_dealFaceUp()` | `e.reveal(c)` |
| Settle | `_verifyValue(c, value, sigs)` | `e.verifyDecryption(...)`, bound to the handle |
## A whole game in about 15 lines
Inherit the kit and write only your rules. This is a simplified sketch; the real
`War.sol` adds matchmaking and settlement.
```solidity theme={null}
import {euint256} from "@inco/lightning/src/Lib.sol";
import {ConfidentialDeck} from "./kit/ConfidentialDeck.sol";
contract War is ConfidentialDeck {
mapping(address => euint256) public myCard;
function startRound() external payable {
require(msg.value >= deckFee(52), "fee");
_newShuffledDeck(52);
}
function draw() external {
myCard[msg.sender] = _dealTo(msg.sender); // only the caller can peek it
}
// showdown: reveal both cards and settle with _verifyValue(...)
}
```
The frontend half reads cards back.
```ts theme={null}
import { getZap, peekMyCards, decodeCard } from "./client/incoDeckClient";
const zap = await getZap({ local: true });
const [c0] = await peekMyCards(zap, wallet, [handle]);
console.log(decodeCard(c0.value).label); // e.g. "A♠"
```
## What is in the box
The five confidential moves, the fees, and the rules that break new projects.
Four full games: War, Blackjack, Raffle, and Mafia.
Install, test against a local node, deploy, and wire the frontend.
The full Hardhat project plus a Next.js demo dApp that plays all four games.
Building with an AI assistant? First set it up with [Build with AI](/build-with-ai),
the Inco agent skill that gives your assistant game-design sense. Then hand it the
template: the repo ships an `AGENTS.md` explaining the kit, the per-game privacy
model, and the frontend, so it can start fast.
## More Inco games
More full game apps, built on Inco but not on the deck template. Read them for
different confidential patterns.
A six-game casino powered by `e.rand()`. The cleanest look at the
play-then-settle pattern.
Minesweeper with an encrypted board. Bombs placed by one shuffle, O(1) per
click, attested cashout.
The secret word stays encrypted on-chain. Every guess is resolved with core
encrypted operations.
# Run It
Source: https://docs.inco.org/games/quickstart
Install, test, deploy, and wire the frontend
Clone the template and you have a full Hardhat project plus a Next.js demo dApp
that plays all four games.
```bash theme={null}
git clone https://github.com/Inco-fhevm/confidential-deck-template.git
cd confidential-deck-template
```
## Layout
```
contracts/
kit/ConfidentialDeck.sol the base contract you inherit
CardLib.sol 52-card rank/suit decoding (optional)
examples/ War, Blackjack, Raffle, Mafia
client/
incoDeckClient.ts peekMyCards / readRevealed / packForSettle
test/ pure units (no Docker) plus full games vs a real covalidator
ignition/modules/ one deploy module per game
frontend/ the demo dApp
RECIPES.md copy-paste snippets, one per move
```
## Contracts
```bash theme={null}
npm install # @inco/lightning + @inco/lightning-js v1.0.2
npm run compile
npm test # pure-logic units (blackjack scoring), no Docker
npm run node:up # local Inco node: anvil + covalidator v1.0.2
npm run test:local # units plus all four games end-to-end
npm run node:down
```
Package and image versions must match: `@inco/lightning{,-js}@1.0.2` with
`inconetwork/local-node-{anvil,covalidator}-mainnet:v1.0.2`. A mismatch fails at
the shuffle with a ciphertext MAC error.
## Deploy and wire the frontend
Deploy to Base Sepolia testnet, then write the addresses into the frontend env.
```bash theme={null}
npm run deploy:war:testnet # also :blackjack :raffle :mafia
npm run wire:frontend # writes deployed addresses into frontend/.env.local
cd frontend && npm install
cp .env.example .env.local # WalletConnect id plus the deployed addresses
npm run dev
```
## The frontend client
`client/incoDeckClient.ts` is the client half of the kit. It mirrors the contract
moves.
| Function | What it does |
| ----------------------------------- | ------------------------------------------------------ |
| `getZap({ local })` | init the SDK against a local node or Base Sepolia |
| `peekMyCards(zap, wallet, handles)` | decrypt cards dealt to you (signs once) |
| `readRevealed(zap, handles)` | read public cards, no wallet |
| `packForSettle(cards)` | shape revealed cards into `(values, sigs)` for settle |
| `decodeCard(value)` | decode a value from 1 to 52 into rank, suit, and label |
`peekMyCards` uses `attestedDecrypt`, so Inco refuses anyone but the owner.
`readRevealed` uses `attestedReveal`, which needs no signature. The covalidator
is async, so both retry until the value lands.
## Next steps
* [Build with AI](/build-with-ai): set your assistant up with the Inco skill, then
hand it this repo and its `AGENTS.md`.
* Play the [live demo](https://confidential-deck.vercel.app) to see all four
games running on Base Sepolia.
* Read the [ConfidentialDeck kit](/games/confidential-deck) for the five moves in
detail.
* See the [worked examples](/games/examples) for full game flows.
* `RECIPES.md` in the repo has one copy-paste snippet per move, and `AGENTS.md`
briefs an AI on the whole project.
# Best Practices
Source: https://docs.inco.org/guide/best-practices
Avoid pitfalls and write secure dapps
To close this concepts guide, here are some best practices to keep in mind when creating your confidential dapps.
## Always check allowance over inputs
As we have seen in the confidential token example, most of your external facing functions
that expose a confidential input will want to be declared twice like so.
```Solidity theme={null}
function transfer(address to, bytes memory valueInput) external returns (ebool) {
euint256 value = valueInput.newEuint256(msg.sender);
return _transfer(to, value);
}
function transfer(address to, euint256 value) public returns (ebool success) {
require(msg.sender.isAllowed(value), "SimpleConfidentialToken: unauthorized value handle access");
return _transfer(to, value);
}
```
This is because one function is meant to receive a ciphertext created offchain, and the other is meant to
be called by smart contracts sending an existing e-variable.
In the second function, you should always check that the caller has access to the ciphertext handle
that is passed as an argument. This is done by performing a require over `msg.sender.isAllowed(value)`.
This is important because the caller may use an existing handle that it has not access to but that the contract
has access to. In this case, depending on the contract, the caller may be to deduce or gain access to the value in used as input.
## Think in terms of information leakage
When designing an app, you need to be mindful not only to who receives access over the ciphertexts,
but also about what can be deduced from the information that is publicly available.
For example, if we were to naively port Uniswap pools to Inco,
we may want to accept confidential input amounts for a swap and send confidential output amounts.
If the price of the pool is public, then the swapped amount can be deduced by comparing the price before and after the swap.
In another example, if you are holding a secret auction where the current highest bidder is continuously updated,
one can deduce the current highest bid by submitting increasingly large bids until it becomes the highest bidder.
This kind of possible deductions are called information leakage, and may show up often in your dapps.
## Don't lose access over your ciphertexts
Don't forget to call `e.allowThis()` and `e.allow` after an operation. By default, after the transaction is
included, no one retains access to the new handles being created and the contract will not be able to compute over them in the future,
and the user won't be able to see them if not granted access.
## Always verify the intended handle when verifying attestations
When accepting attested decryption or computation results on-chain, always verify that the attestation corresponds to the intended ciphertext handle. This prevents malicious actors from submitting valid attestations for different handles that may have been swapped in transit.
```Solidity theme={null}
function SubmitDecryption(
DecryptionAttestation memory decryption,
bytes[] memory signatures
) external {
require(
inco.incoVerifier().isValidDecryptionAttestation(decryption, signatures),
"Invalid Signature"
);
require(euint256.unwrap(randomNumber) == decryption.handle, "Handle mismatch");
decryptedNumber = uint256(decryption.value);
}
```
The signature verification alone is not enough - you must explicitly check that `decryption.handle` matches the specific handle you expect to decrypt.
## Be extra careful of delegatecalls
A contract being delegatecalled can decrypt any ciphertext your contract holds or share access to it.
## Session keys grant unbounded access — scope and lifetime matter
A session voucher (see [Allowance Voucher (EVM)](/js-sdk/voucher/allowance-voucher) or [Allowance Voucher (Solana)](/svm/js-sdk/voucher/allowance-voucher)) gives the holder access to **all** of the signer's encrypted handles across every Inco-enabled dApp, not just the handles created by your application. This is by design — the verifier checks only expiry and decrypter identity, not the origin of the handle being accessed.
Practical guidance for dApp developers:
* **Keep expiry short.** Prefer session lifetimes measured in minutes. A 24-hour session is rarely necessary and leaves a long window for misuse.
* **Revoke promptly.** Call `updateActiveVouchersSessionNonce()` after the session is no longer needed. This immediately invalidates all outstanding vouchers regardless of their expiry timestamp.
* **Do not store or forward vouchers.** The signed voucher is a capability token. Logging it, storing it in localStorage beyond the session, or forwarding it to a backend grants that storage or service the same access as the user.
* **Show users what they are signing.** The voucher `warning` field is placed first in the signed payload so wallets show it before opaque fields. Do not suppress or alter it — verifiers reject proofs whose voucher does not contain the exact required warning text, and it is the user's only in-wallet indication of the scope of what they are authorising.
Don't hesitate to contact us for any question or if you want to discuss your
dapp design. We are also interested in your feedback on this doc.
# Control Flow
Source: https://docs.inco.org/guide/control-flow
Using select and the multiplexer design pattern
Since Inco enables smart contracts to compute over private data without leaking any information,
two common programming usages can't be used.
1. You can't use an if/else statement with a condition depending on a private value.
The flow that the program would take would leak information about the private value.
2. For the same reason you can't revert a transaction based on a condition depending on a private value.
To go around this, we use a pattern called the multiplexer design pattern.
## Multiplexer Design Pattern
The inco equivalent of an if/else statement is the `select` statement.
The `select` statement takes an encrypted boolean as first argument and two encrypted values as second and third arguments.
The result of the `select` statement is the second argument if the first argument is true and the third argument otherwise.
Example usage from the confidential token contract:
```Solidity theme={null}
function _transfer(address to, euint256 value) internal returns (ebool success) {
// we check that the user has enough balance, and assign the result to the ebool success
success = balanceOf[msg.sender].ge(value);
// we use the select statement to assign the value to be transferred
// if the the user has enough balance, we transfer the value
// otherwise we assign 0 to the transferred value
euint256 transferredValue = success.select(value, uint256(0).asEuint256());
// ... rest of the transfer logic
}
```
In the confidential token example, instead of reverting if the user has insufficient balance,
we transfer an amount of 0, which is equivalent to doing nothing. Expect this kind of logic in most confidential apps.
# Decryption
Source: https://docs.inco.org/guide/decryption
Overview of decryption flows and access control.
Inco supports multiple ways to turn encrypted handles into plaintext, depending on who should learn the data and where the result must be consumed. This page summarizes the main flows and highlights how access control and signatures keep the data safe.
## Signatures and EIP-712
Attested flows (`attestedDecrypt`, `attestedCompute`) require the user to prove control over their address.\
The JS SDK does this by asking the user to sign an **EIP-712 message** that binds:
* the caller’s address,
* the requested operation (decrypt, compute),
* and the handles / parameters involved in the request.
This ensures that only the address that has on-chain access to a handle (via `e.allow` or `e.reveal`) can request an attestation for it, and prevents a malicious party from replaying or forging decryption/computation requests.
## Attested Decrypt
Use an off-chain covalidator to decrypt a handle for an authorized user and receive a signed attestation of the plaintext. Refer to [Attested Decrypt](../js-sdk/attestations/attested-decrypt) for full examples. High-level flow:
* A contract exposes an encrypted handle (e.g. created with `e.rand()`), and grants access with `e.allow`.
* The authorized user calls `zap.attestedDecrypt(...)` from the JS SDK, which talks to the covalidator.
* The response contains the plaintext plus the covalidator signature, enabling the user to post the plaintext back on-chain if needed.
## Attested Reveal
If the contract already called `e.reveal(handle)`, anyone may request an attested decryption because the handle is considered public. See [Attested Reveal](../js-sdk/attestations/attested-reveal). The SDK call `zap.attestedReveal([...handles])` returns plaintexts plus signatures that can be re-submitted on-chain. **Warning:** once `e.reveal` runs, the ciphertext is public forever.
## Attested Compute
Sometimes the goal is to evaluate a predicate (e.g. `creditScore >= 700`) instead of exposing the raw value. [Attested Compute](../js-sdk/attestations/attested-compute) executes the computation off-chain, still requiring the handle to be shared via `e.allow` or `e.reveal`. The SDK call `zap.attestedCompute(...)` returns the result (such as an `ebool`) alongside a covalidator signature so the decision can be verified on-chain without re-running the computation.
# EList
Source: https://docs.inco.org/guide/elist
Encrypted list operations for confidential dynamic arrays
## Import
```solidity theme={null}
import {euint256, ebool, e, inco, elist, ETypes} from "@inco/lightning/src/Lib.sol";
```
## Important: Fee Payments and Access Control
**Fee Payments**: Most elist operations require paying fees. The fee scales with the number of elements and element type. Use `inco.getEListFee(nOfElements, elType)` to calculate the required amount. For example, when calling `e.newEList(inputs, listType, user)`, ensure `msg.value >= inco.getEListFee(uint16(inputs.length), listType)`. Other operations like `set()`, `append()` and `shuffle()` also require fee payment proportional to the list length produced. See [Fees](/quickstart/fees#elist-operations-dynamic-fees) for the full fee table and cost accounting formula.
**Access Control**: After creating or modifying an elist, you must explicitly grant access permissions to allow addresses to decrypt the list contents. Use the `e.allow()` convenience helper:
```solidity theme={null}
e.allow(myList, address(this));
e.allow(myList, msg.sender);
```
## Creating new empty EList
`newEList(type)` creates a new empty list and returns a new elist handle. Type must be specified ahead of time and can not be changed.
Here is an example of how to create a new EList holding `euint256` values:
```solidity theme={null}
elist myList = e.newEList(ETypes.Uint256);
// myList = E([])
```
Note: Each elist handle is IMMUTABLE, so a handle will forever point to a particular list of values. Any operation on a list will return a new handle pointing to a new list, leaving the original list unchanged.
Arguments:
* ETypes listType - Type of each element in the list. This can not be changed
Returns:
* Elist - a new elist handle
## Creating new EList from existing handles
`newEList(handles, type)` creates a new list from existing list of handles and returns a new elist handle. Type must be specified ahead of time and can not be changed.
Handles type must match the type of the list container, otherwise it will revert.
Here is an example of how to create a new EList from existing `euint256` handles:
```solidity theme={null}
function createListFromHandles() public payable returns (elist) {
bytes32[] memory handles = new bytes32[](5);
for (uint256 i = 0; i < 5; i++) {
handles[i] = euint256.unwrap(e.asEuint256(i + 1));
}
require(msg.value >= inco.getEListFee(uint16(handles.length), ETypes.Uint256), "Fee not paid");
elist myList = e.newEList(handles, ETypes.Uint256);
// myList = E([1, 2, 3, 4, 5])
return myList;
}
```
Arguments:
* bytes32\[] handles - An array of handles to create a new list from
* ETypes listType - Type of each element in the list. This can not be changed and must match the type of each handle in the array.
Returns:
* Elist - A new elist handle
## Length
`length(list)` returns the length of the list in plaintext. It's a pure function that doesn't require any gas to call.
```solidity theme={null}
uint16 len = e.length(myList);
// len == 5
```
Note: It is IMPORTANT to keep in mind that the length of the elist is ALWAYS PUBLIC and encoded inside the returning handle itself. It's an intentional design choice to make contract behavior more predictable at a cost of leaking the length of the list, because it can (for the most part) always be predicted by looking at history of on-chain operations.
Arguments:
* elist list - list to read length from
Returns:
* uint16 len - length of the list in plaintext
## ListTypeOf
`listTypeOf(list)` returns the type of elements contained in the list. It's a view function that doesn't require any gas to call.
```solidity theme={null}
function listTypeOf() public view returns (ETypes) {
return e.listTypeOf(list);
}
// Returns ETypes.Uint256 or ETypes.Bool
```
Arguments:
* elist list - list to read type from
Returns:
* ETypes - the type of elements in the list (e.g., `ETypes.Uint256`, `ETypes.Bool`)
## Creating new EList from user inputs
Sometimes it's desired to create an elist from user inputs directly, like from a javascript dApp. `newEList(inputs, type, user)` can take an array of user encrypted ciphertexts and returns a new elist handle. Expected type must be specified ahead of time and can not be changed.
Handles type must match the type of the list container, otherwise it will revert.
Here is a complete example of how to create a new EList from user encrypted inputs:
```solidity theme={null}
function newEList(bytes[] memory inputs, ETypes listType, address user)
public
payable
returns (elist)
{
require(msg.value >= inco.getEListFee(uint16(inputs.length), listType), "Fee not paid");
elist list = e.newEList(inputs, listType, user);
e.allow(list, address(this));
e.allow(list, msg.sender);
return list;
}
```
Arguments:
* bytes\[] ciphertexts - An array of encrypted user inputs to create a new list from
* ETypes listType - Expected type of each element in the list. This can not be changed and must match the type of each handle in the array.
* address user - Address of the owner of the inputs, used to decrypt ciphertexts.
Returns:
* elist - A new elist handle
## Append
`append(list, value)` appends an `euint256` or `ebool` element type at the end of an array, returning a new modified list handle.
Example usage:
```solidity theme={null}
function listAppend(bytes memory ctValue) public payable returns (elist) {
require(msg.value >= inco.getEListFee(1, ETypes.Uint256), "Fee not paid");
euint256 handle = e.newEuint256(ctValue, msg.sender);
e.allow(handle, address(this));
e.allow(handle, msg.sender);
list = e.append(list, handle);
e.allow(list, address(this));
e.allow(list, msg.sender);
return list;
}
// [].append(5) == [5]
```
Arguments:
* elist list - An elist handle to append to
* euint256/ebool value - Element value to be appended to the list. Must match the elist type.
Returns:
* elist - A new elist handle
## Insert
`insert(list, i, value)` inserts a hidden element at a desired hidden position, returns a new modified list. Index can be both plaintext or encrypted.
Note however that if index is out of range, it works similarly to append() and appends element at the end of the list.
Example usage:
```solidity theme={null}
elist myList = e.newEList(ETypes.Uint256);
elist myNewList = e.append(l, e.asEuint256(10));
euint256 el = e.asEuint256(5);
elist insertedList = e.insert(myNewList, uint256(0), el);
// [10].insert(0, 5) == [5, 10]
```
Arguments:
* elist A - An elist handle to insert to
* euint256/uint256 i - Index position to insert at, can be both encrypted or plaintext.
* euint256/ebool B - Element value to be inserted to the list. Must match the elist type.
Returns:
* Elist - A new elist handle
## Get
`getEuint256(list, index)` and `getEbool(list, index)` return the hidden element at a plaintext position. These methods have separate names due to Solidity function overloading limitations.
Example usage:
```solidity theme={null}
function listGet(uint16 index) public returns (euint256) {
euint256 res = e.getEuint256(list, index);
e.allow(res, msg.sender);
return res;
}
function boolListGet(uint16 index) public returns (ebool) {
ebool res = e.getEbool(boolList, index);
e.allow(res, msg.sender);
return res;
}
```
Arguments:
* elist list - elist handle to get element from
* uint16 index - Plaintext index position to get element at
Returns:
* euint256 or ebool - The encrypted value at the specified index
## GetOr
`getOr(list, i, default)` return hidden element at hidden position. Index can be either encrypted or plaintext.
Returns a handle to the hidden element if the index is within range, otherwise returns the default value.
Example usage:
```solidity theme={null}
function listGetOr(bytes memory ctIndex, bytes memory ctDefaultValue)
public
payable
returns (euint256)
{
require(msg.value >= inco.getFee() * 2, "Fee not paid");
euint256 index = e.newEuint256(ctIndex, msg.sender);
euint256 defaultValue = e.newEuint256(ctDefaultValue, msg.sender);
euint256 res = e.getOr(list, index, defaultValue);
e.allow(res, msg.sender);
return res;
}
// [5, 10].getOr(1, 0) == 10
```
Arguments:
* elist list - elist handle to get element at
* euint256/uint256 index - Index position to get element at. Can be either plaintext or encrypted.
* euint256/ebool default - A default element value to be returned if index is out of range. Must match the elist type.
Returns:
* euint256/ebool - The encrypted value at the specified index, or the default value if out of range
## Set
`set(list, i, value)` replaces an element at hidden index and returns a new modified list. Index can be either plaintext or encrypted.
Note: If the encrypted index is out of range, the operation is ignored and the same list is returned (although with a new handle, in order to not leak information).
If the plaintext index is out of range, it will revert instead.
Example usage:
```solidity theme={null}
elist myList = e.newEList(ETypes.Uint256);
elist myNewList1 = e.append(myList, e.asEuint256(5));
elist myNewList2 = e.append(myNewList1, e.asEuint256(10));
euint256 index = e.asEuint256(1);
euint256 newValue = e.asEuint256(2);
euint256 ten = e.set(myNewList2, index, newValue);
// [5, 10].set(1, 2) == [5, 2]
```
Arguments:
* elist A - elist handle to modify element in
* euint256/uint256 i - index position of element to modify. Can be either plaintext or encrypted.
* euint256/ebool B - element value to be changed if index is within range. Element will be appended to the list if the index is out of range. Must match the elist type.
Returns:
* Elist - a new elist handle
## Concat
`concat(list_a, list_b)` concatenates two elists into one, returns a new concatenated elist. The length of the new list will be length(list1)+length(list2)
Example usage:
```solidity theme={null}
elist myList = e.newEList(ETypes.Uint256);
elist myNewList1 = e.append(myList, e.asEuint256(5));
elist myNewList2 = e.append(myNewList1, e.asEuint256(10));
elist jointList = e.concat(myNewList2, myNewList2);
// [5, 10].concat([5, 10]) == [5, 10, 5, 10]
```
Arguments:
* elist list\_a - elist handle to be prepended
* elist list\_b - elist handle to be appended
Returns:
* Elist - a new elist handle containing elements from both A and B
## Slice
`slice(list, start, end)` is like in any other language that takes in start and end both in plaintext. Returns a new sliced list of length "end-start".
If start and end are out of bounds, it will revert. The end index must be greater than the start index.
Example usage:
```solidity theme={null}
elist myList = e.newEList(ETypes.Uint256);
elist myNewList1 = e.append(myList, e.asEuint256(5));
elist myNewList2 = e.append(myNewList1, e.asEuint256(10));
elist myNewList3 = e.append(myNewList2, e.asEuint256(15));
elist slicedList = e.slice(myNewList3, 1, 3);
// [5, 10, 15].slice(1, 3) == [10, 15]
```
Arguments:
* elist A - elist handle to be sliced
* uint16 start - Start index of the slice, in plaintext.
* uint16 end - End index of the slice, in plaintext. Must be greater than start and within the bounds of the list length.
Returns:
* Elist - a new sliced list with a new length of "end-start"
## SliceLen
`sliceLen(list, E(start), len, defaultValue)` is a variant of slice() but allows to slice at some hidden index specifying a length instead of end position. Returns a new sliced list of the specified length.
Note that if the encrypted start position is out of bounds, the resulting list will be filled with the provided default value.
Example usage:
```solidity theme={null}
function listSlice(bytes memory ctStart, uint16 len, bytes memory ctDefaultValue)
public
payable
returns (elist)
{
require(msg.value >= inco.getFee() * 2, "Fee not paid");
euint256 start = e.newEuint256(ctStart, msg.sender);
euint256 defaultValue = e.newEuint256(ctDefaultValue, msg.sender);
list = e.sliceLen(list, start, len, defaultValue);
e.allow(list, address(this));
e.allow(list, msg.sender);
return list;
}
// [5, 10, 15].sliceLen(1, 2, 0) == [10, 15]
```
Arguments:
* elist list - elist handle to be sliced
* euint256 start - Encrypted start index of the slice
* uint16 len - Length of the desired slice
* euint256/ebool defaultValue - Default value to use if start position is out of bounds. Must match the elist type.
Returns:
* elist - a new sliced list with the specified length
## Range
`range(start, end, type)` creates a new list (or a "set") and populates it with ordered values from within range. The length of the new list will be equal to "end-start".
Example usage:
```solidity theme={null}
elist myList = e.range(0, 5, ETypes.Uint256);
// myList = E([0, 1, 2, 3, 4])
```
Arguments:
* uint16 start - Start value of the range, inclusive.
* uint16 end - End of the range, exclusive. Must be greater than start and fit within the bit width of the listType argument.
* ETypes listType - Type of each element in the resulting list.
Returns:
* Elist - a new elist handle containing elements from start to end-1 with the length of "end-start"
## Reverse
`reverse(list)` reverses elements in a list, first element becomes last, and so on.
Example usage:
```solidity theme={null}
elist myList = e.newEList(ETypes.Uint256);
elist myNewList1 = e.append(myList, e.asEuint256(5));
elist myNewList2 = e.append(myNewList1, e.asEuint256(10));
elist reversedList = e.reverse(myNewList2);
// [5, 10].reverse() == [10, 5]
```
Arguments:
* elist A - elist handle to be reversed
Returns:
* Elist - a new elist handle with elements in reverse order
## Shuffle
`shuffle(list)` deterministically shuffles elements within a list, returning a new shuffled list with the same length. This operation requires fee payment.
Example usage:
```solidity theme={null}
function listShuffle() public payable returns (elist) {
require(msg.value >= inco.getEListFee(e.length(list), ETypes.Uint256), "Fee not paid");
list = e.shuffle(list);
e.allow(list, address(this));
e.allow(list, msg.sender);
return list;
}
// [5, 10].shuffle() could return [10, 5] or [5, 10] randomly
```
Arguments:
* elist list - elist handle to be shuffled
Returns:
* elist - a new elist handle with elements shuffled where each element is equally likely to be in any position in the new list.
## ShuffledRange
`shuffledRange(start, end, type)` is a convenience function combining range() and shuffle() from example above into one function. It creates a range of elements from start to end, unlike range() the resulting elist is unordered and completely random. This operation requires fee payment.
Example usage:
```solidity theme={null}
function listShuffledRange(uint16 start, uint16 end) public payable returns (elist) {
require(msg.value >= 2*inco.getEListFee(end - start, ETypes.Uint256), "Fee not paid");
elist newRangeList = e.shuffledRange(start, end, ETypes.Uint256);
e.allow(newRangeList, address(this));
e.allow(newRangeList, msg.sender);
return newRangeList;
}
// shuffledRange(1, 53, ETypes.Uint256) = E([42, 7, 19, 33, ...])
```
Arguments:
* uint16 start - Start value of the range, inclusive.
* uint16 end - End of the range, exclusive. Must be greater than start.
* ETypes listType - Type of each element in the resulting list.
Returns:
* elist - a new elist handle containing elements from start to end-1 with the length of "end-start" in a random order.
Since suffledRange is a convenience function that calls range() and shuffle() separately, it would consume twice the fee of regular range.
## Reveal
`reveal(list)` makes all elements in the elist publicly readable without requiring a wallet signature. This is useful when you want to expose results to anyone without the overhead of TEE decryption.
Revealing an elist is irreversible — once revealed, all current and future viewers can read the plaintext values without any authentication.
Example usage:
```solidity theme={null}
function revealResults() public {
e.reveal(list);
}
```
After calling `reveal()`, any address can read the values via the JS SDK using `eListAttestedReveal` without needing a wallet signature.
Arguments:
* elist list - The elist handle to reveal
Returns:
* (none)
## Submitting EList Decryption Attestation On-Chain
After decrypting an elist off-chain, you can submit the proof on-chain so your contract can act on the plaintext values. Use `e.verifyEListDecryption()` to validate the TEE-produced attestation.
```solidity theme={null}
import {euint256, ebool, e, inco, elist, ETypes, ElementAttestationWithProof} from "@inco/lightning/src/Lib.sol";
function submitDecryptionResult(
elist encryptedList,
ElementAttestationWithProof[] calldata proofElements,
bytes32 proof,
bytes[] calldata signatures
) external {
require(
e.verifyEListDecryption(encryptedList, proofElements, proof, signatures),
"Invalid attestation"
);
// proofElements[i].value contains the i-th plaintext element
for (uint256 i = 0; i < proofElements.length; i++) {
_processElement(proofElements[i].value);
}
}
```
Arguments:
* elist elistHandle - The elist handle whose decryption is being attested
* ElementAttestationWithProof\[] proofElements - One entry per element (see below)
* bytes32 proof - Merkle root or aggregated proof from the TEE
* bytes\[] signatures - Covalidator signatures over the proof
Returns:
* bool - `true` if the attestation is valid, reverts or returns `false` otherwise
### ElementAttestationWithProof
Each element in the `proofElements` array is one of two modes:
```solidity theme={null}
struct ElementAttestationWithProof {
bytes32 pairHash; // non-zero: privacy mode — value stays hidden
bytes32 commitment; // non-zero (with value): transparency mode
bytes32 value; // plaintext value (transparency mode only)
}
```
**Privacy mode** (`pairHash != 0`): The element's plaintext value is not included. The TEE provides a pre-computed hash that proves the element was included in the elist without revealing its value. Use this for elements your contract does not need to read.
**Transparency mode** (`pairHash == 0`, `commitment` and `value` set): The plaintext `value` is included alongside a commitment that binds it to the ciphertext. Use this for elements your contract needs to act on.
You can mix both modes in a single submission — for example, reveal only the top-scored entry in an encrypted leaderboard while keeping all other entries hidden.
### Partial EList Submission
You do not need to submit all elements at once. Provide the unsubmitted elements as pre-computed `pairHash` values (privacy mode) so the TEE can still verify the overall proof integrity:
```solidity theme={null}
// Submit only element at index 2; hide the rest
ElementAttestationWithProof[] memory proofElements = new ElementAttestationWithProof[](5);
proofElements[0] = ElementAttestationWithProof({ pairHash: hash0, commitment: 0, value: 0 });
proofElements[1] = ElementAttestationWithProof({ pairHash: hash1, commitment: 0, value: 0 });
proofElements[2] = ElementAttestationWithProof({ pairHash: 0, commitment: commitment2, value: value2 });
proofElements[3] = ElementAttestationWithProof({ pairHash: hash3, commitment: 0, value: 0 });
proofElements[4] = ElementAttestationWithProof({ pairHash: hash4, commitment: 0, value: 0 });
bool valid = e.verifyEListDecryption(encryptedList, proofElements, proof, signatures);
```
The `pairHash` values for hidden elements are returned by the JS SDK alongside the transparency-mode elements when you call `eListAttestedDecrypt`.
# Error Reference
Source: https://docs.inco.org/guide/error-reference
Custom errors thrown by the Inco Lightning smart contracts
This page lists every custom error that a dApp developer may encounter when building on Inco Lightning.
***
## Access Control
### `SenderNotAllowedForHandle`
```solidity theme={null}
error SenderNotAllowedForHandle(bytes32 handle, address sender);
```
The caller does not have read or use permission on this handle. Grant access first with `e.allow(handle, address)` or `inco.allow(handle, address)`.
### `SharerNotAllowedForHandle`
```solidity theme={null}
error SharerNotAllowedForHandle(bytes32 handle, address sharer);
```
The sharer does not hold permission on this handle and therefore cannot delegate access to others.
### `HandleAlreadyExists`
```solidity theme={null}
error HandleAlreadyExists(bytes32 handle);
```
An attempt was made to register a handle that already exists in the access control list.
### `ProofVerificationFailed`
```solidity theme={null}
error ProofVerificationFailed(address verifyingContract, bytes4 callFunction, bytes argData);
```
The session verifier contract did not return `ALLOWANCE_GRANTED_MAGIC_VALUE`. The allowance proof failed — check that the voucher is valid and has not expired or been revoked.
### `InvalidVoucherWarning`
```solidity theme={null}
error InvalidVoucherWarning();
```
Thrown when a voucher's warning field does not match the required warning text
### `InvalidVoucherSignature`
```solidity theme={null}
error InvalidVoucherSignature(address signer, bytes32 digest, bytes signature);
```
The allowance voucher signature does not match the sharer's address.
### `InvalidVoucherSessionNonce`
```solidity theme={null}
error InvalidVoucherSessionNonce(bytes32 providedSessionNonce, bytes32 activeSessionNonce);
```
The voucher was signed under a session nonce that no longer matches the sharer's active nonce. The voucher has been revoked via `updateActiveVouchersSessionNonce`.
### `InvalidVerifyingContract`
```solidity theme={null}
error InvalidVerifyingContract();
```
The voucher specifies a zero-address verifying contract, which is not allowed.
***
## Encrypted Input
### `InvalidInputVersion`
```solidity theme={null}
error InvalidInputVersion(uint16 version);
```
The ciphertext input uses an unsupported version number.
### `InputLengthTooShort`
```solidity theme={null}
error InputLengthTooShort(uint256 length);
```
The input bytes are too short to be a valid encrypted input.
### `ExternalHandleDoesNotMatchComputedHandle`
```solidity theme={null}
error ExternalHandleDoesNotMatchComputedHandle(
bytes32 externalHandle,
bytes32 computedHandle,
uint256 chainId,
address aclAddress,
address userAddress,
address contractAddress,
uint16 version
);
```
The handle supplied by the user does not match the handle derived from the ciphertext content. This indicates the input data was constructed incorrectly or tampered with.
***
## Decryption & Attestation
### `HandleMismatch`
```solidity theme={null}
error HandleMismatch();
```
A decryption or computation attestation was submitted for a different handle than the one the contract expects. Always verify `decryption.handle` explicitly before accepting an attestation — see [Best Practices](./best-practices).
### `InvalidTEEAttestation`
```solidity theme={null}
error InvalidTEEAttestation();
```
The attestation signatures are invalid or fail TEE verification.
### `UnexpectedDecryptedValue`
```solidity theme={null}
error UnexpectedDecryptedValue();
```
The decrypted value does not match the expected value in a computation attestation.
### `AttestationsSignaturesLengthMismatch`
```solidity theme={null}
error AttestationsSignaturesLengthMismatch(uint256 attestationsLength, uint256 signaturesLength);
```
The `attestations` and `signatures` arrays passed to a batch verification call have different lengths.
***
## EList Operations
### `IndexOutOfRange`
```solidity theme={null}
error IndexOutOfRange(uint16 i, uint16 len);
```
An index access on an elist is beyond the list bounds.
### `SliceOutOfRange`
```solidity theme={null}
error SliceOutOfRange(uint16 start, uint16 end, uint16 len);
```
The requested slice boundaries exceed the list length.
### `InvalidRange`
```solidity theme={null}
error InvalidRange(uint16 start, uint16 end);
```
The start index is greater than or equal to the end index.
### `ListRangeExceedsType`
```solidity theme={null}
error ListRangeExceedsType(uint16 end, ETypes listType);
```
The end value of a range operation does not fit within the bit width of the specified list type.
### `ZeroLength`
```solidity theme={null}
error ZeroLength();
```
An operation that requires a non-empty list received an empty one.
### `ListTooLong`
```solidity theme={null}
error ListTooLong(uint32 provided, uint16 max);
```
The list exceeds the maximum allowed length.
### `ListTypeMismatch`
```solidity theme={null}
error ListTypeMismatch(ETypes lhs, ETypes rhs);
```
Two lists have incompatible element types (for example, concatenating a `Uint256` list with a `Bool` list).
### `UnsupportedListType`
```solidity theme={null}
error UnsupportedListType(ETypes listType);
```
The specified element type is not supported for this elist operation.
***
## Type System
### `UnsupportedType`
```solidity theme={null}
error UnsupportedType(ETypes actual);
```
The handle type is not supported for this operation.
### `UnexpectedType`
```solidity theme={null}
error UnexpectedType(ETypes actual, bytes32 expectedTypes);
```
The handle type does not match any of the expected types. `expectedTypes` is a bitmask of the valid types.
### `SameTypeCast`
```solidity theme={null}
error SameTypeCast(ETypes t);
```
A cast was attempted from a type to itself. Use a different target type.
***
## Fees
### `FeeNotPaid`
```solidity theme={null}
error FeeNotPaid();
```
The `msg.value` sent with the transaction was insufficient to cover the required fee. Query `inco.getFee()` to determine the correct amount before calling.
### `FeeWithdrawalFailed`
```solidity theme={null}
error FeeWithdrawalFailed();
```
The ETH transfer during fee withdrawal failed.
### `NoFeesToWithdraw`
```solidity theme={null}
error NoFeesToWithdraw();
```
A withdrawal was attempted when there are no accumulated fees available.
***
## ETH Transfer
### `EthInboundTransferUnsupported`
```solidity theme={null}
error EthInboundTransferUnsupported();
```
Plain ETH transfers directly to the `IncoLightning` contract are rejected. Always attach `msg.value` to a specific function call to pay fees.
### `RefundFailed`
```solidity theme={null}
error RefundFailed();
```
An ETH refund transfer back to the caller failed.
### `ReentrantCall`
```solidity theme={null}
error ReentrantCall();
```
A reentrant call was detected and blocked.
# Access Control
Source: https://docs.inco.org/guide/guide-access-control
Fully programmable access control over encrypted data
The access control logic is fully programmable and onchain.
Who has the right to decrypt and see a give ciphertext is visible onchain.
To give access to an account (i.e an address) to a ciphertext, you can use the `e.allow` function.
This will grant the address permanent access to seeing, publicly decrypting and computing over the ciphertext.
Since handles are immutable, sharing access to a variable to an account only grants access to the current value of the variable.
Whenever the variable is updated, the handle changes and the access to the new handle must be granted again.
For example, ou can share your current balance with an address, but if you update your balance, the address will not be able to see the new value.
Example usage from the confidential token contract:
```Solidity theme={null}
function _transfer(address to, euint256 value) internal returns (ebool success) {
// ... some previous logic
// allow the sender to see its new balance
senderNewBalance.allow(msg.sender);
// allow the receiver to see its new balance
receiverNewBalance.allow(to);
// allow this contract to be able to compute over the new balances in future transfers
senderNewBalance.allowThis();
receiverNewBalance.allowThis();
// let the caller know if the transfer was successful
success.allow(msg.sender);
}
```
`e.allowThis(value)` is an alias for `e.allow(value, address(this))`.
A common mistake is to forget to call `allowThis` on a variable after updating it.
This will result in the contract being unable to compute over the variable in future transactions.
Always call `e.allowThis` after updating a variable, if this variable will be used in your contract again.
### Transient Allowance
`e.transientAllow` is not yet available in the SDK, but coming very soon.
A transient allowance is an allowance that is valid only for the current transaction.
All results of operations such as `e.add` are transiently allowed to be decrypted by the contract who called the operation.
That is why contracts can perform back to back operations using results of previous operations.
But since this allowance is transient, calling `e.allowThis` is necessary to allow the contract to compute over the result in future transactions.
### How to reason about access
The correct way to think of access control is to consider that each account (i.e any address of EOA/contract/smart wallet)
that received access to a ciphertext at some point, either transiently or permanently,
knows its value, has stored it, and may compute over it.
Note that once the access over a ciphertext is shared, the receiving account may share it with any other account, or publicly decrypt it.
Be very mindful of the access you grant over your ciphertexts in your apps, and don't consider transient allowances to be "safer" in any way than permanent ones.
# Handles
Source: https://docs.inco.org/guide/handles
Unique Identifier for an immutable piece of hidden data
## E-Types
At the top of the confidential token implementation, we can see that we are importing new types of variables:
```Solidity theme={null}
import {euint256, ebool, eaddress, e} from "@inco/lightning/src/Lib.sol";
```
`euint256`, `ebool`, and `eaddress` are the hidden counterparts of `uint256`, `bool`, and `address`, respectively.
They are used to represent hidden values in the contract.
The `e`- types are the hidden counterparts of the standard types in Solidity.
In our token example, the user balances are notably represented as `euint256`:
```Solidity theme={null}
mapping(address => euint256) public balanceOf;
```
If we look into Inco's library, we can see how `euint256` and `ebool` are defined:
```Solidity theme={null}
type euint256 is bytes32;
type ebool is bytes32;
type eaddress is bytes32;
```
If we try looking up on a block explorer the raw value returned by calling `balanceOf`, we will get something like:
```
0xa8d84064218bfc979af10dccc8153c9ab8a15068c3d64cb63927aca8ad1a3c9c
```
This gibberish value gives us no information about the actual balance of the user.
## What is a Handle?
A handle is a unique identifier for an immutable piece of hidden data.
In our token example, the balance of each user is represented as a handle, `ebool success`, `euint256 value`, etc. are also handles.
The onchain smart contract is manipulating identifiers for a piece of hidden data (a balance, a boolean, etc.),
and the actual data is safely stored offchain in an encrypted manner.
Whenever an operation is performed over encrypted data types, the result is also a handle, like so:
```Solidity theme={null}
euint256 senderNewBalance = balanceOf[msg.sender].sub(transferredValue);
```
A handle is immutable. If we were to reassigning a variable like so:
```Solidity theme={null}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(transferredValue);
```
`balanceOf[msg.sender]` would get assigned a new handle.
It is important to keep in mind that the handle representing the old balance still exists,
and still corresponds to the encrypted value of the old balance, even if the contract is not keeping track of it.
We will see later in this guide that the value of handles are never lost and can still be accessed.
From Inco's standpoint, handles get created but never deleted.
# Inputs
Source: https://docs.inco.org/guide/input
How to input external values and convert them to handles
```Solidity theme={null}
import {euint256, ebool, eaddress, e} from "@inco/lightning/src/Lib.sol";
using e for *;
```
### Case 1: the value comes from an offchain source
In the confidential transfer example, the first external method is meant to be called by an EOA / Smart account.
It is using `newEuint256` to convert the input value into a handle.
```Solidity theme={null}
function transfer(
address to,
bytes memory valueInput
) external payable returns (ebool) {
// Muliplied with one cause we consumed only one ciphertext i.e called `newEuint256` once
require(msg.value >= inco.getFee() * 1, "Fee Not Paid");
// This call needs the above fee otherwise it will fail
euint256 value = valueInput.newEuint256(msg.sender);
// stuff
}
```
`newEuint256` takes two arguments, the encrypted input value (in the form of `bytes`) and the address of the account doing the input (here `msg.sender`).
This account should always be the one that created the input, it will be given decryption right over the handle.
Passing another address than the user doing the input would be a malicious implementation.
Similarly, `newEaddress` can be used to convert encrypted address inputs into handles:
```Solidity theme={null}
function setAuthorizedAddress(
bytes memory addressInput
) external payable {
require(msg.value >= inco.getFee() * 1, "Fee Not Paid");
eaddress authorizedAddr = addressInput.newEaddress(msg.sender);
// stuff
}
```
`newEaddress` works identically to `newEuint256` but creates an `eaddress` handle instead of an `euint256` handle. It requires the same fee payment and follows the same security principles regarding the originating account.
For boolean inputs, `newEbool` can be used to convert encrypted boolean inputs into handles:
```Solidity theme={null}
function setFlag(
bytes memory flagInput
) external payable {
require(msg.value >= inco.getFee() * 1, "Fee Not Paid");
ebool flag = flagInput.newEbool(msg.sender);
// stuff
}
```
`newEbool` works identically to `newEuint256` but creates an `ebool` handle instead of an `euint256` handle. It requires the same fee payment and follows the same security principles regarding the originating account.
`valueInput` has to be a ciphertext, meaning it has to be the value intended to be transferred,
encrypted in a way that Inco can understand. To do this, you can use the `encrypt` method from the [JavaScript SDK](https://docs.inco.org/js-sdk/existing-project#1-encrypt-a-value).
If the `bytes memory valueInput` is malformed, Inco will fallback to the handle default value.
The default value of `euint256` is `0`, and the default value of `ebool` is `false`.
**Note:** Consuming encrypted inputs on-chain requires paying an encryption fee per ciphertext (**newEuint256**).
Ensure `msg.value >= inco.getFee() × ciphertextCount`, otherwise the call will revert.
After `newEuint256` has been used, the resulting handle can be used immediately, there is no need
for Inco to issue a confirmation to start using it in the contract logic. Inco will decrypt
the corresponding ciphertext safely inside its TEE after the transaction has been included onchain.
All operations onchain are performed virtually over identifiers, and reproduced over the actual
values by Inco asynchronously. We call this model "symbolic execution".
One could try to reuse the same ciphertext as another user to gain decryption
access over it. Our JS SDK embeds context information in the ciphertext
(originating account, chain, contract), and the value of the created handle
will fallback to the default if it is used in another context.
### Case 2 : the value comes from a variable
A known value can be turned into a handle using the `asEuint256` method.
This is sometimes called performing a "trivial encrypt" because the resulting handle will be of a known value.
We can see it in the constructor of the token example:
```Solidity theme={null}
constructor() {
balanceOf[msg.sender] = uint256(1000 * 1e9).asEuint256();
}
```
Anyone can see that the initial value of `balanceOf[msg.sender]` is `1000 * 1e9`,
but after the deployer sends a few transfers, its balance will be unknown to the public.
Similarly, known boolean values can be converted using `asEbool`:
```Solidity theme={null}
constructor() {
isActive = true.asEbool();
}
```
# Concepts Guide Introduction
Source: https://docs.inco.org/guide/intro
Walkthrough all the concepts you need to know to get started with Inco
## Welcome
This guide will get you up to speed on all the concepts you need to know to develop your first confidential dapp.
Throughout this guide, we will be using several examples, the most common one being a confidential token.
A confidential token behaves similarly to a regular ERC20 token, but the balances of the holders, and transfer amounts are hidden from the public.
Here is the full code of a simple confidential token contract:
```Solidity theme={null}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
import {euint256, ebool, e} from "@inco/lightning/src/Lib.sol";
contract SimpleConfidentialToken {
using e for *;
mapping(address => euint256) public balanceOf;
constructor() {
balanceOf[msg.sender] = uint256(1000 * 1e9).asEuint256();
}
function transfer(
address to,
bytes memory valueInput
) external returns (ebool) {
euint256 value = valueInput.newEuint256(msg.sender);
return _transfer(to, value);
}
function transfer(
address to,
euint256 value
) public returns (ebool success) {
require(
msg.sender.isAllowed(value),
"SimpleConfidentialToken: unauthorized value handle access"
);
return _transfer(to, value);
}
function _transfer(
address to,
euint256 value
) internal returns (ebool success) {
success = balanceOf[msg.sender].ge(value);
euint256 transferredValue = success.select(
value,
uint256(0).asEuint256()
);
euint256 senderNewBalance = balanceOf[msg.sender].sub(transferredValue);
euint256 receiverNewBalance = balanceOf[to].add(transferredValue);
balanceOf[msg.sender] = senderNewBalance;
balanceOf[to] = receiverNewBalance;
senderNewBalance.allow(msg.sender);
receiverNewBalance.allow(to);
senderNewBalance.allowThis();
receiverNewBalance.allowThis();
}
}
```
Continue this guide to understand how this code works and its concepts.
# Operations
Source: https://docs.inco.org/guide/operations
Compute over private state
Inco exposes mathematical and logical operations over encrypted data.
Note that for each operation that takes 2 arguments (i.e binary types below), you can use either an e-type or a regular
variable as the first or second argument. Each operation returns a single e-type as result.
Under the hood, all operations are performing a call to the Inco contract
singleton. The Inco contract checks access control rules and emits an event
for each operation
### Example usage
```Solidity theme={null}
euint256 a = e.asEuint256(2);
euint256 b = e.asEuint256(3);
euint256 c = a.add(b); // c = 5 (encrypted)
```
### Supported math operations
All these operations return an `euint256`.
| Name | Function | Type |
| -------------- | -------- | ------ |
| Addition | `e.add` | Binary |
| Subtraction | `e.sub` | Binary |
| Multiplication | `e.mul` | Binary |
| Division | `e.div` | Binary |
| Remainder | `e.rem` | Binary |
| BitAnd | `e.and` | Binary |
| BitOr | `e.or` | Binary |
| BitXor | `e.xor` | Binary |
| Shift Right | `e.shr` | Binary |
| Shift Left | `e.shl` | Binary |
| Rotate Right | `e.rotr` | Binary |
| Rotate Left | `e.rotl` | Binary |
### Supported comparison operations
| Name | Function | Type | Returns |
| --------------------- | -------- | ------ | -------- |
| Equal | `e.eq` | Binary | ebool |
| Not equal | `e.ne` | Binary | ebool |
| Greater than or equal | `e.ge` | Binary | ebool |
| Greater than | `e.gt` | Binary | ebool |
| Less than or equal | `e.le` | Binary | ebool |
| Less than | `e.lt` | Binary | ebool |
| Min | `e.min` | Binary | euint256 |
| Max | `e.max` | Binary | euint256 |
| Not | `e.not` | Unary | ebool |
### Random number generation
```Solidity theme={null}
euint256 randomNumber = e.rand();
euint256 boundedRandom = e.randBounded(100); // Random number in [0, 100)
euint256 boundedRandomEncrypted = e.randBounded(encryptedUpperBound); // With encrypted upper bound
```
| Name | Function | Type | Returns |
| -------------- | ------------------------------------ | ----- | -------- |
| Random | `e.rand()` | Unary | euint256 |
| Random Bounded | `e.randBounded(uint256 upperBound)` | Unary | euint256 |
| Random Bounded | `e.randBounded(euint256 upperBound)` | Unary | euint256 |
### Type conversion functions
Convert between regular types and encrypted types, or between different encrypted types.
```Solidity theme={null}
euint256 a = e.asEuint256(42);
ebool b = e.asEbool(true);
eaddress c = e.asEaddress(0x123...);
ebool d = e.asEbool(encryptedUint); // Cast from euint256
euint256 e = e.asEuint256(encryptedBool); // Cast from ebool
```
| Name | Function | Type | Returns |
| ---------------------- | ------------------------- | ----- | -------- |
| Convert to euint256 | `e.asEuint256(uint256 a)` | Unary | euint256 |
| Convert to ebool | `e.asEbool(bool a)` | Unary | ebool |
| Convert to eaddress | `e.asEaddress(address a)` | Unary | eaddress |
| Cast euint256 to ebool | `e.asEbool(euint256 a)` | Unary | ebool |
| Cast ebool to euint256 | `e.asEuint256(ebool a)` | Unary | euint256 |
### Reveal functions
Reveal encrypted values (decrypt and make public).
```Solidity theme={null}
e.reveal(encryptedUint);
e.reveal(encryptedBool);
e.reveal(encryptedAddress);
```
| Name | Function | Type | Returns |
| ------ | ---------------------- | ----- | ------- |
| Reveal | `e.reveal(euint256 a)` | Unary | void |
| Reveal | `e.reveal(ebool a)` | Unary | void |
| Reveal | `e.reveal(eaddress a)` | Unary | void |
### Additional type support
**Comparison operations** (`e.eq` and `e.ne`) also support `eaddress` comparisons in addition to `euint256`.
**Bitwise operations** (`e.and`, `e.or`, `e.xor`) also support `ebool` operations in addition to `euint256`.
# Verifying Attestations
Source: https://docs.inco.org/guide/verifying-attestations
Verify attested decrypt, reveal, and compute responses in Solidity.
Attested flows (`attestedDecrypt`, `attestedCompute`, `attestedReveal`) allow wallets to convert an encrypted handle into plaintext or a computed result. This page shows how to plug those responses into Solidity, verify the covalidator signatures, and bind attestations to the expected handles.
## DecryptionAttestation Structure
```solidity theme={null}
struct DecryptionAttestation {
bytes32 handle;
bytes32 value;
}
```
## Attested Decrypt
**Off-chain (JS SDK):**
```typescript theme={null}
import { getContract, toHex } from "viem";
import { gatedAccessAbi } from "./abi";
import { walletClient } from "./client";
// 1. Create contract instance
const contract = getContract({
address: "0x...", // Replace with your deployed contract address
abi: gatedAccessAbi,
client: walletClient,
});
// 2. Use attested decrypt and call contract
const results = await zap.attestedDecrypt(walletClient, [handleHex]);
const { handle, plaintext, covalidatorSignatures } = results[0];
const value = toHex(plaintext.value, { size: 32 });
const signatures = covalidatorSignatures.map((s) => toHex(s));
await contract.write.gatedAction([
{
handle,
value,
},
signatures,
]);
```
```typescript theme={null}
import { createWalletClient, http } from "viem";
import { baseSepolia } from "viem/chains";
import { Lightning } from "@inco/lightning-js/lite";
export const walletClient = createWalletClient({
chain: baseSepolia,
transport: http(),
});
// for Base mainnet: Lightning.baseMainnet()
// recommended: pass your own RPC URLs (otherwise viem's public RPC is used)
export const zap = await Lightning.baseSepoliaTestnet({
hostChainRpcUrls: ['https://your-rpc-url'],
});
```
```typescript theme={null}
export const gatedAccessAbi = [
{
inputs: [
{
components: [
{
internalType: "bytes32",
name: "handle",
type: "bytes32",
},
{
internalType: "bytes32",
name: "value",
type: "bytes32",
},
],
internalType: "struct DecryptionAttestation",
name: "decryption",
type: "tuple",
},
{
internalType: "bytes[]",
name: "signatures",
type: "bytes[]",
},
],
name: "gatedAction",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
] as const;
```
**On-chain (Solidity):**
```solidity theme={null}
import {DecryptionAttestation} from "@inco/lightning/src/lightning-parts/DecryptionAttester.types.sol";
import {inco, ebool} from "@inco/lightning/src/Lib.sol";
import {asBool} from "@inco/lightning/src/shared/TypeUtils.sol";
contract GatedAccess {
mapping(address => ebool) internal userAllowed;
function gatedAction(
DecryptionAttestation memory decryption,
bytes[] memory signatures
) external {
require(
inco.incoVerifier().isValidDecryptionAttestation(decryption, signatures),
"Invalid signature"
);
require(ebool.unwrap(userAllowed[msg.sender]) == decryption.handle, "Handle mismatch");
require(asBool(decryption.value) == true, "Not allowed");
// proceed
}
}
```
***
## Attested Reveal
**Off-chain (JS SDK):**
```typescript theme={null}
import { getContract, toHex } from "viem";
import { revealAbi } from "./abi";
import { walletClient } from "./client";
// 1. Create contract instance
const contract = getContract({
address: "0x...", // Replace with your deployed contract address
abi: revealAbi,
client: walletClient,
});
// 2. Use attested reveal and call contract
const results = await zap.attestedReveal([handleHex]);
const { handle, plaintext, covalidatorSignatures } = results[0];
const value = toHex(plaintext.value, { size: 32 });
const signatures = covalidatorSignatures.map((s) => toHex(s));
await contract.write.submitRevealedValue([
{
handle,
value,
},
signatures,
]);
```
```typescript theme={null}
import { createWalletClient, http } from "viem";
import { baseSepolia } from "viem/chains";
import { Lightning } from "@inco/lightning-js/lite";
export const walletClient = createWalletClient({
chain: baseSepolia,
transport: http(),
});
// for Base mainnet: Lightning.baseMainnet()
// recommended: pass your own RPC URLs (otherwise viem's public RPC is used)
export const zap = await Lightning.baseSepoliaTestnet({
hostChainRpcUrls: ['https://your-rpc-url'],
});
```
```typescript theme={null}
export const revealAbi = [
{
inputs: [
{
components: [
{
internalType: "bytes32",
name: "handle",
type: "bytes32",
},
{
internalType: "bytes32",
name: "value",
type: "bytes32",
},
],
internalType: "struct DecryptionAttestation",
name: "decryption",
type: "tuple",
},
{
internalType: "bytes[]",
name: "signatures",
type: "bytes[]",
},
],
name: "submitRevealedValue",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
] as const;
```
**On-chain (Solidity):**
```solidity theme={null}
import {DecryptionAttestation} from "@inco/lightning/src/lightning-parts/DecryptionAttester.types.sol";
import {inco, e, ebool, euint256} from "@inco/lightning/src/Lib.sol";
import {asBool} from "@inco/lightning/src/shared/TypeUtils.sol";
contract GatedAccess {
using e for *;
euint256 someHandle;
function submitRevealedValue(
DecryptionAttestation memory decryption,
bytes[] memory signatures
) external {
require(
inco.incoVerifier().isValidDecryptionAttestation(
decryption,
signatures
),
"Invalid signature"
);
require(
euint256.unwrap(someHandle) == decryption.handle,
"Handle mismatch"
);
uint256 revealedValue = uint256(decryption.value);
// use revealedValue
}
}
```
***
## Attested Compute
Attested compute first produces a **computed handle** (for example
`handleB = handleA.ge(700)`), and then returns a decryption attestation
**for that result handle**. On-chain you verify that:
* the attestation is valid,
* the `decryption.handle` matches the expected computed handle (e.g. `handleB`),
* and the decrypted value of `handleB` satisfies your predicate.
**Off-chain (JS SDK):**
```typescript theme={null}
import { getContract, toHex } from "viem";
import { creditCheckAbi } from "./abi";
import { walletClient } from "./client";
// 1. Create contract instance
const contract = getContract({
address: "0x...", // Replace with your deployed contract address
abi: creditCheckAbi,
client: walletClient,
});
// 2. Read encrypted credit score handle
const creditScoreHandle = await contract.read.userCreditScore([
walletClient.account.address,
]);
// 3. Off-chain check: is credit score >= 700?
const { handle, plaintext, covalidatorSignatures } = await zap.attestedCompute(
walletClient,
creditScoreHandle,
AttestedComputeSupportedOps.Ge,
700n
);
const value = toHex(plaintext.value, { size: 32 }); // always boolean
const signatures = covalidatorSignatures.map((s) => toHex(s));
await contract.write.submitCreditCheck([
{
handle,
value,
},
signatures,
]);
```
```typescript theme={null}
import { createWalletClient, http } from "viem";
import { baseSepolia } from "viem/chains";
import { Lightning } from "@inco/lightning-js/lite";
export const walletClient = createWalletClient({
chain: baseSepolia,
transport: http(),
});
// for Base mainnet: Lightning.baseMainnet()
// recommended: pass your own RPC URLs (otherwise viem's public RPC is used)
export const zap = await Lightning.baseSepoliaTestnet({
hostChainRpcUrls: ['https://your-rpc-url'],
});
```
```typescript theme={null}
export const creditCheckAbi = [
{
inputs: [
{
components: [
{
internalType: "bytes32",
name: "handle",
type: "bytes32",
},
{
internalType: "bytes32",
name: "value",
type: "bytes32",
},
],
internalType: "struct DecryptionAttestation",
name: "decryption",
type: "tuple",
},
{
internalType: "bytes[]",
name: "signatures",
type: "bytes[]",
},
],
name: "submitCreditCheck",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
] as const;
```
**On-chain (Solidity):**
```solidity theme={null}
import {DecryptionAttestation} from "@inco/lightning/src/lightning-parts/DecryptionAttester.types.sol";
import {inco, e, ebool, euint256} from "@inco/lightning/src/Lib.sol";
import {asBool} from "@inco/lightning/src/shared/TypeUtils.sol";
contract GatedAccess {
using e for *;
// Encrypted credit score handle stored on-chain for each user
mapping(address => euint256) internal userCreditScore;
function submitCreditCheck(
DecryptionAttestation memory decryption,
bytes[] memory signatures
) external {
// 1. Verify covalidator signatures over the attested result
require(
inco.incoVerifier().isValidDecryptionAttestation(
decryption,
signatures
),
"Invalid signature"
);
// 2. Recompute the expected "creditScore >= 700" handle on-chain
euint256 creditScore = userCreditScore[msg.sender];
require(
ebool.unwrap(creditScore.ge(700)) == decryption.handle,
"Computed handle mismatch"
);
// 3. Check that the decrypted boolean is true
require(asBool(decryption.value) == true, "Credit check failed");
// proceed with approval
}
}
```
# Inco - Confidential Computing for Web3
Source: https://docs.inco.org/home
Build confidential smart contracts. Secure, private, and scalable blockchain applications.
# Build with Inco
Inco enables developers to easily create confidential smart contracts with
private data types, operations and programmable access control.
Build new private dApps across payment, DeFi, governance, gaming and more.
Developer Friendly
Write confidential smart contracts in Solidity with our easy-to-use SDK.
Post-Quantum Secure
Build scalable applications with enterprise-grade, post-quantum security and privacy.
Confidential in a few lines
Encrypted types and operations that read like regular Solidity with
@inco/lightning, plus
@inco/lightning-js for encrypting and decrypting in your app.
```solidity theme={null}
import {e, euint256} from "@inco/lightning/src/Lib.sol";
contract Counter {
euint256 private count;
// Add an encrypted input to a running encrypted total.
function add(bytes calldata input) external {
euint256 value = input.newEuint256(msg.sender);
count = e.add(count, value);
count.allowThis();
}
}
```
Start building
Guides to take you from zero to a confidential app.
# Introduction
Source: https://docs.inco.org/introduction
Welcome to Inco!
Inco Lightning is live on Base Mainnet and Base Sepolia, with Solana Devnet support available in beta. We are actively working on making Inco Lightning available to other chains.
Inco (short for "incognito") is the confidentiality layer for existing blockchains.
# What is Inco Lightning?
Inco Lightning uses Trusted Execution Environments (TEEs) to deliver verifiable confidential compute at lightning-fast speeds. It introduces new private data types, operations, and access controls, enabling smart contracts to process sensitive data securely. No new chain, no new wallet. Just import our Solidity library and start building privacy-preserving dApps today.
# JavaScript SDK
Source: https://docs.inco.org/js-sdk
Inco Lightning JS is a javascript library that enables developers to interact with the inco protocol
## Overview
Inco Lightning JS (`@inco/lightning-js`) is a JavaScript library that enables developers to interact with the Inco protocol. It provides a comprehensive set of tools and utilities for building privacy-preserving decentralized applications.
## Getting Started
There are two main ways to start using Inco Lightning JS in your project:
Get started quickly with our NextJS template for building dApps with Inco
Learn how to integrate Inco Lightning JS into your existing JavaScript/TypeScript project
# Attested Compute
Source: https://docs.inco.org/js-sdk/attestations/attested-compute
Attested compute allows to perform a computation on a handle completely off-chain and get the decryption attestation containing decryption result and attestation.
Only handles that are allowed with e.allow() or e.reveal() can be used in computation.
The attestation can then be verified on-chain to perform certain on-chain actions, avoiding unnecessary transaction.
## Getting Started
Take this example contract that holds an encrypted credit score of a user, to determine whether they're eligible for a loan:
```solidity theme={null}
import {euint256, e, ebool, inco} from "@inco/lightning/src/Lib.sol";
import {DecryptionAttestation} from "@inco/lightning/src/lightning-parts/DecryptionAttester.types.sol";
import {asBool} from "@inco/lightning/src/shared/TypeUtils.sol";
contract TestAttestedCompute {
euint256 hiddenCreditScore;
constructor(address owner) payable {
require(msg.value == inco.getFee(), "Fee not paid");
hiddenCreditScore = e.asEuint256(800);
e.allow(hiddenCreditScore, address(this));
e.allow(hiddenCreditScore, owner);
}
function GetHandle() external returns (euint256) {
return hiddenCreditScore;
}
function SubmitCreditCheck(
DecryptionAttestation memory decryption,
bytes[] memory signatures
) external {
// Verify covalidator signatures over the attested result
require(
inco.incoVerifier().isValidDecryptionAttestation(decryption, signatures),
"Invalid signature"
);
// Recompute the expected "creditScore >= 700" handle on-chain
require(
ebool.unwrap(e.ge(hiddenCreditScore, 700)) == decryption.handle,
"Computed handle mismatch"
);
// Check that the decrypted boolean is true
require(asBool(decryption.value) == true, "Credit check failed");
// Credit check passed - proceed with loan approval
}
}
```
Presume we want to know whether the credit score is greater than or equal 700 without sending an additional transaction.
We can do that by calling attestedCompute (similar to [Attested Decrypt](../attestations/attested-decrypt)):
```JavaScript theme={null}
import { Lightning } from '@inco/lightning-js/lite';
import { getViemChain, supportedChains, type HexString } from '@inco/lightning-js';
import { AttestedComputeSupportedOps } from '@inco/lightning-js/lite';
import { createWalletClient, custom } from 'viem'
// for Base mainnet: Lightning.baseMainnet()
// recommended: pass your own RPC URLs (otherwise viem's public RPC is used)
const zap = await Lightning.baseSepoliaTestnet({
hostChainRpcUrls: ['https://your-rpc-url'],
});
//Connect to Metamask or other wallet provider
const walletClient = createWalletClient({
chain: getViemChain(supportedChains.baseSepolia),
transport: custom(window.ethereum!)
})
// Retrieve the hiddenCreditScore handle from the contract by calling GetHandle(), e.g. using viem
const hiddenCreditScore = '0x' as HexString;
// isGreaterOrEqual = hiddenCreditScore >= 700
const isGreaterOrEqual = await zap.attestedCompute(
walletClient,
hiddenCreditScore,
AttestedComputeSupportedOps.Ge,
700n,
);
const creditScoreSufficient = isGreaterOrEqual.plaintext.value; // always boolean
```
Which is equivalent to:
```solidity theme={null}
ebool creditScoreSufficient = e.ge(hiddenCreditScore, 700);
```
isGreaterOrEqual also contains a signature from covalidator attesting to the computation, which can be used to submit decryption back on-chain, even if the handle doesn't exist on chain yet.
## Supported operations
| Name | Op | Type | Returns |
| --------------------- | -------------------------------- | --------------- | ------- |
| Equal | `AttestedComputeSupportedOps.Eq` | Scalar Binary\* | bool |
| Not equal | `AttestedComputeSupportedOps.Ne` | Scalar Binary\* | bool |
| Greater than or equal | `AttestedComputeSupportedOps.Ge` | Scalar Binary\* | bool |
| Greater than | `AttestedComputeSupportedOps.Gt` | Scalar Binary\* | bool |
| Less than or equal | `AttestedComputeSupportedOps.Le` | Scalar Binary\* | bool |
| Less than | `AttestedComputeSupportedOps.Lt` | Scalar Binary\* | bool |
* Scalar binary operation - operation that takes in two operands, one of which is a handle and the second one is a number (aka scalar).
## Compute with Allowance Voucher/Session Key
Compute on a handle can be performed with a session key instead of a wallet provider using `attestedComputeWithVoucher()`, see [Allowance Voucher](../voucher/allowance-voucher).
# Attested Decrypt
Source: https://docs.inco.org/js-sdk/attestations/attested-decrypt
Attested decrypt allows authorized user to request a decryption attestation and submit plaintext back on chain.
Only handles that are allowed with `e.allow()` or `e.reveal()` can be used in decryption.
## Getting Started
Take this example contract:
```solidity theme={null}
import {euint256, e, inco} from "@inco/lightning/src/Lib.sol";
import {DecryptionAttestation} from "@inco/lightning/src/lightning-parts/DecryptionAttester.types.sol";
contract TestAttestedDecrypt {
euint256 randomNumber;
uint256 decryptedNumber;
constructor(address owner) payable {
require(msg.value == inco.getFee(), "Fee not paid");
randomNumber = e.rand();
e.allow(randomNumber, address(this));
e.allow(randomNumber, owner);
}
function GetHandle() external returns (euint256) {
return randomNumber;
}
function SubmitDecryption(
DecryptionAttestation memory decryption,
bytes[] memory signatures
) external {
require(
inco.incoVerifier().isValidDecryptionAttestation(decryption, signatures),
"Invalid Signature"
);
require(euint256.unwrap(randomNumber) == decryption.handle, "Handle mismatch");
decryptedNumber = uint256(decryption.value);
}
}
```
This contract creates a random 256bit integer and grants owner the ownership of the handle, allowing the owner to perform computations on it as well as decrypt it.
In order to decrypt the random integer, the owner can now request a decryption with attestation from covalidator and that's done completely offchain.
## Basic Decryption
Here's how to decrypt a handle using a wallet client:
```JavaScript theme={null}
import { getViemChain, supportedChains, type HexString } from '@inco/lightning-js';
import { Lightning } from '@inco/lightning-js/lite';
import { createWalletClient, custom } from 'viem'
// Connect to Metamask or other wallet provider
const walletClient = createWalletClient({
chain: getViemChain(supportedChains.baseSepolia),
transport: custom(window.ethereum!)
})
// for Base mainnet: Lightning.baseMainnet()
// recommended: pass your own RPC URLs (otherwise viem's public RPC is used)
const zap = await Lightning.baseSepoliaTestnet({
hostChainRpcUrls: ['https://your-rpc-url'],
});
const results = await zap.attestedDecrypt(
walletClient,
["0x" as HexString]
);
const plaintext = results[0].plaintext.value;
```
It's also possible to decrypt multiple handles in a single request by passing an array of handles:
```javascript theme={null}
const results = await zap.attestedDecrypt(
walletClient,
[
"0x" as HexString,
"0x" as HexString
]
);
const plaintext1 = results[0].plaintext.value;
const plaintext2 = results[1].plaintext.value;
```
## Understanding Reencryption vs Decryption
When using attested decrypt, you have two main options:
* **Decryption**: Returns the plaintext value directly (as shown in the Basic Decryption examples above)
* **Reencryption**: Instead of returning plaintext, the decrypted value is re-encrypted with a different public key. This allows you to share decrypted data with third parties (delegates) without exposing the plaintext, or to decrypt it locally using your own keypair.
Reencryption provides an additional layer of security by ensuring that even if the attested decrypt response is intercepted, the actual plaintext value remains encrypted and can only be decrypted by the intended recipient.
## Reencryption for Delegates
You can request that the decryption be reencrypted for a delegate using their public key. This returns an encrypted decryption attestation that only the delegate can decrypt:
```javascript theme={null}
import { generateXwingKeypair } from '@inco/lightning-js/lite';
// Generate a keypair for the delegate
const delegateKeypair = await generateXwingKeypair();
const delegatePubKey = delegateKeypair.encodePublicKey();
// Request reencryption for the delegate
const encryptedResults = await zap.attestedDecrypt(
walletClient,
["0x" as HexString],
{ reencryptPubKey: delegatePubKey }
);
// The delegate can decrypt using their keypair
const encryptedAttestation = encryptedResults[0].encryptedPlaintext;
// The delegate would decrypt this using their private key
```
## Reencrypt and Decrypt Locally
You can also request reencryption and decrypt it immediately using a keypair you control:
```javascript theme={null}
import { generateXwingKeypair } from '@inco/lightning-js/lite';
// Generate your own keypair
const keypair = await generateXwingKeypair();
const pubKey = keypair.encodePublicKey();
// Request reencryption and decrypt locally
const results = await zap.attestedDecrypt(
walletClient,
["0x" as HexString],
{ reencryptPubKey: pubKey, reencryptKeypair: keypair }
);
const plaintext = results[0].plaintext.value;
```
## Session Key Decryption
For applications that need to perform decryption without requiring the user to sign each request, you can use session keys with allowance vouchers:
```javascript theme={null}
import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
// Generate an ephemeral Ethereum account for the session
const ephemeralAccount = privateKeyToAccount(generatePrivateKey());
const defaultSessionVerifier = '0xc34569efc25901bdd6b652164a2c8a7228b23005';
// Grant a session key allowance voucher (done once, typically by the user)
const expiresAt = new Date(Date.now() + 3600000); // 1 hour from now
const voucher = await zap.grantSessionKeyAllowanceVoucher(
walletClient,
ephemeralAccount.address,
expiresAt,
defaultSessionVerifier // or a custom session verifier
);
// Now decrypt using the session key (no wallet signature needed)
const results = await zap.attestedDecryptWithVoucher(
ephemeralAccount,
voucher,
["0x" as HexString]
);
const plaintext = results[0].plaintext.value;
```
Session key decryption also supports reencryption. Generate an `XwingKeypair` separately for this:
```javascript theme={null}
import { generateXwingKeypair } from '@inco/lightning-js/lite';
// Reencrypt and decrypt locally using session key
const decryptKeypair = await generateXwingKeypair();
const results = await zap.attestedDecryptWithVoucher(
ephemeralAccount,
voucher,
["0x" as HexString],
{ reencryptPubKey: decryptKeypair.encodePublicKey(), reencryptKeypair: decryptKeypair }
);
const plaintext = results[0].plaintext.value;
```
## Retry Configuration
All decryption methods support optional retry configuration:
```javascript theme={null}
const results = await zap.attestedDecrypt(
walletClient,
["0x" as HexString],
{
backoffConfig: {
maxRetries: 5,
baseDelayInMs: 1000,
backoffFactor: 2,
}
}
);
```
If you wish to perform a computation on a handle before decrypting it in a single request, check out [Attested Compute](../attestations/attested-compute) .
## Attested decrypt with Allowance Voucher/Session Key
Attested decrypt can also be called with a session key instead of a wallet provider using [Allowance Voucher](../voucher/allowance-voucher), allowing someone else to request decryption on your behalf.
# Attested Reveal
Source: https://docs.inco.org/js-sdk/attestations/attested-reveal
Attested reveal is similar to [Attested Decrypt](../attestations/attested-decrypt).
The major difference is that anyone can request a decryption with attestation after e.reveal() has been called on a handle, allowing anyone to submit the decryption result back on-chain.
Once revealed with e.reveal(), the ciphertext is considered public and can be accessed
by anyone. This action can not be undone.
## Getting Started
Let's examine this example contract:
```solidity theme={null}
import {euint256, e, inco} from "@inco/lightning/src/Lib.sol";
import {DecryptionAttestation} from "@inco/lightning/src/lightning-parts/DecryptionAttester.types.sol";
contract TestAttestedReveal {
euint256 randomNumber;
uint256 decryptedNumber;
constructor(address owner) payable {
require(msg.value == inco.getFee(), "Fee not paid");
randomNumber = e.rand();
e.reveal(randomNumber);
}
function GetHandle() external returns (euint256) {
return randomNumber;
}
function SubmitDecryption(
DecryptionAttestation memory decryption,
bytes[] memory signatures
) external {
require(
inco.incoVerifier().isValidDecryptionAttestation(decryption, signatures),
"Invalid Signature"
);
require(euint256.unwrap(randomNumber) == decryption.handle, "Handle mismatch");
decryptedNumber = uint256(decryption.value);
}
}
```
This contract creates a random 256bit integer and immediately calls e.reveal(), allowing anyone to decrypt, perform computation on it or request an attestation, even though we haven't explicitly granted permission to any particular address.
```javascript theme={null}
import { getViemChain, supportedChains, type HexString, type SupportedChainId } from '@inco/lightning-js';
import { Lightning } from '@inco/lightning-js/lite';
import { createWalletClient, custom } from 'viem';
//Connect to Metamask or other wallet provider
const walletClient = createWalletClient({
chain: getViemChain(supportedChains.baseSepolia),
transport: custom(window.ethereum!)
})
// for Base mainnet: Lightning.baseMainnet()
// recommended: pass your own RPC URLs (otherwise viem's public RPC is used)
const zap = await Lightning.baseSepoliaTestnet({
hostChainRpcUrls: ['https://your-rpc-url'],
});
const results = await zap.attestedReveal(
["0x" as HexString]
);
const plaintext = results[0].plaintext;
```
The result contains the plaintext with covalidator signature. It can be used to submit back the decryption on-chain by calling "SubmitDecryption" as an alternative to the old callbacks.
# EList Attested Decrypt
Source: https://docs.inco.org/js-sdk/attestations/elist-attested-decrypt
Decrypt or reveal an encrypted list handle
EList attested decrypt and reveal are the JS SDK counterparts to the on-chain `elist` type. An elist handle encodes an array of encrypted values — decrypting it returns all element values at once.
The length of an elist is always public and encoded in the handle itself. Only the element values are encrypted.
## Prerequisites
The elist handle must be allowed to the caller's address before decryption can succeed. In your Solidity contract:
```solidity theme={null}
inco.allow(elist.unwrap(myList), msg.sender);
```
## Basic Decrypt
`eListAttestedDecrypt` requires a wallet client for signing. The result contains a `values` array with one plaintext entry per list element:
```javascript theme={null}
import { getViemChain, supportedChains, type HexString } from '@inco/lightning-js';
import { Lightning } from '@inco/lightning-js/lite';
import { createWalletClient, custom } from 'viem';
const walletClient = createWalletClient({
chain: getViemChain(supportedChains.baseSepolia),
transport: custom(window.ethereum!),
});
// for Base mainnet: Lightning.baseMainnet()
// recommended: pass your own RPC URLs (otherwise viem's public RPC is used)
const zap = await Lightning.baseSepoliaTestnet({
hostChainRpcUrls: ['https://your-rpc-url'],
});
const result = await zap.eListAttestedDecrypt(
walletClient,
'0x' as HexString,
);
const values = result.values; // array of plaintext elements
```
## Reencryption
The same reencryption options available for `attestedDecrypt` apply here. Pass an X-Wing keypair to receive the values encrypted to your local key:
```javascript theme={null}
import { generateXwingKeypair } from '@inco/lightning-js/lite';
const keypair = await generateXwingKeypair();
const result = await zap.eListAttestedDecrypt(
walletClient,
'0x' as HexString,
{
reencryptPubKey: keypair.encodePublicKey(),
reencryptKeypair: keypair,
},
);
const values = result.values;
```
You can also pass only `reencryptPubKey` (without `reencryptKeypair`) to receive the encrypted attestation for forwarding to a delegate.
## Reveal (no wallet required)
If the elist has been publicly revealed on-chain via `e.reveal(myList)`, anyone can read its values without a wallet signature:
```javascript theme={null}
import { type HexString } from '@inco/lightning-js';
const result = await zap.eListAttestedReveal(
'0x' as HexString,
);
const values = result.values;
```
## Retry Configuration
Both methods accept an optional `backoffConfig`:
```javascript theme={null}
const result = await zap.eListAttestedDecrypt(
walletClient,
'0x' as HexString,
{
backoffConfig: {
maxRetries: 5,
baseDelayInMs: 1000,
backoffFactor: 2,
},
},
);
```
# Encrypting Values
Source: https://docs.inco.org/js-sdk/encryption
How to encrypt supported types (euint256, ebool, eaddress) with Inco Lightning JS.
The `zap.encrypt` helper lets you encrypt plaintext values before sending them on-chain. Inco Lightning JS currently supports three encrypted handle types:
* `handleTypes.euint256` — 256-bit unsigned integers.
* `handleTypes.ebool` — booleans.
* `handleTypes.euint160` — Ethereum addresses (use `BigInt` to encode the address, effectively an `eaddress`).
## Common setup
```ts theme={null}
import { handleTypes, getViemChain, supportedChains } from '@inco/lightning-js';
import { createWalletClient, type Address } from 'viem';
import { Lightning } from '@inco/lightning-js/lite'
// Do this once at initialization
const chainId = supportedChains.baseSepolia;
// for Base mainnet: Lightning.baseMainnet()
// recommended: pass your own RPC URLs (otherwise viem's public RPC is used)
const zap = await Lightning.baseSepoliaTestnet({
hostChainRpcUrls: ['https://your-rpc-url'],
});
const walletClient = createWalletClient({
chain: getViemChain(chainId),
account: /* Choose your account, e.g. from window.ethereum */,
transport: /* Choose your transport, e.g. from Alchemy */,
});
const dappAddress = '0x00000000000000000000000000000000deadbeef'; // Your contract
```
## Encrypt an `euint256`
```ts theme={null}
const amount = 42n;
const ct = await zap.encrypt(amount, {
accountAddress: walletClient.account.address,
dappAddress,
handleType: handleTypes.euint256,
});
```
## Encrypt an `ebool`
```ts theme={null}
const flag = true;
const ct = await zap.encrypt(flag, {
accountAddress: walletClient.account.address,
dappAddress,
handleType: handleTypes.ebool,
});
```
## Encrypt an `eaddress` (aka `euint160`)
Addresses must be converted to a `BigInt` before encryption.
```ts theme={null}
const address: Address = walletClient.account.address;
const ct = await zap.encrypt(BigInt(address), {
accountAddress: walletClient.account.address,
dappAddress,
handleType: handleTypes.euint160,
});
```
Each example returns a ciphertext `HexString` you can pass to your contract or store as a handle for later confidential computation.
👉 **See also:** [How encrypted inputs are consumed on the contract side](../guide/input)
# Use Inco Lightning JS in Existing Project
Source: https://docs.inco.org/js-sdk/existing-project
Integrate Inco Lightning JS into your existing JavaScript/TypeScript project.
Currently only tested with Webpack and NextJS. If you are using Rollup or Vite
please report any issues [here](https://docs.google.com/forms/d/e/1FAIpQLSetj4PsvNUSTP7nQYun9D-VF1cXX6YtYctjKkzC4j-x_g2wXg/viewform)
## Install
Choose your favorite package manager:
```bash npm theme={null}
npm install @inco/lightning-js
```
```bash yarn theme={null}
yarn add @inco/lightning-js
```
```bash bun theme={null}
bun add @inco/lightning-js
```
## Usage
A typical usage of `@inco/lightning-js` includes 3 steps:
1. Encrypting a value.
2. Posting the ciphertext to the contract, which will perform confidential computes on it.
3. Requesting a decryption of the result of the computation.
Next, follow the [Encryption guide](/js-sdk/encryption) for a full walkthrough of these steps.
# Migrating to @inco/lightning-js (v1)
Source: https://docs.inco.org/js-sdk/migration-v1
Upgrade from the old @inco/js package to the renamed @inco/lightning-js v1 SDK.
The Inco JS SDK has been **renamed from `@inco/js` to `@inco/lightning-js`** for v1. This guide covers the package rename plus the breaking API changes when upgrading from `@inco/js` 0.7.x.
Update every import — `@inco/js` → `@inco/lightning-js` and `@inco/js/lite` → `@inco/lightning-js/lite` — then reinstall. The old `@inco/js` package is no longer updated.
## Install
```bash npm theme={null}
npm install @inco/lightning-js@latest
```
```bash yarn theme={null}
yarn add @inco/lightning-js@latest
```
```bash bun theme={null}
bun add @inco/lightning-js@latest
```
***
## Instantiating the SDK
v1 adds explicit per-network factories — `Lightning.baseSepoliaTestnet()` and `Lightning.baseMainnet()` — which take no `pepper` or `chainId`. Prefer them over the v0.7 `Lightning.latest(...)` call:
```diff theme={null}
- // v0.7
- const zap = await Lightning.latest('testnet', supportedChains.baseSepolia);
+ // v1 — Base Sepolia
+ const zap = await Lightning.baseSepoliaTestnet();
+ // v1 — Base mainnet
+ const zap = await Lightning.baseMainnet();
```
Pass your own `hostChainRpcUrls` (recommended — otherwise the SDK falls back to viem's public RPC endpoints):
```ts theme={null}
const zap = await Lightning.baseSepoliaTestnet({
hostChainRpcUrls: ['https://your-rpc-url'],
});
```
`Lightning.latest(pepper, chainId)` still works for advanced cases, but the network factories are the recommended entry point.
***
## Breaking Changes
### 1. Keypair generation: `generateSecp256k1Keypair` removed
`generateSecp256k1Keypair` was used for reencryption in attested decrypt calls. It has been replaced by `generateXwingKeypair`, a post-quantum X-Wing keypair. The new function is **async**.
```diff theme={null}
- import { generateSecp256k1Keypair } from '@inco/lightning-js/lite';
+ import { generateXwingKeypair } from '@inco/lightning-js/lite';
- const keypair = generateSecp256k1Keypair();
+ const keypair = await generateXwingKeypair();
```
The returned keypair still exposes `encodePublicKey()` for use in attested decrypt calls.
Session keys are unaffected — they use a plain viem `PrivateKeyAccount` (via `privateKeyToAccount(generatePrivateKey())`), not an X-Wing keypair.
***
### 2. Attested methods: positional args replaced by an opts object
All attested methods (`attestedDecrypt`, `attestedCompute`, `attestedDecryptWithVoucher`, `attestedComputeWithVoucher`) previously accepted reencryption keys as extra positional arguments. They now use a typed `opts` object as the last parameter.
#### `attestedDecrypt` — reencrypt for a delegate
```diff theme={null}
- const results = await zap.attestedDecrypt(walletClient, handles, delegatePubKey);
+ const results = await zap.attestedDecrypt(walletClient, handles, { reencryptPubKey: delegatePubKey });
```
#### `attestedDecrypt` — reencrypt and decrypt locally
```diff theme={null}
- const results = await zap.attestedDecrypt(walletClient, handles, pubKey, keypair);
+ const results = await zap.attestedDecrypt(walletClient, handles, { reencryptPubKey: pubKey, reencryptKeypair: keypair });
```
#### `attestedCompute` — reencrypt for a delegate
```diff theme={null}
- const result = await zap.attestedCompute(walletClient, handle, op, value, delegatePubKey);
+ const result = await zap.attestedCompute(walletClient, handle, op, value, { reencryptPubKey: delegatePubKey });
```
#### No-opts calls are unchanged
If you were calling `attestedDecrypt` or `attestedCompute` without any reencryption options (plain decryption), no change is needed — the default behaviour is still to return plaintext directly.
***
### 3. Session key methods: reencryption options moved into an `opts` object
The session key is still a plain viem `PrivateKeyAccount`, and `attestedDecryptWithVoucher` / `attestedComputeWithVoucher` keep their positional arguments. What changed is that reencryption keys moved out of positional arguments and into a trailing `opts` object (the same change as section 2).
```diff theme={null}
+ import { generateXwingKeypair } from '@inco/lightning-js/lite';
+ const decryptKeypair = await generateXwingKeypair();
- await zap.attestedDecryptWithVoucher(ephemeralAccount, voucher, handles, pubKey, keypair);
+ await zap.attestedDecryptWithVoucher(ephemeralAccount, voucher, handles, {
+ reencryptPubKey: decryptKeypair.encodePublicKey(),
+ reencryptKeypair: decryptKeypair,
+ });
```
***
### 4. BackoffConfig field renames
The `backoffConfig` object passed to attested methods has two renamed fields, and is now passed inside the opts object.
```diff theme={null}
- await zap.attestedDecrypt(walletClient, handles, {
- maxRetries: 5,
- initialDelay: 1000,
- maxDelay: 10000,
- });
+ await zap.attestedDecrypt(walletClient, handles, {
+ backoffConfig: {
+ maxRetries: 5,
+ baseDelayInMs: 1000,
+ backoffFactor: 2,
+ }
+ });
```
| Old field | New field | Notes |
| -------------- | --------------- | ----------------------------- |
| `initialDelay` | `baseDelayInMs` | Renamed |
| `maxDelay` | *(removed)* | Replaced by `backoffFactor` |
| *(n/a)* | `backoffFactor` | Multiplier applied each retry |
***
### 5. `AllowanceVoucher`: `warning` field is first and enforced on-chain (EIP-712 digest change)
The `AllowanceVoucher` EIP-712 struct includes a `string warning` field that is now **first** in the struct. This ensures wallets display it before the opaque byte fields. The field order is part of the EIP-712 type hash, so any voucher signed with the old field order produces a different digest and will fail verification.
Additionally, `isAllowedWithProof` now **enforces the exact warning text on-chain** — it reverts with `InvalidVoucherWarning` if the voucher's `warning` does not match `REQUIRED_ALLOWANCE_VOUCHER_WARNING` exactly. Passing an empty string, a custom message, or the old warning text will be rejected.
If you use `grantSessionKeyAllowanceVoucher` or `grantCustomSessionKeyAllowanceVoucher` (the `Lightning` methods), **no change is needed** — the correct `warning` is populated automatically.
Always create vouchers through the SDK, which sets the correct `warning` for you:
```typescript theme={null}
import { Lightning } from '@inco/lightning-js/lite';
const zap = await Lightning.baseSepoliaTestnet();
// warning is set automatically to the required on-chain text
const voucher = await zap.grantSessionKeyAllowanceVoucher(
walletClient,
granteeAddress,
new Date(Date.now() + 10 * 60 * 1000),
sessionVerifierAddress,
);
```
For custom session-verifier logic, use `grantCustomSessionKeyAllowanceVoucher(walletClient, sessionVerifierAddress, sharerArgData)` instead — it also sets the `warning` automatically.
***
## New Features
### Multiple RPC endpoints with automatic fallback
All Lightning factory methods now accept an optional `hostChainRpcUrls` array. When multiple URLs are provided the SDK uses viem's `fallback()` transport internally — it tries providers in order and moves to the next on failure.
```typescript theme={null}
// Recommended: use the explicit network factory for your chain.
// for Base mainnet: Lightning.baseMainnet({ ... })
const zap = await Lightning.baseSepoliaTestnet({
hostChainRpcUrls: ['https://primary.rpc', 'https://fallback.rpc'],
});
```
`baseSepoliaTestnet()` and `baseMainnet()` are the recommended way to initialize the SDK. Passing your own `hostChainRpcUrls` is recommended — without it the SDK falls back to viem's public RPC endpoints. A single URL also works.
# NextJS Starter
Source: https://docs.inco.org/js-sdk/nextjs-starter
Get started quickly with our NextJS template for building dApps with Inco
> Note: currently, the NextJS template **works against Base Mainnet and Base Sepolia**. An updated template will be published shortly with a working setup against a local node and local covalidator.
## Overview
The Inco NextJS starter template provides a pre-configured environment for building decentralized applications with privacy features. It includes everything you need to start building confidential dApps with NextJS and Inco.
# NextJs Starter
Here's a simple NextJs starter kit with Inco Lightning JS: [GitHub Template](https://github.com/Inco-fhevm/nextjs-template)
## Getting Started
### 1. Clone the Template
We can start by cloning our template project. You can either:
* Go to our [repository](https://github.com/Inco-fhevm/nextjs-template) and click the `Use this template` button at the top of the page to create a new repository
* Or clone it directly:
```bash theme={null}
git clone https://github.com/Inco-fhevm/nextjs-template.git
cd nextjs-template
```
### 2. Install and Run
Install the project dependencies and start the development server:
```bash theme={null}
npm install
npm run dev
```
# Allowance Voucher
Source: https://docs.inco.org/js-sdk/voucher/allowance-voucher
Allowance voucher (aka Session Key) allows owner of a ciphertext to delegate viewing/compute to someone else for a period of time completely off-chain.
Vouchers are like sessions and are revokable.
## Security model
A session voucher grants the holder access to **all** of the sharer's encrypted handles — it is not scoped to a specific dApp or contract. `canUseSession` checks only that the session has not expired and that the caller matches the authorized decrypter; it does not restrict access by which application the encrypted value came from.
This means a single voucher signed for one application also covers handles created by any other Inco-enabled dApp the user has interacted with (auction bids, game states, private messages, etc).
**To limit exposure:**
* Use the shortest expiry that makes sense for your use case (minutes rather than hours or days).
* Call `updateActiveVouchersSessionNonce()` as soon as the session is no longer needed to invalidate all outstanding vouchers immediately, regardless of their expiry.
* Never log, persist, or transmit the voucher outside of the narrowest scope that requires it.
### Wallet signing prompt
When a user signs a session voucher, wallets render all EIP-712 struct fields. The `AllowanceVoucher` includes a `warning` field that is part of the signed payload:
Inco Warning: signing this message may leak your private data, including from
unrelated apps. Sign only if you fully trust this app.
The `warning` field is placed **first** in the EIP-712 struct so wallets show it before the opaque byte fields, ensuring users see it prominently.
This message is included automatically when using `grantSessionKeyAllowanceVoucher`. **Do not suppress or alter it** — the on-chain verifier rejects any `AllowanceProof` whose voucher does not contain this exact text (reverts with `InvalidVoucherWarning`), and altering it also produces a different EIP-712 digest that will fail signature verification.
## Getting Started
To create a voucher and grant Bob permission to decrypt on Alice's behalf:
```javascript theme={null}
import { createWalletClient, custom } from 'viem'
import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
import { getViemChain, supportedChains, type SupportedChainId } from '@inco/lightning-js';
import { Lightning } from '@inco/lightning-js/lite';
// Alice connects her wallet
const walletClient = createWalletClient({
chain: getViemChain(supportedChains.baseSepolia),
transport: custom(window.ethereum!)
})
// Alice creates an ephemeral Ethereum account (the session key)
const ephemeralAccount = privateKeyToAccount(generatePrivateKey());
// for Base mainnet: Lightning.baseMainnet()
// recommended: pass your own RPC URLs (otherwise viem's public RPC is used)
const zap = await Lightning.baseSepoliaTestnet({
hostChainRpcUrls: ['https://your-rpc-url'],
});
// Default session verifier address
const sessionVerfier = "0xc34569efc25901bdd6b652164a2c8a7228b23005";
// Alice grants the ephemeral account permission to decrypt on her behalf
const voucherWithSig = await zap.grantSessionKeyAllowanceVoucher(
walletClient,
ephemeralAccount.address,
new Date(Date.now() + 1000 * 60 * 60 * 24), // 1 day
sessionVerfier,
);
```
Some specific use cases may require a custom session verifier logic, to for
example check whether a payment has been made in order to access secrets.
grantSessionKeyAllowanceVoucher() allows the owner to specify a custom session
verifier contract address with a custom canUseSession() function that can
either allow or deny access based on certain on-chain conditions.
Using the default session verifier will give the session key unverified access
to all user handles for the specified time period.
DEFAULT\_SESSION\_VERIFIER (Base Sepolia): 0xc34569efc25901bdd6b652164a2c8a7228b23005
DEFAULT\_SESSION\_VERIFIER (Base mainnet): 0x68a5b59b4caf23416885859c1662746619a471f3
```Solidity theme={null}
import {ALLOWANCE_GRANTED_MAGIC_VALUE} from "@inco/lightning/src/Types.sol";
struct Session {
address decrypter;
uint256 expiresAt;
}
contract MyCustomSessionVerifier {
function canUseSession(
bytes32, /* handle */
address account, /* user trying to use the session */
bytes memory sharerArgData,
bytes memory /* requesterArgData */
) external view returns (bytes32) {
Session memory session = abi.decode(sharerArgData, (Session));
if (session.expiresAt >= block.timestamp && session.decrypter == account) {
return ALLOWANCE_GRANTED_MAGIC_VALUE;
}
return bytes32(0);
}
}
```
## Attested Decrypt with Voucher/Session Key
The voucher and signature now allow Bob to decrypt any handle that Alice owns using the attestedDecryptWithVoucher() function:
```javascript theme={null}
import type { HexString } from '@inco/lightning-js';
// Bob calls the attestedDecryptWithVoucher function with voucher
const decrypted = await zap.attestedDecryptWithVoucher(
ephemeralAccount,
voucherWithSig,
['0x...' as HexString]
);
const plaintext = decrypted[0].plaintext.value;
```
## AttestedCompute with Voucher/Session Key
Bob can also perform attested compute on behalf of Alice using attestedComputeWithVoucher() to check if the value is equal to an expected value:
```javascript theme={null}
import type { AttestedComputeSupportedOps } from '@inco/lightning-js/lite';
import type { HexString } from '@inco/lightning-js';
const computed = await zap.attestedComputeWithVoucher(
ephemeralAccount,
voucherWithSig,
'0x...' as HexString,
AttestedComputeSupportedOps.Eq,
100n
);
const plaintext = computed.plaintext.value;
```
## SessionKey Reencrypt
Similarly, Bob can also perform reencryption on behalf of Alice using attestedDecryptWithVoucher() with a reencrypt public key. This is similar to standard [attested decrypt reencryption](../attestations/attested-decrypt#reencryption-for-delegates).
```javascript theme={null}
import { generateXwingKeypair } from '@inco/lightning-js/lite';
import type { HexString } from '@inco/lightning-js';
// Generate an X-Wing keypair for reencryption
const reencryptKeypair = await generateXwingKeypair();
const reencryptPubKey = reencryptKeypair.encodePublicKey();
// Bob performs reencryption on behalf of Alice
const reencrypted = await zap.attestedDecryptWithVoucher(
ephemeralAccount,
voucherWithSig,
['0x...' as HexString],
{ reencryptPubKey, reencryptKeypair }
);
// Bob can decrypt the reencrypted data
const decrypted = await decrypt(
reencryptKeypair,
hexToBytes(reencrypted[0].encryptedPlaintext.ciphertext.value)
);
const plaintext = BigInt('0x' + Buffer.from(decrypted).toString('hex'));
```
## Revoking a Voucher
In order to invalidate existing vouchers, you can call this function:
```javascript theme={null}
const txHash = await zap.updateActiveVouchersSessionNonce(walletClient);
```
Which will invalidate all existing vouchers, despite their expiration time.
If you want to selectively revoke access to specific users, your dApp would
need to handle the logic of reissuing new vouchers to users who still require
access.
# Quickstart
Source: https://docs.inco.org/quickstart
Get started with Inco Lightning in minutes
## Prerequisites
Before you begin, make sure you have:
* [Bun](https://bun.sh//) installed (you can also chose to use node + npm or equivalent)
* [Docker](https://www.docker.com/get-started) installed
* [Foundry](https://book.getfoundry.sh/) installed
* Basic knowledge of Solidity and JavaScript/TypeScript
## 1-minute setup
We recommend getting started using our [template](https://github.com/Inco-fhevm/lightning-rod).
1. Clone the repository:
```sh theme={null}
git clone git@github.com:Inco-fhevm/lightning-rod.git
cd lightning-rod
```
Note that you can also clone the repository using HTTPS:
```
git clone https://github.com/Inco-fhevm/lightning-rod
cd lightning-rod
```
2. Install dependencies:
```sh theme={null}
bun install
```
3. Compile contracts and test:
```sh theme={null}
bun run test
```
4. Finally, stop the docker containers which were started for the test:
```sh theme={null}
docker compose down
```
See [README.md](https://github.com/Inco-fhevm/lightning-rod) for other options on how to run the local development environment.
## Next Steps
If you are using Inco for the first time we recommend following our guide of basics, or you can learn from example.
Learn the basics of Inco Lightning
Learn how to write confidential smart contracts
# Build a dApp
Source: https://docs.inco.org/quickstart/build-a-dapp
Scaffold a confidential dApp with create-inco-app
`create-inco-app` is the fastest way to start building on Inco. It scaffolds a confidential project — a **monorepo** with Solidity contracts and a Next.js frontend, or just the **contracts**, or just the **frontend** — pre-wired with the Inco SDK, your contract framework, and a wallet provider.
## Basic usage
```bash npm theme={null}
npx create-inco-app@latest
```
```bash pnpm theme={null}
pnpm create inco-app@latest
```
```bash yarn theme={null}
yarn create inco-app
```
```bash bun theme={null}
bunx create-inco-app@latest
```
You'll be prompted for:
```
What is your project named? my-app
What would you like to scaffold? Full monorepo / Contracts only / Frontend only
Which chain would you like to use? EVM / SVM
Which contract framework? Hardhat / Foundry (skipped for frontend-only)
Which wallet provider? RainbowKit / Privy / Dynamic / Reown / Para (skipped for contracts-only)
```
## Scaffold modes
Choose what to generate with `--template` (or the second prompt). Contracts-only and frontend-only are scaffolded **at the project root** (no monorepo wrapper).
Contracts **and** frontend in one workspace.
```bash npm theme={null}
npx create-inco-app@latest my-app --chain evm --framework hardhat --wallet rainbowkit --yes
```
```bash pnpm theme={null}
pnpm create inco-app@latest my-app --chain evm --framework hardhat --wallet rainbowkit --yes
```
```bash yarn theme={null}
yarn create inco-app my-app --chain evm --framework hardhat --wallet rainbowkit --yes
```
```bash bun theme={null}
bunx create-inco-app@latest my-app --chain evm --framework hardhat --wallet rainbowkit --yes
```
```
my-app/
├── contracts/ # Solidity (Hardhat or Foundry) — ConfidentialERC20 + ConfidentialLottery
├── frontend/ # Next.js app (wallet provider + Inco SDK wired up)
└── package.json # workspace root (npm run dev, contracts:compile, ...)
```
Just the contract project — Hardhat or Foundry — no frontend.
```bash Foundry theme={null}
npx create-inco-app@latest my-contracts --template contracts --chain evm --framework foundry --yes
```
```bash Hardhat theme={null}
npx create-inco-app@latest my-contracts --template contracts --chain evm --framework hardhat --yes
```
```
# Foundry # Hardhat
my-contracts/ my-contracts/
├── src/ ├── contracts/ # Solidity files
├── test/ ├── test/
├── script/ ├── ignition/ # deployment modules
├── foundry.toml ├── hardhat.config.ts
├── remappings.txt ├── utils/
└── docker-compose.yaml └── docker-compose.yaml
```
Just the Next.js dApp — no contracts. Wire it to an already-deployed contract address.
```bash npm theme={null}
npx create-inco-app@latest my-frontend --template frontend --chain evm --wallet rainbowkit --yes
```
```bash pnpm theme={null}
pnpm create inco-app@latest my-frontend --template frontend --chain evm --wallet rainbowkit --yes
```
```bash yarn theme={null}
yarn create inco-app my-frontend --template frontend --chain evm --wallet rainbowkit --yes
```
```bash bun theme={null}
bunx create-inco-app@latest my-frontend --template frontend --chain evm --wallet rainbowkit --yes
```
```
my-frontend/
├── app/ # Next.js App Router
├── components/ # Providers.tsx (wallet) + UI
├── hooks/ # Inco SDK integration
├── lib/network.ts # network + Inco Lightning factory
└── abi/
```
## Reference
```
npx create-inco-app@latest [project-name] [options]
```
| Option | Description |
| ------------------------------------------------------- | ------------------------------------------------------------------ |
| `-t`, `--template ` | Scaffold type: `monorepo` (default), `contracts`, `frontend` |
| `-c`, `--chain ` | Chain type: `evm`, `svm` |
| `-f`, `--framework ` | Contract framework: `hardhat`, `foundry` (EVM), `anchor` (SVM) |
| `-w`, `--wallet ` | Wallet provider: `rainbowkit`, `privy`, `dynamic`, `reown`, `para` |
| `-y`, `--yes` | Skip prompts, use defaults |
| `--git` | Initialize a git repository |
| `--install` | Install dependencies after scaffolding |
| `--use-npm` / `--use-pnpm` / `--use-yarn` / `--use-bun` | Choose the package manager |
| `-h`, `--help` | Show all options |
| `-v`, `--version` | Print the version |
## Networks
The project targets **Base Sepolia by default** and supports **Base Mainnet**. The frontend selects the network from a single env var — no code changes needed:
```bash frontend/.env theme={null}
# "testnet" (Base Sepolia, default) or "mainnet" (Base Mainnet)
NEXT_PUBLIC_NETWORK=testnet
```
`lib/network.ts` reads it and returns the matching Inco Lightning client (`Lightning.baseSepoliaTestnet()` or `Lightning.baseMainnet()`).
## After setup (monorepo)
1. Install dependencies:
```bash npm theme={null}
cd my-app && npm install
```
```bash pnpm theme={null}
cd my-app && pnpm install
```
```bash yarn theme={null}
cd my-app && yarn install
```
```bash bun theme={null}
cd my-app && bun install
```
2. Set up frontend env vars:
```bash theme={null}
cp frontend/.env.example frontend/.env
# set NEXT_PUBLIC_NETWORK, your wallet key(s), and NEXT_PUBLIC_CONFLOTTERY_ADDRESS after deploy
```
3. Compile and test the contracts:
```bash npm theme={null}
npm run contracts:compile
npm run contracts:test
```
```bash pnpm theme={null}
pnpm contracts:compile
pnpm contracts:test
```
```bash yarn theme={null}
yarn contracts:compile
yarn contracts:test
```
```bash bun theme={null}
bun run contracts:compile
bun run contracts:test
```
4. (Optional) Deploy — copy `contracts/.env.sample` to `contracts/.env` and fill in the key for your target network, then:
```bash theme={null}
# local Inco node (anvil + covalidator) — run in a separate terminal
npm run contracts:node
# deploy
npm run contracts:deploy:local # or :deploy:testnet / :deploy:mainnet
```
`contracts/.env` keys, per target network:
```bash contracts/.env theme={null}
PRIVATE_KEY_ANVIL=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 # local default
PRIVATE_KEY_BASE_SEPOLIA=
PRIVATE_KEY_BASE=
```
5. Start the frontend (set `NEXT_PUBLIC_CONFLOTTERY_ADDRESS` to your deployed address first):
```bash npm theme={null}
npm run dev
```
```bash pnpm theme={null}
pnpm dev
```
```bash yarn theme={null}
yarn dev
```
```bash bun theme={null}
bun run dev
```
Open [http://localhost:3000](http://localhost:3000).
## Workspace scripts (monorepo)
| Script | Description |
| ---------------------------------- | ----------------------------------------------- |
| `npm run dev` | Start the frontend dev server |
| `npm run build` | Build the frontend |
| `npm run contracts:compile` | Compile the contracts |
| `npm run contracts:test` | Run the contract tests |
| `npm run contracts:node` | Start the local Inco node (anvil + covalidator) |
| `npm run contracts:deploy:local` | Deploy the lottery to the local node |
| `npm run contracts:deploy:testnet` | Deploy the lottery to Base Sepolia |
| `npm run contracts:deploy:mainnet` | Deploy the lottery to Base Mainnet |
`deploy:token:local` / `:testnet` / `:mainnet` variants deploy only the `ConfidentialERC20` token. Each deploy reads its key from `contracts/.env` by target chain (`PRIVATE_KEY_ANVIL` / `PRIVATE_KEY_BASE_SEPOLIA` / `PRIVATE_KEY_BASE`).
## Inco SDK integration
The frontend talks to Inco through `@inco/lightning-js`. The network-aware client comes from `lib/network.ts`:
```ts lib/network.ts theme={null}
import { Lightning } from "@inco/lightning-js/lite";
// NEXT_PUBLIC_NETWORK: "testnet" (Base Sepolia, default) or "mainnet" (Base Mainnet)
export async function getIncoLightning() {
return process.env.NEXT_PUBLIC_NETWORK === "mainnet"
? Lightning.baseMainnet()
: Lightning.baseSepoliaTestnet();
}
```
Encrypt a value before sending it on-chain, then decrypt results with attestation:
```ts theme={null}
import { getIncoLightning } from "@/lib/network";
import { handleTypes } from "@inco/lightning-js";
import { parseEther } from "viem";
const zap = await getIncoLightning();
// Encrypt an amount for the contract
const ciphertext = await zap.encrypt(parseEther(amount), {
accountAddress: address,
dappAddress: contractAddress,
handleType: handleTypes.euint256,
});
// The Inco executor fee is read from the network and passed as msg.value
const fee = await publicClient.readContract({
address: zap.executorAddress,
abi: getFeeAbi,
functionName: "getFee",
});
writeContract({ address: contractAddress, abi, functionName: "encryptedMint", args: [ciphertext], value: fee });
// Decrypt a handle with attestation (e.g. check if the user won)
const [result] = await zap.attestedDecrypt(walletClient, [encryptedHandle]);
const plaintext = result.plaintext.value;
```
See [Encrypting Values](/js-sdk/encryption) and [Attested Decrypt](/js-sdk/attestations/attested-decrypt) for full details.
## Choose your wallet provider
Each provider has its own setup. Select one to see the provider configuration and how it integrates with Inco:
Multi-wallet connector (recommended)
Embedded wallets & social login
Multi-chain wallet orchestration
WalletConnect-powered connections
Embedded + external wallet support
# Cheatcodes reference
Source: https://docs.inco.org/quickstart/cheatcodes-reference
Fully simulate the Inco environment all from solidity tests
## Execute the operations
Inco's infrastructure is monitoring the operations requested over encrypted variables by the smart contracts.\
Inco executes them asynchronously after the blocks containing the ops are mined. Under the hood, the Inco singleton instance on each
supported chain is emitting events to request the operations (that includes encrypts, trivial encrypts, all logical and mathematical operations,
and decryption requests). The solidity-based mock is using Foundry's `vm.recordLogs()` function to record the pending ops.
As the events recording are consumed whenever read, there would be conflicts if you try to use `recordLogs` in your tests.
To simulate Inco processing the operations, which assigns to its internal value store its encrypted value to each handle, use the following cheatcode:
```Solidity theme={null}
processAllOperations();
```
This cheatcode must be called before reading the value of any encrypted variable, and performing assert statements.
`processAllOperations` also executes any pending decryption callback.
## Simulate Inputs
Encrypted inputs are normally generated using Inco's JS SDK. Simulate them with the following cheatcodes:
### For euint256
```Solidity theme={null}
fakePrepareEuint256Ciphertext(uint256 value) returns (bytes memory ciphertext);
// example usage
token.transfer(bob, fakePrepareEuint256Ciphertext(1 ether));
```
### For ebool
```Solidity theme={null}
fakePrepareEboolCiphertext(bool value) returns (bytes memory ciphertext);
// example usage
someContract.setActive(fakePrepareEboolCiphertext(true));
```
### For eaddress
```Solidity theme={null}
fakePrepareEaddressCiphertext(address value) returns (bytes memory ciphertext);
// example usage
token.setOwner(fakePrepareEaddressCiphertext(alice));
```
## Simulate decryption
Allowed accounts can request reading the values of e-variables using JS SDK. In the tests, you can read any value bypassing the access control checks.
### For euint256
```Solidity theme={null}
getUint256Value(euint256 input) (uint256);
// example usage
assertEq(getUint256Value(token.balanceOf(alice)), 9 * GWEI);
```
### For ebool
```Solidity theme={null}
getBoolValue(ebool input) (bool);
// example usage
assertEq(getBoolValue(someContract.isActive()), true);
```
### For eaddress
```Solidity theme={null}
getAddressValue(eaddress input) (address);
// example usage
assertEq(getAddressValue(token.owner()), alice);
```
To fully test how one of your user could see its encrypted data, we recommend combining an assertion over the decrypted value with an access control check.
```Solidity theme={null}
// example, we check that alice can read her balance
assertTrue(token.balanceOf(alice).isAllowed(alice));
```
# Fees
Source: https://docs.inco.org/quickstart/fees
Understanding Inco fees and which operations require them
Inco charges fees for certain operations to ensure the security and performance of the confidential computing infrastructure. This page explains how fees work and which operations require payment.
## Fee Structure
Inco fees are paid in the native blockchain currency (ETH on Ethereum, etc.) and are required for operations that involve processing encrypted inputs from external sources.
### Getting the Current Fee Amount
Use the `inco.getFee()` function to get the current fee amount:
```solidity theme={null}
uint256 fee = inco.getFee(); // 0.000001 ETH
```
### Paying Fees
Fees can be paid in two ways: either by users including them in `msg.value`, or by having the contract pay from its own ETH balance.
#### Option 1: User Pays via msg.value
Fees must be paid via `msg.value` when calling functions that require them. The transaction will revert if insufficient fees are provided.
```solidity theme={null}
require(msg.value >= inco.getFee() * ciphertextCount, "Fee Not Paid");
```
#### Option 2: Contract Pays from Balance
Contracts can hold ETH in their balance to pay fees automatically, eliminating the need for users to include fees in `msg.value`.
```solidity theme={null}
contract MyContract {
// Contract holds ETH to pay fees automatically
function transfer(address to, bytes memory valueInput) external {
// No payable modifier needed, no msg.value check required
euint256 value = valueInput.newEuint256(msg.sender);
// Contract's ETH balance is used to pay fees automatically
// ... rest of function
}
// Function to top up contract's ETH balance
function depositFees() external payable {
// Allows anyone to add ETH to contract for fee payments
}
// Function to withdraw excess ETH
function withdrawFees(uint256 amount) external onlyOwner {
require(address(this).balance >= amount, "Insufficient balance");
payable(owner()).transfer(amount);
}
}
```
**Benefits of contract-paid fees:**
* Better user experience - no need to calculate or send exact fees
* Simpler function signatures - no `payable` modifier required
* Automatic fee management by contract owner
**Considerations:**
* Contract owner must ensure sufficient ETH balance
* Monitor contract balance and top up as needed
* Consider implementing balance thresholds and alerts
## Operations That Require Fees
### Encrypted Input Creation and Random Generation
The following operations create new encrypted handles from external ciphertexts or generate random values. They have a fixed base cost of 0.000001 ETH per call:
| Operation | Fee Required | Description |
| ----------------------------------- | -------------- | ----------------------------------------------- |
| `e.newEuint256(bytes memory input)` | 1 fee per call | Create a new `euint256` from an encrypted input |
| `e.newEbool(bytes memory input)` | 1 fee per call | Create a new `ebool` from an encrypted input |
| `e.newEaddress(bytes memory input)` | 1 fee per call | Create a new `eaddress` from an encrypted input |
| `e.rand()` | 1 fee per call | Generate a random `euint256` value |
| `e.randBounded(uint256)` | 1 fee per call | Generate a bounded random `euint256` value |
| `e.randBounded(euint256)` | 1 fee per call | Generate a bounded random `euint256` value |
### EList Operations (Dynamic Fees)
Unlike the fixed fees above, most [elist](/guide/preview/elist) operations have a dynamic fee structure that scales with the amount of elements and element type:
```
fee = element length × element bitwidth × (0.000001 / 256) ETH
```
or simply
```solidity theme={null}
uint256 fee = inco.getEListFee(n_of_elements, ETypes.Uint256);
```
In other words, you pay per bit output by the operation. For `euint256` elements (256 bits), this works out to 0.000001 ETH per element.
| Operation | Fee Required | Description |
| --------------------------------------- | --------------------------------------------- | ------------------------------------------------- |
| `e.newEList(...)` | ret\_len \* bits \* (0.000001 / 256) ETH | Create a new `elist` from encrypted inputs |
| `e.append(list, value)` | ret\_len \* bits \* (0.000001 / 256) ETH | Append an element to a list |
| `e.insert(list, index, value)` | ret\_len \* bits \* (0.000001 / 256) ETH | Insert an element into a list |
| `e.set(list, index, value)` | ret\_len \* bits \* (0.000001 / 256) ETH | Set an element at a given index |
| `e.concat(listA, listB)` | ret\_len \* bits \* (0.000001 / 256) ETH | Concatenate two lists |
| `e.slice(list, start, end)` | ret\_len \* bits \* (0.000001 / 256) ETH | Extract a sub-list |
| `e.sliceLen(list, start, length)` | ret\_len \* bits \* (0.000001 / 256) ETH | Extract a sub-list by length |
| `e.range(start, end, listType)` | ret\_len \* bits \* (0.000001 / 256) ETH | Create a list populated with ordered values |
| `e.reverse(list)` | ret\_len \* bits \* (0.000001 / 256) ETH | Reverse the order of elements in a list |
| `e.shuffle(list)` | ret\_len \* bits \* (0.000001 / 256) ETH | Randomly shuffle the elements of a list |
| `e.shuffledRange(start, end, listType)` | 2 \* ret\_len \* bits \* (0.000001 / 256) ETH | Create a randomly shuffled list of ordered values |
| `e.getEuint256(list, index)` | Free, only consumes gas. | Read an euint256 element from a list (if allowed) |
| `e.getEbool(list, index)` | Free, only consumes gas. | Read an ebool element from a list (if allowed) |
| `e.getOr(list, index, default)` | Free, only consumes gas. | Read an element or return default (if allowed) |
**Example:** creating an elist of 52 `euint256` elements using `range()` (a deck of cards) costs 52 × 0.000001 = 0.000052 ETH. Performing further operations on that list, such as `shuffle()` or `reverse()`, costs the same amount per call, as they produce new elist with the same length and type.
Users get charged for above eList operations regardless of whether the return handle is allowed or not. Avoid calling them in a for-loop or keep iterations low to avoid excessive fee charges.
**Example with user-paid fees:**
```solidity theme={null}
function transfer(address to, bytes memory valueInput) external payable {
// Each newEuint256 call requires 1 fee
require(msg.value >= inco.getFee() * 1, "Fee Not Paid");
euint256 value = valueInput.newEuint256(msg.sender);
// ... rest of function
}
```
**Example with contract-paid fees:**
```solidity theme={null}
function transfer(address to, bytes memory valueInput) external {
// No fee check needed - contract pays from its balance
euint256 value = valueInput.newEuint256(msg.sender);
// ... rest of function
}
```
**Multiple encrypted inputs:**
```solidity theme={null}
function multiInput(bytes memory input1, bytes memory input2) external payable {
// Two newEuint256 calls require 2 fees (user pays)
require(msg.value >= inco.getFee() * 2, "Fee Not Paid");
euint256 value1 = input1.newEuint256(msg.sender);
euint256 value2 = input2.newEuint256(msg.sender);
// ... rest of function
}
```
**Multiple encrypted inputs (contract pays):**
```solidity theme={null}
function multiInput(bytes memory input1, bytes memory input2) external {
// Contract automatically pays 2 fees from its balance
euint256 value1 = input1.newEuint256(msg.sender);
euint256 value2 = input2.newEuint256(msg.sender);
// ... rest of function
}
```
## Operations That Don't Require Fees
All other Inco operations are free and don't require any fee payment:
### Math Operations
* `e.add`, `e.sub`, `e.mul`, `e.div`, `e.rem`
* `e.and`, `e.or`, `e.xor`, `e.shr`, `e.shl`, `e.rotr`, `e.rotl`
### Comparison Operations
* `e.eq`, `e.ne`, `e.ge`, `e.gt`, `e.le`, `e.lt`
* `e.min`, `e.max`, `e.not`
### Multiplexer Operations
* `e.select`
### Trivial Encryption (no external input)
* `e.asEuint256(uint256)` - Convert known uint256 to euint256
* `e.asEbool(bool)` - Convert known bool to ebool
### Access Control
* `e.allow`, `e.allowThis`, `e.isAllowed`
## Fee Best Practices
### For User-Paid Fees
#### Always Check Fees Before Operations
```solidity theme={null}
function _requireFee(uint256 ciphertextCount) internal view {
require(msg.value >= inco.getFee() * ciphertextCount, "Insufficient fee");
}
```
#### Calculate Ciphertext Count Accurately
Count each `newEuint256`, `newEbool` or `newEaddress` call in your function to ensure you charge the correct total fee.
### For Contract-Paid Fees
#### Monitor Contract Balance
```solidity theme={null}
function getContractFeeBalance() external view returns (uint256) {
return address(this).balance;
}
function isBalanceSufficient(uint256 requiredFees) internal view returns (bool) {
return address(this).balance >= requiredFees;
}
```
#### Implement Balance Management
```solidity theme={null}
function depositFees() external payable {
// Allow topping up contract balance
}
function withdrawFees(uint256 amount) external onlyOwner {
require(address(this).balance >= amount, "Insufficient balance");
require(amount <= address(this).balance - minimumReserve, "Cannot withdraw below minimum reserve");
payable(owner()).transfer(amount);
}
```
### General Best Practices
#### Handle Fee Changes
Fees may change over time. Always use `inco.getFee()` rather than hardcoding fee amounts.
#### Test Fee Requirements
When testing contracts, ensure sufficient funds for both approaches:
```solidity theme={null}
// For user-paid fees in Foundry tests
vm.deal(user, inco.getFee() * 2); // User needs ETH for fees
// For contract-paid fees in Foundry tests
vm.deal(address(contract), inco.getFee() * 10); // Contract needs ETH balance
```
## Common Fee-Related Errors
### User-Paid Fee Errors
* **"Fee Not Paid"**: Transaction reverted due to insufficient `msg.value`
* **Overpaying**: While allowed, unnecessary ETH is consumed as gas
* **Fee changes**: Contract fails if fees increase between deployment and usage
### Contract-Paid Fee Errors
* **"Insufficient contract balance"**: Contract doesn't have enough ETH to pay fees
* **"Below minimum reserve"**: Withdrawal attempts that would leave insufficient funds
* **"Contract balance depleted"**: Functions fail when contract runs out of ETH during high usage
**Important:** Encrypted input operations (`newEuint256`, `newEbool`, `newEaddress`) require
fees because they involve off-chain decryption and processing within Inco's
Trusted Execution Environment (TEE). All other operations are performed
symbolically on-chain and are therefore free.
# Library Reference
Source: https://docs.inco.org/quickstart/lib-reference
All functions exposed by the Inco library
## Installation
```bash npm theme={null}
npm install @inco/lightning
```
```bash yarn theme={null}
yarn add @inco/lightning
```
```bash bun theme={null}
bun add @inco/lightning
```
## Types
* `ebool`: Encrypted `bool`
* `euint256`: Encrypted `uint256`
* `eaddress`: Encrypted `address`
## Math operations
All arithmetic operations return an `euint256`.
All binary operations may use either an `euint256` or a regular `uint256` as the first or second argument, or two `euint256`s.
Bitwise operations work on both `euint256` and `ebool` types, and may use either encrypted or plain values as arguments.
| Name | Function | Type | Returns |
| -------------- | -------- | ------ | ----------------- |
| Addition | `e.add` | Binary | euint256 |
| Subtraction | `e.sub` | Binary | euint256 |
| Multiplication | `e.mul` | Binary | euint256 |
| Division | `e.div` | Binary | euint256 |
| Remainder | `e.rem` | Binary | euint256 |
| BitAnd | `e.and` | Binary | euint256 or ebool |
| BitOr | `e.or` | Binary | euint256 or ebool |
| BitXor | `e.xor` | Binary | euint256 or ebool |
| Shift Right | `e.shr` | Binary | euint256 |
| Shift Left | `e.shl` | Binary | euint256 |
| Rotate Right | `e.rotr` | Binary | euint256 |
| Rotate Left | `e.rotl` | Binary | euint256 |
## Comparison operations
| Name | Function | Type | Returns | Notes |
| --------------------- | -------- | ------ | -------- | ---------------------------------------------------------------- |
| Equal | `e.eq` | Binary | ebool | Works with euint256, eaddress, and combinations with plain types |
| Not equal | `e.ne` | Binary | ebool | Works with euint256, eaddress, and combinations with plain types |
| Greater than or equal | `e.ge` | Binary | ebool | euint256 only |
| Greater than | `e.gt` | Binary | ebool | euint256 only |
| Less than or equal | `e.le` | Binary | ebool | euint256 only |
| Less than | `e.lt` | Binary | ebool | euint256 only |
| Min | `e.min` | Binary | euint256 | euint256 only |
| Max | `e.max` | Binary | euint256 | euint256 only |
| Not | `e.not` | Unary | ebool | ebool only |
## Multiplexer
* `e.select(ebool, euint256, euint256) returns(euint256)`: Select between two `euint256`s based on an `ebool` condition
* `e.select(ebool, ebool, ebool) returns(ebool)`: Select between two `ebool`s based on an `ebool` condition
* `e.select(ebool, eaddress, eaddress) returns(eaddress)`: Select between two `eaddress`es based on an `ebool` condition
## Random Functions
All random functions require payment of the Inco fee.
* `e.rand() returns(euint256)`: Generate a random `euint256` value
* `e.randBounded(uint256) returns(euint256)`: Generate a random `euint256` value bounded by a `uint256` upper limit
* `e.randBounded(euint256) returns(euint256)`: Generate a random `euint256` value bounded by an `euint256` upper limit
## Inputs
* `e.asEuint256(uint256) returns(euint256)`: Convert a `uint256` to an `euint256` (trivial encrypt)
* `e.asEaddress(address) returns(eaddress)`: Convert an `address` to an `eaddress` (trivial encrypt)
* `e.newEuint256(bytes memory input) returns(euint256)`: Create a new `euint256` from a ciphertext
* `e.newEbool(bytes memory input) returns(ebool)`: Create a new `ebool` from a ciphertext
* `e.newEaddress(bytes memory input) returns(eaddress)`: Create a new `eaddress` from a ciphertext
## Type Casting
* `e.asEuint256(ebool) returns(euint256)`: Cast an `ebool` to an `euint256`
## Access control
* `e.allow(euint256, address)`: Allow a user to access an `euint256` value permanently
* `e.allow(ebool, address)`: Allow a user to access an `ebool` value permanently
* `e.allow(eaddress, address)`: Allow a user to access an `eaddress` value permanently
* `e.allowThis(euint256)`: Allow the current contract to access an `euint256` value permanently
* `e.allowThis(ebool)`: Allow the current contract to access an `ebool` value permanently
* `e.allowThis(eaddress)`: Allow the current contract to access an `eaddress` value permanently
* `e.reveal(euint256)`: Make an `euint256` value publicly accessible
* `e.reveal(ebool)`: Make an `ebool` value publicly accessible
* `e.reveal(eaddress)`: Make an `eaddress` value publicly accessible
* `e.isAllowed(address, euint256) returns(bool)`: Check if a user is allowed to access an `euint256` value
# Dynamic
Source: https://docs.inco.org/quickstart/wallets/dynamic
Set up Dynamic wallet integration with Inco
## Scaffold
```bash npm theme={null}
npx create-inco-app@latest my-app --wallet dynamic --framework hardhat --chain evm --yes
```
```bash pnpm theme={null}
pnpm create inco-app@latest my-app --wallet dynamic --framework hardhat --chain evm --yes
```
```bash yarn theme={null}
yarn create inco-app my-app --wallet dynamic --framework hardhat --chain evm --yes
```
```bash bun theme={null}
bunx create-inco-app@latest my-app --wallet dynamic --framework hardhat --chain evm --yes
```
This scaffolds the full monorepo with Dynamic as the wallet provider. For just the frontend, add `--template frontend`.
## Environment Setup
Get your Environment ID from [app.dynamic.xyz](https://app.dynamic.xyz) and set it in `frontend/.env`:
```bash frontend/.env theme={null}
# Base network: "testnet" (Base Sepolia, default) or "mainnet" (Base Mainnet)
NEXT_PUBLIC_NETWORK=testnet
NEXT_PUBLIC_DYNAMIC_ENVIRONMENT_ID=your_environment_id_here
# Your deployed contract address
NEXT_PUBLIC_CONFLOTTERY_ADDRESS=
```
## Provider Setup
Dynamic wraps your app with `DynamicContextProvider` + a wagmi connector (`DynamicWagmiConnector`). The EVM network it shows is built from `activeChain` in `lib/network.ts`, which follows `NEXT_PUBLIC_NETWORK` — no per-provider chain edits needed.
```tsx components/Providers.tsx theme={null}
"use client";
import { ReactNode } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { WagmiProvider, createConfig, http } from "wagmi";
import {
DynamicContextProvider,
DynamicWidget,
} from "@dynamic-labs/sdk-react-core";
import { EthereumWalletConnectors } from "@dynamic-labs/ethereum";
import { DynamicWagmiConnector } from "@dynamic-labs/wagmi-connector";
import { ThemeProvider } from "next-themes";
import { activeChain } from "@/lib/network";
const queryClient = new QueryClient();
const environmentId = process.env.NEXT_PUBLIC_DYNAMIC_ENVIRONMENT_ID || "";
const config = createConfig({
chains: [activeChain],
multiInjectedProviderDiscovery: false,
transports: {
[activeChain.id]: http(),
},
ssr: true,
});
const evmNetworks = [
{
blockExplorerUrls: [activeChain.blockExplorers?.default.url ?? ""],
chainId: activeChain.id,
name: activeChain.name,
rpcUrls: [activeChain.rpcUrls.default.http[0]],
iconUrls: ["https://avatars.githubusercontent.com/u/108554348?v=4"],
nativeCurrency: activeChain.nativeCurrency,
networkId: activeChain.id,
},
];
const Providers = ({ children }: { children: ReactNode }) => {
if (!environmentId) {
console.warn(
"Missing NEXT_PUBLIC_DYNAMIC_ENVIRONMENT_ID. Get one at https://app.dynamic.xyz/"
);
}
return (
{children}
);
};
export { Providers };
```
**Provider hierarchy:** `ThemeProvider` → `DynamicContextProvider` → `WagmiProvider` → `QueryClientProvider` → `DynamicWagmiConnector`
## Inco SDK Integration
The Inco SDK works with the `walletClient` provided by wagmi (which Dynamic supplies via `DynamicWagmiConnector`). The network-aware client comes from `lib/network.ts`:
```tsx hooks/useConfLottery.ts theme={null}
import { getIncoLightning } from "@/lib/network";
import { handleTypes } from "@inco/lightning-js";
import { useAccount, useWalletClient } from "wagmi";
import { parseEther } from "viem";
const { address } = useAccount();
const { data: walletClient } = useWalletClient();
// Network (Base Sepolia / Mainnet) is selected centrally in lib/network.ts via NEXT_PUBLIC_NETWORK.
const zap = await getIncoLightning();
// Encrypt a value before sending on-chain
const ciphertext = await zap.encrypt(parseEther(amount), {
accountAddress: address,
dappAddress: LOTTERY_ADDRESS,
handleType: handleTypes.euint256,
});
// Decrypt a handle with attestation (e.g. check if the user won)
const [result] = await zap.attestedDecrypt(walletClient, [encryptedHandle]);
const isWinner = result.plaintext.value; // boolean for an ebool handle
```
## Dependencies
| Package | Purpose |
| ------------------------------- | -------------------------- |
| `@dynamic-labs/sdk-react-core` | Dynamic auth & wallet UI |
| `@dynamic-labs/ethereum` | EVM wallet connectors |
| `@dynamic-labs/wagmi-connector` | Dynamic ↔ wagmi connector |
| `@inco/lightning-js` | Inco encryption/decryption |
| `wagmi` | EVM wallet hooks |
| `viem` | Ethereum utilities |
# Para
Source: https://docs.inco.org/quickstart/wallets/para
Set up Para wallet integration with Inco
## Scaffold
```bash npm theme={null}
npx create-inco-app@latest my-app --wallet para --framework hardhat --chain evm --yes
```
```bash pnpm theme={null}
pnpm create inco-app@latest my-app --wallet para --framework hardhat --chain evm --yes
```
```bash yarn theme={null}
yarn create inco-app my-app --wallet para --framework hardhat --chain evm --yes
```
```bash bun theme={null}
bunx create-inco-app@latest my-app --wallet para --framework hardhat --chain evm --yes
```
This scaffolds the full monorepo with Para as the wallet provider. For just the frontend, add `--template frontend`.
## Environment Setup
Get your API key from [developer.getpara.com](https://developer.getpara.com) and set it in `frontend/.env`:
```bash frontend/.env theme={null}
# Base network: "testnet" (Base Sepolia, default) or "mainnet" (Base Mainnet)
NEXT_PUBLIC_NETWORK=testnet
NEXT_PUBLIC_PARA_API_KEY=your_api_key_here
NEXT_PUBLIC_PARA_ENVIRONMENT=BETA
# Your deployed contract address
NEXT_PUBLIC_CONFLOTTERY_ADDRESS=
```
## Provider Setup
Para wraps your app with `ParaProvider`, which handles wallet connections, embedded wallets, and external wallet support (MetaMask, Coinbase, WalletConnect, Rainbow) out of the box. The chain comes from `activeChain` in `lib/network.ts`, which follows `NEXT_PUBLIC_NETWORK` — no per-provider chain edits needed.
```tsx components/Providers.tsx theme={null}
"use client";
import { ReactNode } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ParaProvider } from "@getpara/react-sdk";
import { Environment } from "@getpara/react-sdk";
import { http } from "wagmi";
import { ThemeProvider } from "next-themes";
import { activeChain } from "@/lib/network";
const queryClient = new QueryClient();
const apiKey = process.env.NEXT_PUBLIC_PARA_API_KEY || "";
const environment =
(process.env.NEXT_PUBLIC_PARA_ENVIRONMENT as Environment) ||
Environment.BETA;
const Providers = ({ children }: { children: ReactNode }) => {
if (!apiKey) {
console.warn(
"Missing NEXT_PUBLIC_PARA_API_KEY. Get one at https://developer.getpara.com/"
);
}
return (
{children}
);
};
export { Providers };
```
**Provider hierarchy:** `ThemeProvider` → `QueryClientProvider` → `ParaProvider`
Para's `ParaProvider` internally manages wagmi configuration, so you don't need a separate `WagmiProvider`. The `externalWalletConfig` lets you specify which external wallets to support alongside Para's embedded wallets.
## Inco SDK Integration
The Inco SDK works with the `walletClient` provided by wagmi (which Para supplies under the hood). The network-aware client comes from `lib/network.ts`:
```tsx hooks/useConfLottery.ts theme={null}
import { getIncoLightning } from "@/lib/network";
import { handleTypes } from "@inco/lightning-js";
import { useAccount, useWalletClient } from "wagmi";
import { parseEther } from "viem";
const { address } = useAccount();
const { data: walletClient } = useWalletClient();
// Network (Base Sepolia / Mainnet) is selected centrally in lib/network.ts via NEXT_PUBLIC_NETWORK.
const zap = await getIncoLightning();
// Encrypt a value before sending on-chain
const ciphertext = await zap.encrypt(parseEther(amount), {
accountAddress: address,
dappAddress: LOTTERY_ADDRESS,
handleType: handleTypes.euint256,
});
// Decrypt a handle with attestation (e.g. check if the user won)
const [result] = await zap.attestedDecrypt(walletClient, [encryptedHandle]);
const isWinner = result.plaintext.value; // boolean for an ebool handle
```
The key pattern: Para provides the `walletClient` via wagmi, which the Inco SDK uses for signing attestation requests during `attestedDecrypt`.
## Dependencies
| Package | Purpose |
| -------------------- | -------------------------- |
| `@getpara/react-sdk` | Para wallet SDK |
| `@inco/lightning-js` | Inco encryption/decryption |
| `wagmi` | EVM wallet hooks |
| `viem` | Ethereum utilities |
# Privy
Source: https://docs.inco.org/quickstart/wallets/privy
Set up Privy wallet integration with Inco
## Scaffold
```bash npm theme={null}
npx create-inco-app@latest my-app --wallet privy --framework hardhat --chain evm --yes
```
```bash pnpm theme={null}
pnpm create inco-app@latest my-app --wallet privy --framework hardhat --chain evm --yes
```
```bash yarn theme={null}
yarn create inco-app my-app --wallet privy --framework hardhat --chain evm --yes
```
```bash bun theme={null}
bunx create-inco-app@latest my-app --wallet privy --framework hardhat --chain evm --yes
```
This scaffolds the full monorepo with Privy as the wallet provider. For just the frontend, add `--template frontend`.
## Environment Setup
Get your App ID from [dashboard.privy.io](https://dashboard.privy.io) and set it in `frontend/.env`:
```bash frontend/.env theme={null}
# Base network: "testnet" (Base Sepolia, default) or "mainnet" (Base Mainnet)
NEXT_PUBLIC_NETWORK=testnet
NEXT_PUBLIC_PRIVY_APP_ID=your_app_id_here
# Your deployed contract address
NEXT_PUBLIC_CONFLOTTERY_ADDRESS=
```
## Provider Setup
Privy wraps your app with `PrivyProvider` and Privy's wagmi connector (`@privy-io/wagmi`), giving you email, social, and embedded-wallet login. The chain comes from `activeChain` in `lib/network.ts`, which follows `NEXT_PUBLIC_NETWORK` — no per-provider chain edits needed.
```tsx components/Providers.tsx theme={null}
"use client";
import { ReactNode } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { PrivyProvider } from "@privy-io/react-auth";
import { WagmiProvider, createConfig } from "@privy-io/wagmi";
import { http } from "wagmi";
import { ThemeProvider } from "next-themes";
import { activeChain } from "@/lib/network";
const queryClient = new QueryClient();
const appId = process.env.NEXT_PUBLIC_PRIVY_APP_ID || "";
const config = createConfig({
chains: [activeChain],
transports: {
[activeChain.id]: http(),
},
ssr: true,
});
const Providers = ({ children }: { children: ReactNode }) => {
if (!appId) {
console.warn(
"Missing NEXT_PUBLIC_PRIVY_APP_ID. Get one at https://dashboard.privy.io/"
);
}
return (
{children}
);
};
export { Providers };
```
**Provider hierarchy:** `ThemeProvider` → `PrivyProvider` → `QueryClientProvider` → `WagmiProvider`
Note the wagmi `createConfig` is imported from `@privy-io/wagmi` (not `wagmi`), so Privy's embedded wallets connect through wagmi automatically.
## Inco SDK Integration
The Inco SDK works with the `walletClient` provided by wagmi (which Privy supplies). The network-aware client comes from `lib/network.ts`:
```tsx hooks/useConfLottery.ts theme={null}
import { getIncoLightning } from "@/lib/network";
import { handleTypes } from "@inco/lightning-js";
import { useAccount, useWalletClient } from "wagmi";
import { parseEther } from "viem";
const { address } = useAccount();
const { data: walletClient } = useWalletClient();
// Network (Base Sepolia / Mainnet) is selected centrally in lib/network.ts via NEXT_PUBLIC_NETWORK.
const zap = await getIncoLightning();
// Encrypt a value before sending on-chain
const ciphertext = await zap.encrypt(parseEther(amount), {
accountAddress: address,
dappAddress: LOTTERY_ADDRESS,
handleType: handleTypes.euint256,
});
// Decrypt a handle with attestation (e.g. check if the user won)
const [result] = await zap.attestedDecrypt(walletClient, [encryptedHandle]);
const isWinner = result.plaintext.value; // boolean for an ebool handle
```
## Dependencies
| Package | Purpose |
| ---------------------- | --------------------------------------- |
| `@privy-io/react-auth` | Privy authentication & embedded wallets |
| `@privy-io/wagmi` | Privy ↔ wagmi connector |
| `@inco/lightning-js` | Inco encryption/decryption |
| `wagmi` | EVM wallet hooks |
| `viem` | Ethereum utilities |
# RainbowKit
Source: https://docs.inco.org/quickstart/wallets/rainbowkit
Set up RainbowKit wallet integration with Inco
## Scaffold
```bash npm theme={null}
npx create-inco-app@latest my-app --wallet rainbowkit --framework hardhat --chain evm --yes
```
```bash pnpm theme={null}
pnpm create inco-app@latest my-app --wallet rainbowkit --framework hardhat --chain evm --yes
```
```bash yarn theme={null}
yarn create inco-app my-app --wallet rainbowkit --framework hardhat --chain evm --yes
```
```bash bun theme={null}
bunx create-inco-app@latest my-app --wallet rainbowkit --framework hardhat --chain evm --yes
```
This scaffolds the full monorepo with RainbowKit as the wallet provider. For just the frontend, add `--template frontend`.
## Environment Setup
Get a WalletConnect Project ID from [cloud.walletconnect.com](https://cloud.walletconnect.com) and set it in `frontend/.env`:
```bash frontend/.env theme={null}
# Base network: "testnet" (Base Sepolia, default) or "mainnet" (Base Mainnet)
NEXT_PUBLIC_NETWORK=testnet
NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID=your_project_id_here
# Your deployed contract address
NEXT_PUBLIC_CONFLOTTERY_ADDRESS=
```
Without a Project ID, the template falls back to an injected-wallet-only config (no WalletConnect), so it still runs locally.
## Provider Setup
RainbowKit wraps your app with `WagmiProvider` + `RainbowKitProvider`. The chain comes from `activeChain` in `lib/network.ts`, which follows `NEXT_PUBLIC_NETWORK` — no per-provider chain edits needed.
```tsx components/Providers.tsx theme={null}
"use client";
import { ReactNode, useState, useEffect } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { WagmiProvider, createConfig, http } from "wagmi";
import {
getDefaultConfig,
RainbowKitProvider,
darkTheme,
lightTheme,
} from "@rainbow-me/rainbowkit";
import { ThemeProvider, useTheme } from "next-themes";
import { activeChain } from "@/lib/network";
const queryClient = new QueryClient();
const projectId = process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID || "";
const config = projectId
? getDefaultConfig({
appName: "inco confidential lottery",
projectId,
chains: [activeChain],
ssr: true,
})
: createConfig({
chains: [activeChain],
transports: {
[activeChain.id]: http(),
},
ssr: true,
});
// Inner provider that uses theme context
const RainbowKitWithTheme = ({ children }: { children: ReactNode }) => {
const { resolvedTheme } = useTheme();
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
const rainbowTheme =
mounted && resolvedTheme === "light"
? lightTheme({ accentColor: "#262626", accentColorForeground: "#fafafa", borderRadius: "none" })
: darkTheme({ accentColor: "#d4d4d4", accentColorForeground: "#0a0a0a", borderRadius: "none" });
return (
{children}
);
};
const Providers = ({ children }: { children: ReactNode }) => {
if (!projectId) {
console.warn(
"Missing NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID. Get one at https://cloud.walletconnect.com/"
);
}
return (
{children}
);
};
export { Providers };
```
**Provider hierarchy:** `ThemeProvider` → `WagmiProvider` → `QueryClientProvider` → `RainbowKitProvider`
## Inco SDK Integration
The Inco SDK works with the `walletClient` provided by wagmi (which RainbowKit supplies). The network-aware client comes from `lib/network.ts`:
```tsx hooks/useConfLottery.ts theme={null}
import { getIncoLightning } from "@/lib/network";
import { handleTypes } from "@inco/lightning-js";
import { useAccount, useWalletClient } from "wagmi";
import { parseEther } from "viem";
const { address } = useAccount();
const { data: walletClient } = useWalletClient();
// Network (Base Sepolia / Mainnet) is selected centrally in lib/network.ts via NEXT_PUBLIC_NETWORK.
const zap = await getIncoLightning();
// Encrypt a value before sending on-chain
const ciphertext = await zap.encrypt(parseEther(amount), {
accountAddress: address,
dappAddress: LOTTERY_ADDRESS,
handleType: handleTypes.euint256,
});
// Decrypt a handle with attestation (e.g. check if the user won)
const [result] = await zap.attestedDecrypt(walletClient, [encryptedHandle]);
const isWinner = result.plaintext.value; // boolean for an ebool handle
```
## Dependencies
| Package | Purpose |
| ------------------------ | --------------------------- |
| `@rainbow-me/rainbowkit` | RainbowKit wallet connector |
| `@inco/lightning-js` | Inco encryption/decryption |
| `wagmi` | EVM wallet hooks |
| `viem` | Ethereum utilities |
# Reown
Source: https://docs.inco.org/quickstart/wallets/reown
Set up Reown (AppKit) wallet integration with Inco
## Scaffold
```bash npm theme={null}
npx create-inco-app@latest my-app --wallet reown --framework hardhat --chain evm --yes
```
```bash pnpm theme={null}
pnpm create inco-app@latest my-app --wallet reown --framework hardhat --chain evm --yes
```
```bash yarn theme={null}
yarn create inco-app my-app --wallet reown --framework hardhat --chain evm --yes
```
```bash bun theme={null}
bunx create-inco-app@latest my-app --wallet reown --framework hardhat --chain evm --yes
```
This scaffolds the full monorepo with Reown (AppKit, formerly Web3Modal) as the wallet provider. For just the frontend, add `--template frontend`.
## Environment Setup
Get a Project ID from [cloud.reown.com](https://cloud.reown.com) and set it in `frontend/.env`:
```bash frontend/.env theme={null}
# Base network: "testnet" (Base Sepolia, default) or "mainnet" (Base Mainnet)
NEXT_PUBLIC_NETWORK=testnet
NEXT_PUBLIC_REOWN_PROJECT_ID=your_project_id_here
# Your deployed contract address
NEXT_PUBLIC_CONFLOTTERY_ADDRESS=
```
A Project ID is required for Reown — without it, the app renders a "Missing configuration" screen instead of connecting.
## Provider Setup
Reown initializes AppKit with a `WagmiAdapter` and wraps your app in `WagmiProvider`. The network comes from `activeChain` in `lib/network.ts`, which follows `NEXT_PUBLIC_NETWORK` — no per-provider chain edits needed.
```tsx components/Providers.tsx theme={null}
"use client";
import { ReactNode, useState, useEffect } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { WagmiProvider, type Config } from "wagmi";
import { createAppKit } from "@reown/appkit/react";
import { WagmiAdapter } from "@reown/appkit-adapter-wagmi";
import { ThemeProvider } from "next-themes";
import { activeChain } from "@/lib/network";
const queryClient = new QueryClient();
const projectId = process.env.NEXT_PUBLIC_REOWN_PROJECT_ID || "";
let wagmiAdapter: WagmiAdapter | null = null;
let isAppKitInitialized = false;
function initializeAppKit() {
if (isAppKitInitialized || !projectId) return;
wagmiAdapter = new WagmiAdapter({
networks: [activeChain],
projectId,
ssr: true,
});
createAppKit({
adapters: [wagmiAdapter],
networks: [activeChain],
projectId,
features: {
analytics: true,
},
themeMode: "dark",
});
isAppKitInitialized = true;
}
const Providers = ({ children }: { children: ReactNode }) => {
const [mounted, setMounted] = useState(false);
useEffect(() => {
if (!projectId) {
console.warn(
"Missing NEXT_PUBLIC_REOWN_PROJECT_ID. Get one at https://cloud.reown.com/"
);
} else {
initializeAppKit();
}
setMounted(true);
}, []);
if (!projectId) {
return (
Missing configuration
Add NEXT_PUBLIC_REOWN_PROJECT_ID to your .env file
);
}
if (!mounted || !wagmiAdapter) {
return (
);
}
return (
{children}
);
};
export { Providers };
```
**Provider hierarchy:** `ThemeProvider` → `WagmiProvider` (from the AppKit adapter) → `QueryClientProvider`
## Inco SDK Integration
The Inco SDK works with the `walletClient` provided by wagmi (which Reown/AppKit supplies). The network-aware client comes from `lib/network.ts`:
```tsx hooks/useConfLottery.ts theme={null}
import { getIncoLightning } from "@/lib/network";
import { handleTypes } from "@inco/lightning-js";
import { useAccount, useWalletClient } from "wagmi";
import { parseEther } from "viem";
const { address } = useAccount();
const { data: walletClient } = useWalletClient();
// Network (Base Sepolia / Mainnet) is selected centrally in lib/network.ts via NEXT_PUBLIC_NETWORK.
const zap = await getIncoLightning();
// Encrypt a value before sending on-chain
const ciphertext = await zap.encrypt(parseEther(amount), {
accountAddress: address,
dappAddress: LOTTERY_ADDRESS,
handleType: handleTypes.euint256,
});
// Decrypt a handle with attestation (e.g. check if the user won)
const [result] = await zap.attestedDecrypt(walletClient, [encryptedHandle]);
const isWinner = result.plaintext.value; // boolean for an ebool handle
```
## Dependencies
| Package | Purpose |
| ----------------------------- | ---------------------------- |
| `@reown/appkit` | Reown AppKit (WalletConnect) |
| `@reown/appkit-adapter-wagmi` | AppKit ↔ wagmi adapter |
| `@inco/lightning-js` | Inco encryption/decryption |
| `wagmi` | EVM wallet hooks |
| `viem` | Ethereum utilities |
# Build a Confidential Token
Source: https://docs.inco.org/tutorials/confidential-token
This tutorial will guide you through creating and deploying a confidential fungible token. You can choose your preferred development environment
Deploy using Foundry - Recommended for Solidity developers
Deploy using Hardhat - Recommended for TypeScript and testing
Choose your preferred development environment above to get started.
# Import Inco in your contract
Source: https://docs.inco.org/tutorials/confidential-token/foundry/import-in-your-contract
Use the Inco library to enable confidentiality in your contract
To start using Inco features in your contract, all you need is to add this line at the top of your solidity file:
```Solidity theme={null}
import {e, ebool, euint256, inco} from "@inco/lightning/src/Lib.sol";
```
and add this line at the top of the contract body:
```Solidity theme={null}
using e for *;
```
Now you have access to encrypted types and operations in your contract. Here is a full example of a simple fungible token:
The following example is present with comments explaining the code [here](https://github.com/Inco-fhevm/lightning-rod/blob/main/contracts/src/SimpleConfidentialToken.sol) in the [lightning-rod template](https://github.com/Inco-fhevm/lightning-rod).
```Solidity theme={null}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
// This line of import is all you need to get started with Inco
import {euint256, ebool, e, inco} from "@inco/lightning/src/Lib.sol";
/// @notice a fungible token whose balances and transfer values are confidential
contract SimpleConfidentialToken {
using e for euint256;
using e for ebool;
using e for uint256;
using e for bytes;
using e for address;
// since balances are represented by handles, just calling balanceOf() without having the decryption access
// on the corresponding handle won't allow to know the actual balance
mapping(address => euint256) public balanceOf;
constructor() {
// mint 1000 tokens to the deployer
// we consider this token to have 9 decimals, which is standard for confidential fungible tokens
// units are GWEI instead of WADs (WADs being 18 decimals, used in ERC20)
// `uint256(1000 * 1e9).asEuint256()` is a trivial encrypt, i.e it converts a known value into
// an e-type. We can also write `e.asEuint256(1000 * 1e9);`
balanceOf[msg.sender] = uint256(1000 * 1e9).asEuint256();
}
// this function is meant to be called by EOAs or smart wallets as valueInput is an encrypted amount that should
// be generated using @inco/lightning-js sdk
function transfer(address to, bytes memory valueInput) external payable returns (ebool) {
require(msg.value == inco.getFee(),"Fee not paid");
// `newInput` returns an euint256 from an encrypted input, if the encrypted input is malformed, it will return
// an euint256 with a value of 0. Depending on how malformed the input is, an external observer may know
// that the fallback 0 value has been returned. Just use the js sdk to avoid that.
// The second parameter of newInput will receive decryption rights on the euint256, and should be the account
// that created the encrypted input.
euint256 value = valueInput.newEuint256(msg.sender);
return _transfer(to, value);
}
// this function is meant to be called by smart contracts, as it is using an existing euint256.
// caller has to use `value.allow(tokenAddress)` before calling this function or it will revert.
function transfer(address to, euint256 value) public returns (ebool success) {
// always perform this check on encrypted parameters. In this case, a malicious caller could try to pass
// the handle corresponding of a victim's balance to deduce its value, it wouldn't revert without this check
// as this token contract holds allowance on the balances of all holders.
require(msg.sender.isAllowed(value), "SimpleConfidentialToken: unauthorized value handle access");
return _transfer(to, value);
}
function _transfer(address to, euint256 value) internal returns (ebool success) {
// check if the sender has enough balance to transfer the value
success = balanceOf[msg.sender].ge(value);
// Solidity can't revert on an insufficient balance as it has no way of knowing the actual value of the ebool.
// Instead, we use the multiplexer pattern, replacing the actual transferred value for a 0 (trivial encrypt)
// if the balance is insufficient, which is equivalent to doing nothing.
euint256 transferredValue = success.select(value, uint256(0).asEuint256());
// saving handles used multiple times in memory variables to save some gas
euint256 senderNewBalance = balanceOf[msg.sender].sub(transferredValue);
euint256 receiverNewBalance = balanceOf[to].add(transferredValue);
balanceOf[msg.sender] = senderNewBalance;
balanceOf[to] = receiverNewBalance;
// allow the sender to see its new balance
senderNewBalance.allow(msg.sender);
// allow the receiver to see its new balance
receiverNewBalance.allow(to);
// allow this contract to be able to compute over the new balances in future transfers
senderNewBalance.allowThis();
receiverNewBalance.allowThis();
// let the caller know if the transfer was successful
success.allow(msg.sender);
}
}
```
This contract is explained in depth in the [Concepts Guide](/guide/handles).
# Setup
Source: https://docs.inco.org/tutorials/confidential-token/foundry/setup
Setup your repo
## Using the lightning-rod template (recommended)
We recommend using our [template](https://github.com/Inco-fhevm/lightning-rod/tree/main) which comes with foundry already setup.
```bash theme={null}
git clone git@github.com:Inco-fhevm/lightning-rod.git
cd lightning-rod
bun install
```
Using the template, you may want to skip to the [cheatcodes reference](/quickstart/cheatcodes-reference).
## Or setup manually
You do not need to follow these steps if you are using the lightning-rod template.
Follow these steps to add inco to your existing project, or manually setup a new one.
### Download the inco libraries
Inco uses npm packages to provide its solidity library.
```bash theme={null}
bun add @inco/lightning
```
Alternatively, you can use npm/yarn/pnpm.
### Setup remappings
Create a file `remappings.txt` at the root of your contracts directory.
```bash theme={null}
touch remappings.txt
```
Edit your remappings paths according to your setup.
```txt theme={null}
forge-std/=your/path/to/forge-std/src/
ds-test/=your/path/to/ds-test/src/
@inco/=path/to/your/node_modules/@inco/
@openzeppelin/=path/to/your/node_modules/@openzeppelin/
```
Due to how solidity imports and remappings work, your remappings have to follow
the idiomatic form. Here are the requirements so your project compiles while using inco:
* left to the `=` sign, have the following names
* `forge-std/`
* `ds-test/`
* `@inco/`
* `@openzeppelin/`
* right to the `=` sign, have the path to the corresponding library
* `forge-std/` should point to the `src/` directory of your local `forge-std` library
* `ds-test/` should point to the `src/` directory of your local `ds-test` library
* `@inco/` should point to the `@inco` directory in your `node_modules` directory, and not to the `@inco/lightning` or `@inco/shared` directories
* In the same way `@openzeppelin/` should point to the `@openzeppelin` directory in your `node_modules` directory
To simplify this process, we recommend using bun/npm to import all the dependencies (including `foundry-std` and `ds-test`) like so:
```bash theme={null}
bun add @inco/lightning https://github.com/dapphub/ds-test https://github.com/foundry-rs/forge-std @openzeppelin/contracts
```
and using this remapping file (supposing that your `node_modules` sit one directory up from your contracts directory):
```txt theme={null}
@openzeppelin/=../node_modules/@openzeppelin/
forge-std/=../node_modules/forge-std/src/
ds-test/=../node_modules/ds-test/src/
@inco/=../node_modules/@inco/
safe-smart-account/=../node_modules/@safe-global/safe-smart-account/contracts/
```
### Configure `foundry.toml`
Because `node_modules` sits **outside** your contracts directory, Foundry rejects the `../node_modules/…` imports (`Source … not found: File outside of allowed directories`) unless you allow that path. List it under `libs`:
```toml theme={null}
[profile.default]
src = "src"
libs = ["../node_modules"]
auto_detect_solc = true # or set solc = "0.8.29" — it must be 0.8.29 or newer
```
The `safe-smart-account/` remapping is needed to compile tests that extend `IncoTest` (see [Test your contract](/tutorials/confidential-token/foundry/test-your-contract)).
# Test your contract
Source: https://docs.inco.org/tutorials/confidential-token/foundry/test-your-contract
Test your contract in solidity, using Inco cheatcodes
In the package that comes the Inco library, an extension to the usual `Test` Foundry contract is provided.\
You can import it like this:
```Solidity theme={null}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
import {IncoTest} from "@inco/lightning/src/test/IncoTest.sol";
contract YourTest is IncoTest {
function testSomething() public {
// Your test code here
}
}
```
`IncoTest` extends Foundry's `Test` contract, and exposes useful Inco-specific cheatcodes to test your contract.\
If you are extending the `setUp` function, remember to call `super.setUp()` at the beginning of your function.
## Example
The following example is present with comments explaining the code [here](https://github.com/Inco-fhevm/lightning-rod/blob/main/contracts/src/test/TestSimpleConfidentialToken.t.sol) in the [lightning-rod template](https://github.com/Inco-fhevm/lightning-rod).
```Solidity theme={null}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
import {SimpleConfidentialToken} from "../SimpleConfidentialToken.sol";
import {IncoTest} from "@inco/lightning/src/test/IncoTest.sol";
import {GWEI} from "@inco/lightning/src/shared/TypeUtils.sol"; // 1 GWEI = 1e9
import {console} from "forge-std/console.sol";
import {inco, euint256, e} from "@inco/lightning/src/Lib.sol";
// IncoTest extends forge-std's Test
contract TestSimpleConfidentialToken is IncoTest {
SimpleConfidentialToken token;
function setUp() public override {
// always call the parent setUp() function, which deploys the mocked Inco infrastructure
super.setUp();
token = new SimpleConfidentialToken();
vm.deal(address(this), inco.getFee());
// Transfer 10 GWEI from the test contract (which received the initial mint) to Alice
// The test contract can use the euint256 version of transfer since it's a contract
euint256 transferAmount = e.asEuint256(10 * GWEI);
// Allow the test contract (sender) to use this value for the authorization check
// and allow the token contract to use this value in computations
e.allow(transferAmount, address(this));
e.allow(transferAmount, address(token));
token.transfer(alice, transferAmount);
processAllOperations();
// Verify Alice's balance
vm.prank(alice);
uint256 decryptedAliceBalance = getUint256Value(token.balanceOf(alice));
assertEq(decryptedAliceBalance, 10 * GWEI);
}
function testTransfer() public {
vm.deal(address(alice), inco.getFee());
bytes memory ciphertext = fakePrepareEuint256Ciphertext(1 * GWEI, alice, address(token));
vm.startPrank(alice);
token.transfer{value: inco.getFee()}(bob, ciphertext);
vm.stopPrank();
processAllOperations();
// Inco processes the operations over encrypted variables asynchronously offchain.
// call processAllOperations() to simulate this offchain processing, which will assign to each e-variable
// its encrypted value. if you don't call this function and try to simulate a decrypt on a handle
// resulting from an operation, it will revert.
// `getUint256Value` is a cheatcode returning the decrypted value of an euint256, without checking
// any access rights, it is useful in tests and doesn't exist in prod.
uint256 decryptedBobBalance = getUint256Value(token.balanceOf(bob));
uint256 decryptedAliceBalance = getUint256Value(token.balanceOf(alice));
assertEq(decryptedBobBalance, 1 * GWEI);
assertEq(decryptedAliceBalance, 9 * GWEI);
}
}
```
Once you are happy with the state of your contract, you can deploy it and Inco will react to its ops (Base Sepolia and Base mainnet are currently supported).
Read on for the reference of the available cheatcodes.
# Setting up Environment for Hardhat
Source: https://docs.inco.org/tutorials/confidential-token/hardhat
This is a quick start guide for deploying and understanding a confidential ERC20 using the [Hardhat template](https://github.com/Inco-fhevm/inco-lite-template).
We recommend installing nvm (Node Version Manager) first and then install Node.js with nvm.
* For Linux: The official Linux version can be found [here](https://github.com/nvm-sh/nvm) or follow [this tutorial](https://tecadmin.net/how-to-install-nvm-on-ubuntu-20-04/).
* For Windows, follow the [Readme guide](https://github.com/coreybutler/nvm-windows/blob/master/README.md#installation--upgrades).
* For Mac, you can follow this [tutorial](https://tecadmin.net/install-nvm-macos-with-homebrew/).
Install Node.js:
```bash theme={null}
nvm install node
```
Install pnpm:
```bash theme={null}
npm install -g pnpm
```
1. Clone the template project:
```bash theme={null}
git clone https://github.com/Inco-fhevm/inco-lite-template.git
cd inco-lite-template
```
2. Install dependencies:
```bash theme={null}
pnpm install
```
If `pnpm install` fails with `ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED` for `@safe-global/safe-smart-account`, allow its build script by adding the following to `package.json`, then re-run `pnpm install`:
```json theme={null}
"pnpm": { "onlyBuiltDependencies": ["@safe-global/safe-smart-account"] }
```
3. Set up `.env` file. You can use the values below, taken from the README:
```bash theme={null}
# This should be a private key funded with native tokens.
PRIVATE_KEY_ANVIL="0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"
PRIVATE_KEY_BASE_SEPOLIA=""
# This should be a seed phrase used to test functionalities with different accounts.
# You can send funds from the main wallet to this whenever needed.
SEED_PHRASE="garden cage click scene crystal fat message twice rubber club choice cool"
# This should be an RPC URL provided by a proper provider
# that supports the eth_getLogs() and eth_getFilteredLogs() methods.
LOCAL_CHAIN_RPC_URL="http://localhost:8545"
BASE_SEPOLIA_RPC_URL="https://base-sepolia-rpc.publicnode.com"
```
If you don't have a mnemonic, you can generate one using [this website](https://iancoleman.io/bip39/) or use our default test accounts.
We recommend using RPC providers instead of public endpoints for better log access.
4. Compile contracts:
```bash theme={null}
pnpm hardhat compile
```
5. Run a local Node
The current instructions will run a local node and a local covalidator. If you are using this template against another network, e.g. Base Sepolia, skip this step.
```bash theme={null}
docker compose up
```
6. Run tests (against the local node):
```bash theme={null}
pnpm test:local
```
## Deploying on Base Sepolia
After setting the `PRIVATE_KEY_BASE_SEPOLIA` and `BASE_SEPOLIA_RPC_URL` fields in the `.env` file, run the following command:
```bash theme={null}
pnpm hardhat ignition deploy ./ignition/modules/ConfidentialToken.ts --network baseSepolia
```
Then, you can make sure tests still pass with:
```bash theme={null}
pnpm test:testnet
```
## Next Step
Now that you have deployed and tested the contract, let's understand how it works.
# Complete Contract Implementation
Source: https://docs.inco.org/tutorials/confidential-token/hardhat/complete-contract
Full implementation of the confidential ERC20 token
Here's the complete implementation of the confidential ERC20 token contract. You can find this code in `ConfidentialERC20.sol` if you're using the Hardhat template.
```Solidity theme={null}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {inco, e, ebool, euint256} from "@inco/lightning/src/Lib.sol";
import "@openzeppelin/contracts/access/Ownable2Step.sol";
contract ConfidentialERC20 is Ownable2Step {
// Errors
error InsufficientFees();
// Events
event Transfer(address indexed from, address indexed to, euint256 amount);
event Approval(
address indexed owner,
address indexed spender,
euint256 amount
);
event Mint(address indexed to, uint256 amount);
event EncryptedMint(address indexed to, euint256 amount);
// State variables
euint256 public totalSupply;
string public _name;
string public _symbol;
uint8 public constant decimals = 18;
// Mappings for balances and allowances
mapping(address => euint256) internal balances;
mapping(address => mapping(address => euint256)) internal allowances;
// Constructor to set the token name, symbol, and owner
constructor() Ownable(msg.sender) {
_name = "Confidential USD";
_symbol = "cUSD";
}
// Helper functions
function _requireFee() internal view {
if (msg.value < inco.getFee()) revert InsufficientFees();
}
// Mint function to create tokens and add to the owner's balance
function mint(uint256 mintAmount) public virtual onlyOwner {
euint256 amount = e.asEuint256(mintAmount);
balances[owner()] = e.add(balances[owner()], amount);
e.allow(balances[owner()], address(this));
e.allow(balances[owner()], owner());
totalSupply = e.add(totalSupply, amount);
e.reveal(totalSupply);
emit Mint(owner(), mintAmount);
}
// Encrypted mint function to create tokens and add to the sender's balance
function encryptedMint(
bytes calldata encryptedAmount
) public payable virtual /*onlyOwner*/ {
_requireFee();
euint256 amount = e.newEuint256(encryptedAmount, msg.sender);
e.allow(amount, address(this));
if(euint256.unwrap(balances[msg.sender]) == bytes32(0)) {
balances[msg.sender] = amount;
} else {
balances[msg.sender] = e.add(balances[msg.sender], amount);
}
e.allow(balances[msg.sender], address(this));
e.allow(balances[msg.sender], owner());
e.allow(balances[msg.sender], msg.sender);
totalSupply = e.add(totalSupply, amount);
e.reveal(totalSupply);
emit EncryptedMint(msg.sender, amount);
}
// Transfer function for EOAs using encrypted inputs
function transfer(
address to,
bytes calldata encryptedAmount
) public payable virtual returns (bool) {
_requireFee();
transfer(
to,
e.newEuint256(encryptedAmount, msg.sender)
);
return true;
}
// Transfer function for contracts
function transfer(
address to,
euint256 amount
) public virtual returns (bool) {
e.allow(amount, address(this));
ebool canTransfer = e.ge(balances[msg.sender], amount);
_transfer(msg.sender, to, amount, canTransfer);
return true;
}
// Retrieves the balance handle of a specified wallet
function balanceOf(address wallet) public view virtual returns (euint256) {
return balances[wallet];
}
// Retrieves the total supply handle
function getTotalSupply() public view virtual returns (euint256) {
return totalSupply;
}
// Approve function for EOAs with encrypted inputs
function approve(
address spender,
bytes calldata encryptedAmount
) public payable virtual returns (bool) {
_requireFee();
approve(spender, e.newEuint256(encryptedAmount, msg.sender));
return true;
}
// Approve function for contracts
function approve(
address spender,
euint256 amount
) public virtual returns (bool) {
_approve(msg.sender, spender, amount);
emit Approval(msg.sender, spender, amount);
return true;
}
// Internal function to handle allowance approvals
function _approve(
address owner,
address spender,
euint256 amount
) internal virtual {
allowances[owner][spender] = amount;
e.allow(amount, address(this));
e.allow(amount, owner);
e.allow(amount, spender);
}
// Retrieves the allowance handle for a spender
function allowance(
address owner,
address spender
) public view virtual returns (euint256) {
return _allowance(owner, spender);
}
// Internal function to retrieve an allowance handle
function _allowance(
address owner,
address spender
) internal view virtual returns (euint256) {
return allowances[owner][spender];
}
// TransferFrom function for EOAs with encrypted inputs
function transferFrom(
address from,
address to,
bytes calldata encryptedAmount
) public payable virtual returns (bool) {
_requireFee();
transferFrom(
from,
to,
e.newEuint256(encryptedAmount, msg.sender)
);
return true;
}
// TransferFrom function for contracts
function transferFrom(
address from,
address to,
euint256 amount
) public virtual returns (bool) {
e.allow(amount, address(this));
ebool isTransferable = _updateAllowance(from, msg.sender, amount);
_transfer(from, to, amount, isTransferable);
return true;
}
function _updateAllowance(
address owner,
address spender,
euint256 amount
) internal virtual returns (ebool) {
euint256 currentAllowance = _allowance(owner, spender);
ebool allowedTransfer = e.ge(currentAllowance, amount);
ebool canTransfer = e.ge(balances[owner], amount);
ebool isTransferable = e.select(
canTransfer,
allowedTransfer,
e.asEbool(false)
);
_approve(
owner,
spender,
e.select(
isTransferable,
e.sub(currentAllowance, amount),
currentAllowance
)
);
return isTransferable;
}
// Internal transfer function for encrypted token transfer
function _transfer(
address from,
address to,
euint256 amount,
ebool isTransferable
) internal virtual {
euint256 transferValue = e.select(
isTransferable,
amount,
e.asEuint256(0)
);
if(euint256.unwrap(balances[to]) == bytes32(0)) {
balances[to] = transferValue;
} else {
balances[to] = e.add(balances[to], transferValue);
}
e.allow(balances[to], address(this));
e.allow(balances[to], to);
balances[from] = e.sub(balances[from], transferValue);
e.allow(balances[from], address(this));
e.allow(balances[from], from);
emit Transfer(from, to, transferValue);
}
}
```
## Contract Structure
* Inco libraries for encryption - OpenZeppelin for ownership management
* Public token details - Encrypted total supply - Encrypted balances and
allowances
* Standard ERC20 interface - Encrypted variants for privacy - Internal helpers
## Deployment
To deploy the contract using Hardhat Ignition:
1. Create a deployment module in `ignition/modules/ConfidentialToken.ts`:
```typescript theme={null}
import { buildModule } from "@nomicfoundation/hardhat-ignition/modules";
const ConfidentialERC20Module = buildModule("ConfidentialERC20Module", (m) => {
const confidentialERC20Module = m.contract("ConfidentialERC20");
return { confidentialERC20Module };
});
export default ConfidentialERC20Module;
```
2. Deploy using the following command:
```bash theme={null}
pnpm hardhat ignition deploy ./ignition/modules/ConfidentialToken.ts --network baseSepolia
```
3. Run tests to verify the deployment:
```bash theme={null}
pnpm test:testnet
```
The contract will be deployed with: - Name: "Confidential USD" - Symbol:
"cUSD" - Decimals: 18 - Owner: The deploying address (msg.sender)
Make sure to save the deployed contract address for future interactions.
You'll need it when integrating with your frontend or other contracts.
# Understanding the Confidential ERC-20
Source: https://docs.inco.org/tutorials/confidential-token/hardhat/contract-details
Deep dive into the confidential token implementation
We will be creating a confidential ERC20 contract that enables:
* Minting new tokens
* Transferring tokens between accounts
* Managing token allowances
* Keeping all amounts encrypted
* Using encrypted minting and transfers that require Inco execution fees
Learn how to set up the basic contract structure
Understand the core functionality implementation
See the full contract implementation
# Contract Functions
Source: https://docs.inco.org/tutorials/confidential-token/hardhat/contract-functions
Understanding the core functionality of the confidential token
## Constructor
The constructor sets up the initial token configuration:
```Solidity theme={null}
constructor() Ownable(msg.sender) {
_name = "Confidential USD";
_symbol = "cUSD";
}
```
## Minting Tokens
There are two minting functions for different use cases, plus a helper for enforcing fees:
```Solidity theme={null}
// Helper to enforce that the caller pays the Inco fee
function _requireFee() internal view {
if (msg.value < inco.getFee()) revert InsufficientFees();
}
// Standard minting with plaintext amount (owner only)
function mint(uint256 mintAmount) public virtual onlyOwner {
euint256 amount = e.asEuint256(mintAmount);
balances[owner()] = e.add(balances[owner()], amount);
e.allow(balances[owner()], address(this));
e.allow(balances[owner()], owner());
totalSupply = e.add(totalSupply, amount);
e.reveal(totalSupply);
emit Mint(owner(), mintAmount);
}
// Minting with encrypted amount (fee required)
function encryptedMint(
bytes calldata encryptedAmount
) public payable virtual /*onlyOwner*/ {
_requireFee();
euint256 amount = e.newEuint256(encryptedAmount, msg.sender);
e.allow(amount, address(this));
if(euint256.unwrap(balances[msg.sender]) == bytes32(0)) {
balances[msg.sender] = amount;
} else {
balances[msg.sender] = e.add(balances[msg.sender], amount);
}
e.allow(balances[msg.sender], address(this));
e.allow(balances[msg.sender], owner());
e.allow(balances[msg.sender], msg.sender);
totalSupply = e.add(totalSupply, amount);
e.reveal(totalSupply);
emit EncryptedMint(msg.sender, amount);
}
```
The `encryptedMint` function accepts encrypted amounts for enhanced privacy and requires the caller to pay the Inco fee.
## Transfer Functions
Two versions of transfer are available, with a fee required for the encrypted entrypoint:
```Solidity theme={null}
// For EOAs using encrypted inputs
function transfer(
address to,
bytes calldata encryptedAmount
) public payable virtual returns (bool) {
_requireFee();
transfer(
to,
e.newEuint256(encryptedAmount, msg.sender)
);
return true;
}
// For contract interactions
function transfer(
address to,
euint256 amount
) public virtual returns (bool) {
e.allow(amount, address(this));
ebool canTransfer = e.ge(balances[msg.sender], amount);
_transfer(msg.sender, to, amount, canTransfer);
return true;
}
```
## Approval System
The approval system allows delegated spending:
```Solidity theme={null}
// Approve for EOAs (encrypted amount, fee required)
function approve(
address spender,
bytes calldata encryptedAmount
) public payable virtual returns (bool) {
_requireFee();
approve(spender, e.newEuint256(encryptedAmount, msg.sender));
return true;
}
// Approve for contracts
function approve(
address spender,
euint256 amount
) public virtual returns (bool) {
_approve(msg.sender, spender, amount);
emit Approval(msg.sender, spender, amount);
return true;
}
// Internal approval logic
function _approve(
address owner,
address spender,
euint256 amount
) internal virtual {
allowances[owner][spender] = amount;
e.allow(amount, address(this));
e.allow(amount, owner);
e.allow(amount, spender);
}
```
## TransferFrom Functions
For spending approved tokens, the encrypted entrypoint also requires a fee:
```Solidity theme={null}
// TransferFrom for EOAs
function transferFrom(
address from,
address to,
bytes calldata encryptedAmount
) public payable virtual returns (bool) {
_requireFee();
transferFrom(
from,
to,
e.newEuint256(encryptedAmount, msg.sender)
);
return true;
}
// TransferFrom for contracts
function transferFrom(
address from,
address to,
euint256 amount
) public virtual returns (bool) {
e.allow(amount, address(this));
ebool isTransferable = _updateAllowance(from, msg.sender, amount);
_transfer(from, to, amount, isTransferable);
return true;
}
```
## View Functions
Functions to check balances and allowances:
```Solidity theme={null}
// Get encrypted balance
function balanceOf(address wallet) public view virtual returns (euint256) {
return balances[wallet];
}
// Get encrypted total supply
function getTotalSupply() public view virtual returns (euint256) {
return totalSupply;
}
// Get encrypted allowance
function allowance(
address owner,
address spender
) public view virtual returns (euint256) {
return _allowance(owner, spender);
}
```
## Next Steps
See how all these functions come together in the complete contract
# Setting up the Contract
Source: https://docs.inco.org/tutorials/confidential-token/hardhat/contract-setup
Learn how to set up the basic structure of a confidential ERC20 token
## Import Required Libraries
First, we need to import the necessary contracts and libraries:
```Solidity theme={null}
pragma solidity ^0.8.28;
import {inco, e, ebool, euint256} from "@inco/lightning/src/Lib.sol";
import "@openzeppelin/contracts/access/Ownable2Step.sol";
```
## Contract Definition
Our confidential ERC20 contract inherits from `Ownable2Step`, which provides secure ownership management:
```Solidity theme={null}
contract ConfidentialERC20 is Ownable2Step {
// Contract implementation will go here
}
```
The `Ownable2Step` contract from OpenZeppelin sets the owner in the constructor, allowing only the owner to view all users' balances.
## State Variables
We need to define our state variables, including encrypted balances and allowances:
```Solidity theme={null}
euint256 public totalSupply;
string public _name;
string public _symbol;
uint8 public constant decimals = 18;
// Mappings for balances and allowances
mapping(address => euint256) internal balances;
mapping(address => mapping(address => euint256)) internal allowances;
```
Notice that `balances`, `allowances`, and `totalSupply` use the `euint256` type for encrypted storage.
## Events
Define the standard ERC20 events plus custom events for minting:
```Solidity theme={null}
// Errors
error InsufficientFees();
// Events for Transfer, Approval, and Mint
event Transfer(address indexed from, address indexed to, euint256 amount);
event Approval(
address indexed owner,
address indexed spender,
euint256 amount
);
event Mint(address indexed to, uint256 amount);
event EncryptedMint(address indexed to, euint256 amount);
```
## Understanding the Structure
`euint256` is used for encrypted integers, ensuring balance privacy
`Ownable2Step` provides secure ownership management
Events enable tracking transfers and approvals without revealing amounts
## Next Steps
Continue to learn how to implement the core token functionality