Documentation

ShieldFlow is a confidential escrow and milestone payment protocol built on Zama fhEVM. Encrypted amounts, programmable milestones, and selective auditor access — all enforced on-chain without revealing values to the network.

Deployed on Sepoliaeuint64 encrypted amountsACL-based access controlNon-custodialOpen source
Introduction

What is ShieldFlow?

ShieldFlow solves a fundamental problem in on-chain escrow: every ETH amount and milestone condition is publicly visible on-chain by default, exposing deal terms to competitors, regulators, and adversaries before work is even complete.

By building on Zama's Fully Homomorphic Encryption (FHE) virtual machine, ShieldFlow keeps every payment amount encrypted at the smart contract layer. Counterparties see that funds exist, but the amounts remain sealed — the blockchain cannot read them, and neither can any third party unless explicitly granted access via on-chain ACL.

Encrypted by default

All amounts stored as euint64 ciphertexts. Plain values never appear in contract state.

Multi-party

Client, Contractor, and optional Auditor each get precisely scoped on-chain access.

Composable

Built on fhEVM standards — ACL handles interoperate with other Zama-native contracts.

Process

How ShieldFlow Works

Escrows move through six on-chain steps. FHE operations happen at deposit and release — the two moments where financial values are read or updated.

Escrow Lifecycle
1
createEscrow()caller: Client→ Pending

Register contractor, optional auditor, and milestone deadlines. No ETH yet.

2
deposit()caller: Client→ ActiveFHE

Send ETH + FHE-encrypted amounts for each milestone. Amounts are sealed on-chain.

3
submitMilestone()caller: Contractor→ InProgress

Mark a milestone as complete and ready for review.

4
approveMilestone()caller: Client→ Approved

Verify deliverables and mark the milestone approved.

5
releaseMilestone()caller: Client→ ReleasedFHE

Trigger FHE homomorphic add to update encrypted running total. Payment queued.

6
withdrawReleased()caller: Contractor→ Completed

Pull accrued ETH to wallet. Escrow completes when all milestones are released.

Privacy at each step

1

Create — Only addresses are public. Milestone count is visible; amounts are not set yet.

2

Deposit — ETH value in msg.value is visible; the breakdown across milestones is hidden inside euint64 handles. Only permissioned parties can request decryption.

3

Submit → Approve — Status flags are public. No amounts change; privacy unchanged.

4

Release — Homomorphic addition updates encrypted releasedAmount. The release transaction includes amountWei for native ETH (public in that tx); the full milestone schedule stays encrypted until each release.

5

Withdraw — ETH transfer is on-chain; individual milestone allocations remain hidden in ciphertext.

TipThe total ETH deposited (msg.value) appears in the EscrowDeposited event. Per-milestone allocations are never revealed on-chain unless an authorised party requests FHE decryption through the relayer.
Capabilities

Core Features

Confidential Escrow with Encrypted Amounts

Every monetary value — total deposit and per-milestone allocation — is stored as a euint64 ciphertext on Zama fhEVM. No smart contract, indexer, or blockchain explorer can read these values without explicit ACL permission. The escrow enforces correct payment ordering purely through FHE arithmetic.

Multi-Party: Client, Contractor, Auditor

Three roles with scoped privileges. The Client controls flow (create, deposit, approve, release). The Contractor submits milestones and withdraws. The Auditor gains read-only FHE access granted by the Client at any point during the escrow lifecycle — without disrupting the payment flow.

Milestone Management with FHE Conditions

Up to 10 milestones per escrow, each with an independent encrypted amount and deadline. Release uses FHE.select to guard against overflow — the running releasedAmount accumulates homomorphically and is only trusted if the operation succeeds. Milestones flow through: Pending → InProgress → Approved → Released.

Programmable Auditor Access & Compliance

grantAuditorAccess() issues on-chain FHE.allow() calls for every encrypted handle in the escrow — total deposit, released total, and each milestone amount. This enables a compliance workflow where an auditor can prove payment occurred without parties having to reveal deal terms to the public.

Composable with Zama fhEVM

ShieldFlow uses FHE.allowThis() so the contract can re-read its own ciphertexts in future transactions. ACL handles are standard fhEVM objects compatible with ERC-7984 and other Zama-native contracts. The pattern can be extended to support token-gated access, DAO governance, or automated oracle-triggered releases.

Technical

FHE Deep Dive

