Encrypt & decrypt
How to encrypt values and decrypt FHE encrypted values for custom confidential smart contracts that are not wrapped ERC-20 tokens.
Example
import { useEncrypt, useDecryptValues, useZamaSDK } from "@zama-fhe/react-sdk";
import { useAccount } from "wagmi";
import { useState, type FormEvent } from "react";
function ConfidentialRoundTrip() {
const sdk = useZamaSDK();
const encrypt = useEncrypt();
const { address: userAddress } = useAccount();
const [inputs, setInputs] = useState<
{ encryptedValue: string; contractAddress: `0x${string}` }[]
>([]);
// Disabled by default — opt in with `enabled`. The hook still waits for
// non-empty inputs and a connected wallet before it decrypts.
const { data: decrypted } = useDecryptValues(inputs, { enabled: true });
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const contractAddress = "0xYourContract" as `0x${string}`;
// 1. Encrypt
const encrypted = await encrypt.mutateAsync({
values: [{ value: 42n, type: "euint64" }],
contractAddress,
userAddress: userAddress!,
});
// 2. Send to contract
await sdk.signer!.writeContract({
address: contractAddress,
abi: yourContractABI,
functionName: "store",
args: [encrypted.encryptedValues[0]!, encrypted.inputProof],
});
// 3. Read the encrypted value back — setting inputs triggers decryption
const encryptedValue = (await sdk.provider.readContract({
address: contractAddress,
abi: yourContractABI,
functionName: "getHandle",
args: [userAddress],
})) as string;
setInputs([{ encryptedValue, contractAddress }]);
};
return (
<form onSubmit={handleSubmit}>
<button type="submit" disabled={encrypt.isPending}>
Encrypt → Store → Decrypt
</button>
{decrypted && inputs[0] && (
<output>Decrypted: {decrypted[inputs[0].encryptedValue]?.toString()}</output>
)}
</form>
);
}Steps
1. Encrypt values with useEncrypt
Encrypting multiple values
2. Use encrypted values in contract calls
3. Decryption of the encrypted data
Gating useConfidentialBalance
Decrypting encrypted values from multiple contracts
Persistent caching
4. Decrypt with useDecryptPublicValues (advanced)
Last updated