Add

Introduction to homomorphic addition on encrypted values. Demonstrates adding two encrypted numbers without decryption, including input handling, addition, and permission management.

circle-info

To run this example correctly, make sure the files are placed in the following directories:

  • .sol file → <your-project-root-dir>/contracts/

  • .ts file → <your-project-root-dir>/test/

This ensures Hardhat can compile and test your contracts as expected.

chevron-right🔐 FHE API Reference (6 items)hashtag

Types: euint8 · externalEuint8

Functions:

  • FHE.add() - Homomorphic addition: result = a + b (overflow wraps)

  • FHE.allow() - Grants PERMANENT permission for address to decrypt/use value

  • FHE.allowThis() - Grants contract permission to operate on ciphertext

  • FHE.fromExternal() - Validates and converts external encrypted input using inputProof

// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.24;

import {FHE, euint8, externalEuint8} from "@fhevm/solidity/lib/FHE.sol";
import {ZamaEthereumConfig} from "@fhevm/solidity/config/ZamaConfig.sol";

/**
 * @notice Introduction to homomorphic addition on encrypted values.
 *         Demonstrates adding two encrypted numbers without decryption, including
 *         input handling, addition, and permission management.

 * @dev Shows the basic FHE operation and permission flow (FHE.add ~100k gas).
 */
contract FHEAdd is ZamaEthereumConfig {
    euint8 private _a;
    euint8 private _b;
    euint8 private _result;

    /// @notice Set the first operand (encrypted)
    function setA(externalEuint8 inputA, bytes calldata inputProof) external {
        _a = FHE.fromExternal(inputA, inputProof);
        FHE.allowThis(_a);
    }

    /// @notice Set the second operand (encrypted)
    function setB(externalEuint8 inputB, bytes calldata inputProof) external {
        _b = FHE.fromExternal(inputB, inputProof);
        FHE.allowThis(_b);
    }

    /// @notice Compute a + b on encrypted values
    /// @dev Contract operates on ciphertexts - never sees actual values!
    function computeAPlusB() external {
        // 🧮 Homomorphic: operates on encrypted data without decrypting
        _result = FHE.add(_a, _b);

        // 🔑 Why both? allowThis = contract can use it, allow = user can decrypt
        FHE.allowThis(_result);
        FHE.allow(_result, msg.sender);
    }

    /// @notice Returns the encrypted result handle
    function result() public view returns (euint8) {
        return _result;
    }
}

Last updated