Fully Homomorphic Encryption allows arbitrary computation on ciphertexts without decrypting them first. Zama fhEVM implements this at the EVM level using the TFHE cryptosystem, enabling Solidity contracts to add, compare, and branch on encrypted integers.

NoteTwo-layer privacy model. ShieldFlow hides the payment schedule and milestone splits (confidential euint64 terms). Settlement uses public ETH rails — deposit msg.value, release amountWei, and withdraw transfers are visible by Ethereum design. We do not claim full payment privacy.

Encrypted types used

Solidity typeUsed forABI encoding
euint64Milestone amounts, total deposit, released total (all in Gwei)bytes32 handle
externalEuint64User-submitted ciphertexts (before conversion with FHE.fromExternal)bytes32
eboolEncrypted boolean for overflow guard in releaseMilestonebytes32 handle

1. Accepting and storing encrypted input

Users encrypt values client-side with the Zama relayer SDK before submitting. FHE.fromExternal() converts the user-submitted ciphertext and zero-knowledge input proof into an euint64 that the contract can operate on. ACL calls immediately follow to register who may decrypt each handle.

ShieldFlowEscrow.sol — deposit()
euint64 encTotal = FHE.fromExternal(encryptedTotal, inputProof);
  euint64 sumMilestones = FHE.asEuint64(0);
  for (uint8 i = 0; i < e.milestoneCount; i++) {
      euint64 amt = FHE.fromExternal(encMilestoneAmts[i], inputProof);
      sumMilestones = FHE.add(sumMilestones, amt);
      e.milestones[i].encryptedAmount = amt;
      FHE.allowThis(e.milestones[i].encryptedAmount);
      FHE.allow(e.milestones[i].encryptedAmount, msg.sender);
      FHE.allow(e.milestones[i].encryptedAmount, e.contractor);
  }
  FHE.eq(encTotal, sumMilestones);
  FHE.eq(sumMilestones, FHE.asEuint64(uint64(msg.value)));
  e.totalDeposit = sumMilestones;

2. Homomorphic arithmetic with overflow protection

releaseMilestone() uses FHE.add() to accumulate the released total homomorphically — the contract never decrypts the value. To guard against 64-bit overflow, FHE.select() acts as an encrypted ternary: if overflow is detected (the result is less than the previous value), the old value is preserved.

ShieldFlowEscrow.sol — releaseMilestone()
// Homomorphic addition — both operands remain encrypted
euint64 newReleased = FHE.add(e.releasedAmount, m.encryptedAmount);

// Overflow guard: compare encrypted values without revealing them
ebool didOverflow = FHE.lt(newReleased, e.releasedAmount);

// FHE.select(cond, ifTrue, ifFalse) — branch without decrypting
// If overflow detected: keep old value. Otherwise: accept newReleased.
e.releasedAmount = FHE.select(didOverflow, e.releasedAmount, newReleased);

// Re-issue ACL after mutation so all parties retain read access
FHE.allowThis(e.releasedAmount);
FHE.allow(e.releasedAmount, e.client);
FHE.allow(e.releasedAmount, e.contractor);
if (e.auditor != address(0)) {
    FHE.allow(e.releasedAmount, e.auditor);
}

3. ACL-based selective decryption

The Access Control List (ACL) is Zama fhEVM's mechanism for granting decryption rights. Every ciphertext handle exists in an on-chain ACL registry. When a user requests decryption through the Zama relayer, the relayer verifies the caller holds an ACL grant before returning the plaintext. No grant — no decryption.

ShieldFlowEscrow.sol — grantAuditorAccess()
function grantAuditorAccess(uint256 escrowId, address auditor)
    external onlyClient(escrowId)
{
    require(auditor != address(0), "ShieldFlow: invalid auditor address");
    Escrow storage e = _escrows[escrowId];

    e.auditor = auditor;

    // Issue ACL grants for every encrypted handle in the escrow
    FHE.allow(e.totalDeposit, auditor);
    FHE.allow(e.releasedAmount, auditor);
    for (uint8 i = 0; i < e.milestoneCount; i++) {
        if (FHE.isInitialized(e.milestones[i].encryptedAmount)) {
            FHE.allow(e.milestones[i].encryptedAmount, auditor);
        }
    }
    emit AuditorGranted(escrowId, auditor);
}

4. Frontend: encrypting values with the Zama relayer SDK

The frontend encrypts ETH amounts Gwei before submitting them to the contract. The SDK generates a batched ZK input proof covering all values in a single call, which is passed as inputProof to deposit().

src/lib/fhe/fhevm.ts — Encrypting milestone amounts
import { createInstance } from "@zama-fhe/relayer-sdk";

// Initialise the fhEVM instance for the connected wallet
const instance = await createInstance({
  kmsContractAddress,   // Zama KMS contract on Sepolia
  aclContractAddress,   // Zama ACL contract on Sepolia
  network: provider,
});

// Build a batched input — all values share one proof
const input = instance.createEncryptedInput(contractAddress, userAddress);
input.add64(totalGwei);           // Encrypted total
input.add64(milestone1Gwei);      // Per-milestone breakdown
input.add64(milestone2Gwei);
const { handles, inputProof } = await input.encrypt();

// handles[0] = encryptedTotal (externalEuint64)
// handles[1], handles[2] = encMilestoneAmts[]
// inputProof  = ZK proof the client knows the plaintexts
await deposit(escrowId, handles[0], [handles[1], handles[2]], inputProof, amountsWei);
NoteThe inputProof is a compact zero-knowledge proof generated by the Zama SDK that proves the user supplied well-formed 64-bit values. Without it, FHE.fromExternal() would revert. This prevents malformed ciphertext attacks that could corrupt encrypted state.

FHE vs. alternatives

PropertyCentralizedZK ProofsFHE — ShieldFlow
On-chain privacy✗ Amounts public⚡ Partial (proofs only)✓ Full encryption
Compute on secrets✗ Raw data required✗ Prove, not compute✓ Homomorphic ops
Trustless execution✗ Custodian required✓ Verifiable✓ On-chain, no trust
Custodial riskHigh — single party holds fundsNoneNone — smart contract
Programmable conditionsManual / off-chainComplex circuit design✓ FHE.select, FHE.add
Selective disclosureAll-or-nothingDifficult; verifier set✓ Per-address ACL
AuditabilityOff-chain onlyProof logs✓ On-chain ACL grants
TipZK proofs can verify thatsomething is true (e.g. "I own this balance") but cannot perform computation on encrypted values. FHE can do both — which is why ShieldFlow can accumulate a running payment total and apply conditional logic without ever decrypting the underlying amounts.
Guides

User Guides

Step-by-step instructions for each role in a ShieldFlow escrow.

For Clients

The Client creates and funds the escrow, approves completed milestones, and releases payments.

  1. 1
    Connect wallet — Connect a Sepolia wallet in the app. ShieldFlow requires Sepolia — switch chains if prompted.
  2. 2
    Create an escrow — Go to /app/create. Enter the contractor's address, an optional auditor, and define 1–10 milestones with labels, ETH amounts, and deadlines.
  3. 3
    Review & deploy — Step 3 of the wizard shows a summary. Confirm the transaction. This registers the escrow on-chain at no cost except gas.
  4. 4
    Fund the escrow — After creation, the FundEscrowForm appears. Confirm the ETH amount. The frontend encrypts each milestone allocation and submits deposit() with the encrypted handles and input proof.
  5. 5
    Approve milestones — When the contractor submits work, visit /app/contracts/[id]. Review and click Approve Milestone. This does not release funds yet.
  6. 6
    Release payment — Click Release Milestone to trigger the FHE payment update and queue ETH for contractor withdrawal.
  7. 7
    Add an auditor (optional) — At any time, use Grant Auditor Access to give a compliance address read-only FHE decryption rights.

For Contractors

Contractors receive an escrow link from the client. No wallet connection is needed to view the invite; a Sepolia wallet is required to interact.

  1. 1
    Receive the escrow link — The client shares a /app/contracts/[id] link. Visit it to see contract status, milestone count, and deadlines.
  2. 2
    View your encrypted amount — The Encrypted Value component lets you click-to-decrypt your milestone amounts using the Zama relayer. Only your wallet address can decrypt values you hold ACL grants for.
  3. 3
    Submit a milestone — When work is complete, click Submit Milestone on the relevant row. This calls submitMilestone() on-chain and notifies the client.
  4. 4
    Wait for approval — The client reviews and approves the milestone. You will see the milestone status change to Approved in the UI.
  5. 5
    Withdraw funds — After the client releases the milestone, click Withdraw Released Funds to pull all accrued ETH to your wallet via withdrawReleased().

For Auditors

Auditors have read-only decryption access. They cannot approve, release, or withdraw. Their role is to verify that payment amounts match agreed terms for compliance purposes.

  1. 1
    Receive ACL grant — The client calls grantAuditorAccess(escrowId, yourAddress). This is an on-chain transaction that registers your address in the fhEVM ACL for all encrypted handles in the escrow.
  2. 2
    Connect wallet — Visit /app/contracts/[id] with the auditor wallet connected. The UI will show encrypted value placeholders.
  3. 3
    Decrypt & verify — Click any Encrypted Value component to trigger decryption via the Zama relayer. Your wallet signs the request; the relayer verifies your ACL grant and returns the plaintext.
  4. 4
    Confirm compliance — Cross-reference decrypted milestone amounts against your off-chain agreement. All decryption events are recorded by the relayer for audit trails.
NoteAuditors cannot approve milestones, release funds, or withdraw ETH. The onlyClient and onlyContractor modifiers enforce this at the contract level.
Reference

Smart Contract Reference

ShieldFlowEscrowSepolia · 0x4A4DC01B2505C70995908513b0c16eea5AB93BBdView on Etherscan

Functions

FunctionCallerDescription
createEscrow()ClientRegisters a new escrow in Pending state. Sets parties and milestone deadlines. Returns escrowId.
deposit()ClientFunds the escrow with ETH (msg.value is public). Accepts FHE-encrypted total and per-milestone amounts in one inputProof batch. Homomorphic FHE.eq validates milestone sum. No plaintext milestone array on-chain.
submitMilestone()ContractorMarks a milestone as submitted (InProgress). Signals work is ready for client review.
approveMilestone()ClientApproves a submitted milestone, setting status to Approved and enabling release.
releaseMilestone()ClientReleases payment for an approved milestone. Updates encrypted running total homomorphically. amountWei is used for native ETH accounting (visible in this tx only — not stored in public getters/events).
openDispute()Client or ContractorOpens a dispute on a submitted/approved milestone. Freezes release and withdraw until auditor resolves.
resolveDispute()AuditorResolves a dispute: Release (queue ETH for contractor) or Refund (return ETH to client). Auditor decrypts confidential terms off-chain to adjudicate.
withdrawReleased()ContractorTransfers all queued ETH (from released milestones) to the contractor's wallet.
grantAuditorAccess()ClientAdds an auditor address and grants FHE ACL read access to all encrypted handles in the escrow.
cancelEscrow()ClientCancels a Pending (unfunded) escrow. Cannot cancel after deposit.
getEscrowInfo()AnyoneReturns parties, status, creation timestamp, and milestone count.
getPendingWithdrawal()AnyoneReturns operational pending withdrawal wei for the contractor queue. Does not expose per-milestone splits.
getTotalDeposit()ACL holdersReturns the euint64 handle for the encrypted total deposit. Requires FHE ACL permission to decrypt.
getMilestone()ACL holdersReturns milestone data including encrypted amount handle, deadline, and status flags.

Events

EventDescription
EscrowCreatedFired on successful createEscrow()
EscrowDepositedFired after deposit confirms — no wei amounts in event
MilestoneSubmittedContractor submitted a milestone
MilestoneApprovedClient approved a submitted milestone
MilestoneReleasedPayment released for a milestone — no amountWei
FundsWithdrawnContractor withdrew ETH — no amountWei
DisputeOpenedDispute opened by client or contractor
DisputeResolvedAuditor resolved dispute
EscrowCompletedAll milestones released; escrow fully settled
EscrowCancelledPending escrow cancelled by client
AuditorGrantedAuditor ACL access granted
Security

Security & Best Practices

ACL Implementation

Every ciphertext handle created or modified by ShieldFlowEscrow immediately receives ACL grants via FHE.allowThis() and role-specific FHE.allow(). Without FHE.allowThis(), the contract cannot re-read its own ciphertexts in future transactions — a common fhEVM mistake that would permanently freeze state.

Contract
allowThis() on all handles it creates and mutates
Client
allow() on deposit, released total, all milestone amounts
Contractor
allow() on deposit, released total, all milestone amounts
Auditor
allow() issued on-demand via grantAuditorAccess()

Gas Considerations

FHE operations are significantly more gas-expensive than plaintext arithmetic on standard EVM chains. On Zama fhEVM Sepolia, each FHE.add, FHE.lt, and FHE.selectcarries an overhead computed by Zama's coprocessor. As a result:

  • Milestone count is capped at 10 to bound deposit() gas usage (10 FHE.fromExternal calls).
  • releaseMilestone() performs 3 FHE ops (add, lt, select) per call — plan milestone granularity accordingly.
  • grantAuditorAccess() gas scales linearly with milestone count (one FHE.allow per milestone).

Secure patterns used

  • Checks-Effects-Interactions: state is updated before external ETH transfer in withdrawReleased().
  • Re-entrancy safe: pendingWithdrawal zeroed before call{}() in withdrawReleased().
  • Overflow-protected FHE addition via FHE.select(overflow, old, new) pattern.
  • Homomorphic deposit integrity: FHE.add milestone sum + FHE.eq against declared total and msg.value binding.
  • Sanitized events/getters: no per-milestone wei in EscrowDeposited, MilestoneReleased, FundsWithdrawn, or getMilestone.
  • Encrypted solvency: FHE.le(released + milestone, total) before release.
  • Role modifiers: onlyClient, onlyContractor, onlyClientOrAuditor enforced at function level.
  • Status guards: escrowActive() and explicit status checks prevent out-of-order calls.
  • FHE.isInitialized() check before ACL grants to avoid operating on uninitialised handles.

Known Limitations

WarningShieldFlow has not undergone a formal security audit. It is deployed on Sepolia testnet only and should not be used with real assets.
  • Deposit msg.value is public (native ETH). Per-milestone splits remain in encrypted handles only.
  • Release/withdraw ETH amounts are visible in those transactions — schedule privacy, not transfer privacy.
  • Relayer decryption is asynchronous — UI may show a loading state while the relayer processes decrypt requests.
  • Escrows created before the metadata URI upgrade have no on-chain pointer — contractors only see project details after the client republishes metadata on a redeployed contract.
  • Milestone delivery links/notes are stored in the submitter's browser only until a future on-chain delivery URI is added.
  • cancelEscrow() only works before deposit — post-deposit cancellation is not yet implemented.
Integration

Deployment & Integration

Deploy your own instance

Terminal
# 1. Clone and install
git clone https://github.com/your-org/shieldflow
cd shieldflow/fhevm-hardhat
pnpm install

# 2. Configure environment
cp .env.example .env
# Set PRIVATE_KEY and ALCHEMY_API_KEY in .env

# 3. Deploy to Sepolia
npx hardhat run deploy/deploy_ShieldFlowEscrow.ts --network sepolia

# Output: ShieldFlowEscrow deployed to: 0x...
# Update frontend/src/lib/contracts/addresses.ts with the new address

Frontend setup

Terminal
cd frontend
pnpm install
cp .env.local.example .env.local

Environment variables

VariableDescription
NEXT_PUBLIC_ALCHEMY_RPC_URLAlchemy RPC endpoint for Sepolia (or any Sepolia-compatible RPC)
NEXT_PUBLIC_CHAIN_ID11155111 for Sepolia

Updating the contract address

After redeploying, update the address in:

src/lib/contracts/addresses.ts
export const CONTRACT_ADDRESSES = {
  sepolia: {
    ShieldFlowEscrow: "0xYOUR_NEW_ADDRESS" as `0x${string}`,
  },
} as const;

Relayer configuration

ShieldFlow uses the Zama hosted relayer on Sepolia. The relayer is initialized in src/lib/fhe/fhevm.ts using the public Zama KMS and ACL contract addresses for Sepolia. No API key is required for testnet usage. For production deployments, consult Zama fhEVM documentation for relayer configuration options.

Future

Roadmap & Future Work

ShieldFlow is actively developed. The following capabilities are planned for future releases.

v0.2Dispute Resolution
  • Arbitrator role with time-locked dispute window
  • FHE-conditional release: auto-approve on deadline if no dispute
  • Partial release support (percentage of milestone)
v0.3Token Support
  • ERC-20 escrow alongside ETH (euint64 token amounts)
  • Encrypted token balances via fhEVM ERC-20 standard
  • Multi-token milestones (mixed asset deals)
v0.4Oracle Integration
  • Chainlink Functions trigger for milestone auto-approval
  • FHE-encrypted oracle responses for private condition checks
  • Delivery confirmation hooks for digital goods
v0.5Advanced Composability
  • On-chain identity integration (ENS, EAS attestations)
  • DAO governance for escrow parameter changes
  • Encrypted escrow factory for platform builders
v1.0Mainnet Launch
  • Independent security audit
  • Formal Zama fhEVM mainnet deployment
  • SDK for third-party integrations
OngoingInfrastructure
  • Subgraph indexing for escrow discovery
  • Email/push notifications for milestone events
  • Mobile-optimised frontend