### Querying Documentation Example Source: https://docs.zama.org/protocol/sdk/api-references/sdk/genericprovider.md Example of how to dynamically query documentation by making an HTTP GET request with 'ask' and optional 'goal' query parameters. ```http GET https://docs.zama.org/protocol/sdk/api-references/sdk/genericprovider.md?ask=&goal= ``` -------------------------------- ### Start Development Server Source: https://docs.zama.org/protocol/sdk/getting-started/first-confidential-dapp.md Command to start the development server for your DApp. Ensure you have pnpm installed and the project dependencies are set up. ```bash pnpm dev ``` -------------------------------- ### Example GET Request for Documentation Query Source: https://docs.zama.org/protocol/sdk/api-references/react/usewrappersregistryaddress.md Demonstrates how to query the documentation dynamically using an HTTP GET request. This is useful for retrieving information not explicitly present on the page or for clarification. ```http GET https://docs.zama.org/protocol/sdk/api-references/react/usewrappersRegistryaddress.md?ask=&goal= ``` -------------------------------- ### Query Documentation Example Source: https://docs.zama.org/protocol/sdk/guides/shield-tokens.md Use this GET request to query the documentation dynamically. Replace `` with your specific query and `` with your broader objective. ```http GET https://docs.zama.org/protocol/sdk/guides/shield-tokens.md?ask=&goal= ``` -------------------------------- ### Query Documentation Example Source: https://docs.zama.org/protocol/examples/basic/decryption/fhe-user-decrypt-multiple-values.md Demonstrates how to perform an HTTP GET request to query documentation dynamically. Use the 'ask' parameter for specific questions and the optional 'goal' parameter for broader context. ```http GET https://docs.zama.org/protocol/examples/basic/decryption/fhe-user-decrypt-multiple-values.md?ask=&goal= ``` -------------------------------- ### Compile and Run Tests Source: https://docs.zama.org/protocol/solidity-guides/getting-started/setup-1.md Build the project and run tests to verify the setup. This step ensures that the example FHECounter contract tests pass. ```bash forge build forge test -vvv ``` -------------------------------- ### Example GET Request for Documentation Query Source: https://docs.zama.org/protocol/examples/basic/decryption/fhe-user-decrypt-single-value.md Use this endpoint to ask questions about the documentation. The 'ask' parameter specifies the question, and 'goal' provides optional broader context for the AI. ```http GET https://docs.zama.org/protocol/examples/basic/decryption/fhe-user-decrypt-single-value.md?ask=&goal= ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.zama.org/protocol/protocol-apps/confidential-tokens/wrapper-registry.md This example shows how to make an HTTP GET request to query the documentation. Use the 'ask' parameter for your question and optionally the 'goal' parameter for your broader objective. ```http GET https://docs.zama.org/protocol/protocol-apps/confidential-tokens/wrapper-registry.md?ask=&goal= ``` -------------------------------- ### Install Zama SDK Packages Source: https://docs.zama.org/protocol/sdk/guides/local-development.md Install the necessary Zama SDK packages and Viem for local development. ```bash npm install @zama-fhe/sdk viem ``` -------------------------------- ### Install Vanilla SDK Source: https://docs.zama.org/protocol/sdk/overview.md Use this command to install the core SDK for vanilla TypeScript or Node.js applications. ```sh # Vanilla TypeScript / Node.js pnpm add @zama-fhe/sdk ``` -------------------------------- ### Install Vanilla SDK (npm) Source: https://docs.zama.org/protocol/sdk/overview.md Use this command to install the core SDK for vanilla TypeScript or Node.js applications using npm. ```sh # Vanilla TypeScript / Node.js npm install @zama-fhe/sdk ``` -------------------------------- ### Install Zama SDK for ethers Source: https://docs.zama.org/protocol/sdk/getting-started/quick-start.md Install the Zama SDK and ethers.js for your project. ```bash pnpm add @zama-fhe/sdk ethers ``` -------------------------------- ### Install React SDK with Dependencies Source: https://docs.zama.org/protocol/sdk/overview.md Use this command to install the React SDK along with its core SDK and React query dependency for React applications. ```sh # React app pnpm add @zama-fhe/react-sdk @zama-fhe/sdk @tanstack/react-query ``` -------------------------------- ### Install Zama SDK and Dependencies Source: https://docs.zama.org/protocol/sdk/getting-started/first-confidential-dapp.md Install the necessary Zama SDK packages, React SDK, and other project dependencies using pnpm. ```bash pnpm add @zama-fhe/sdk @zama-fhe/react-sdk @tanstack/react-query wagmi viem ``` -------------------------------- ### Querying Documentation via HTTP GET Source: https://docs.zama.org/protocol/examples/basic/encryption/fhe-encrypt-multiple-values.md Demonstrates the HTTP GET request format for querying documentation. Use the 'ask' parameter for specific questions and the optional 'goal' parameter for broader context. ```bash GET https://docs.zama.org/protocol/examples/basic/encryption/fhe-encrypt-multiple-values.md?ask=&goal= ``` -------------------------------- ### Install Project Dependencies Source: https://docs.zama.org/protocol/examples/openzeppelin-confidential-contracts/openzeppelin.md Install all necessary project dependencies using npm ci for a clean installation. ```bash npm ci ``` -------------------------------- ### Install OpenZeppelin Confidential Contracts Source: https://docs.zama.org/protocol/examples/openzeppelin-confidential-contracts/openzeppelin.md Install OpenZeppelin's confidential contracts library as a project dependency. ```bash npm i @openzeppelin/confidential-contracts ``` -------------------------------- ### Instantiate ViemProvider Source: https://docs.zama.org/protocol/sdk/api-references/sdk/viemprovider.md Example of how to instantiate ViemProvider with a viem PublicClient. ```APIDOC ## Usage ```ts import { createPublicClient, http } from "viem"; import { sepolia } from "viem/chains"; import { ViemProvider } from "@zama-fhe/sdk/viem"; const publicClient = createPublicClient({ chain: sepolia, transport: http("https://sepolia.infura.io/v3/YOUR_KEY"), }); const provider = new ViemProvider({ publicClient }); ``` {% hint style="info" %} You rarely need to instantiate `ViemProvider` directly. The viem `createConfig` builds one from the `publicClient` you pass. Use this class when constructing `ZamaSDK` manually or when using the generic `createConfig`.{% endhint %} ``` -------------------------------- ### Install Vanilla SDK (yarn) Source: https://docs.zama.org/protocol/sdk/overview.md Use this command to install the core SDK for vanilla TypeScript or Node.js applications using yarn. ```sh # Vanilla TypeScript / Node.js yarn add @zama-fhe/sdk ``` -------------------------------- ### Custom Provider Implementation Example Source: https://docs.zama.org/protocol/sdk/api-references/sdk/genericprovider.md An example class demonstrating how to implement the `GenericProvider` interface for a custom blockchain provider. ```typescript import type { GenericProvider } from "@zama-fhe/sdk"; class MyProvider implements GenericProvider { async getChainId() { /* ... */ } async readContract(config) { /* ... */ } async waitForTransactionReceipt(hash) { /* ... */ } async getBlockTimestamp() { /* ... */ } } ``` -------------------------------- ### Example Configuration for useDelegationStatus Source: https://docs.zama.org/protocol/sdk/api-references/react/usedelegationstatus.md Provides an example of how to configure the useDelegationStatus hook with contract and address details. ```typescript const { data } = useDelegationStatus({ contractAddress: "0xToken", delegatorAddress: "0xDelegator", delegateAddress: "0xDelegate", }); ``` -------------------------------- ### Install React SDK with Dependencies (npm) Source: https://docs.zama.org/protocol/sdk/overview.md Use this command to install the React SDK along with its core SDK and React query dependency for React applications using npm. ```sh # React app npm install @zama-fhe/react-sdk @zama-fhe/sdk @tanstack/react-query ``` -------------------------------- ### Usage Examples Source: https://docs.zama.org/protocol/sdk/api-references/react/query-keys.md Examples demonstrating how to use zamaQueryKeys with React Query's useQueryClient to invalidate cache entries. ```APIDOC ## Usage ```tsx import { useQueryClient } from "@tanstack/react-query"; import { zamaQueryKeys } from "@zama-fhe/sdk/query"; const queryClient = useQueryClient(); // Invalidate all balances queryClient.invalidateQueries({ queryKey: zamaQueryKeys.confidentialBalance.all }); // Invalidate one token's balances queryClient.invalidateQueries({ queryKey: zamaQueryKeys.confidentialBalance.token("0xToken"), }); // Invalidate a specific owner's balance queryClient.invalidateQueries({ queryKey: zamaQueryKeys.confidentialBalance.owner("0xToken", "0xOwner"), }); ``` ``` -------------------------------- ### Viem Setup with ZamaProvider Source: https://docs.zama.org/protocol/sdk/api-references/react/zamaprovider.md Configure and wrap your application with ZamaProvider when using viem for blockchain interactions. This setup involves creating viem clients and configuring the Zama SDK with appropriate chains and relayers. ```typescript import { createPublicClient, createWalletClient, custom, http } from "viem"; import { sepolia } from "viem/chains"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { ZamaProvider } from "@zama-fhe/react-sdk"; import { web } from "@zama-fhe/sdk/web"; import { createConfig } from "@zama-fhe/sdk/viem"; import { sepolia as sepoliaFhe, type FheChain } from "@zama-fhe/sdk/chains"; const publicClient = createPublicClient({ chain: sepolia, transport: http("https://sepolia.infura.io/v3/YOUR_KEY"), }); const walletClient = createWalletClient({ chain: sepolia, transport: custom(window.ethereum!), }); const mySepolia = { ...sepoliaFhe, relayerUrl: "https://your-app.com/api/relayer/11155111", } as const satisfies FheChain; const zamaConfig = createConfig({ chains: [mySepolia], publicClient, walletClient, relayers: { [mySepolia.id]: web(), }, }); const queryClient = new QueryClient(); function App() { return ( ); } ``` -------------------------------- ### Import zamaQueryKeys Source: https://docs.zama.org/protocol/sdk/api-references/react/query-keys.md Import the zamaQueryKeys factory from the SDK to start using it. ```APIDOC ## Import ```ts import { zamaQueryKeys } from "@zama-fhe/sdk/query"; ``` ``` -------------------------------- ### Querying Documentation with HTTP GET Source: https://docs.zama.org/protocol/sdk/getting-started Use this HTTP GET request to query the documentation dynamically. Include an 'ask' parameter for your specific question and an optional 'goal' parameter to tailor the response. ```http GET https://docs.zama.org/protocol/sdk/getting-started.md?ask=&goal= ``` -------------------------------- ### Query Documentation with GET Request Source: https://docs.zama.org/homepage/llms.txt Use this GET request to query the documentation index with an 'ask' parameter for specific questions and an optional 'goal' parameter for broader context. The response includes a direct answer and relevant excerpts. ```http GET https://docs.zama.org/homepage/readme.md?ask=&goal= ``` -------------------------------- ### Install Zama Skills for Claude Source: https://docs.zama.org/protocol/sdk/getting-started/build-with-an-llm.md Use these commands to install the Zama skills for Claude. This provides your agent with expert, up-to-date guidance on the protocol and SDK. ```bash /plugin marketplace add zama-ai/skills /plugin install zama-protocol@zama-skills ``` -------------------------------- ### Query Documentation Source: https://docs.zama.org/protocol/examples/basic/encryption.md Demonstrates how to query the documentation dynamically using HTTP GET requests. Use this to get information not explicitly present on the page or to retrieve related documentation. ```http GET https://docs.zama.org/protocol/examples/basic/encryption.md?ask=&goal= ``` -------------------------------- ### Install Zama SDK v3 Dependencies Source: https://docs.zama.org/protocol/sdk/migration/migrate-v2-to-v3.md Install the latest versions of the core SDK and the React SDK. The React SDK depends on the core SDK. ```bash pnpm add @zama-fhe/sdk@^3 @zama-fhe/react-sdk@^3 ``` -------------------------------- ### Install React SDK with Dependencies (yarn) Source: https://docs.zama.org/protocol/sdk/overview.md Use this command to install the React SDK along with its core SDK and React query dependency for React applications using yarn. ```sh # React app yarn add @zama-fhe/react-sdk @zama-fhe/sdk @tanstack/react-query ``` -------------------------------- ### Install Zama Skills for Other Agents Source: https://docs.zama.org/protocol/sdk/getting-started/build-with-an-llm.md Install the Zama skills for other skill-aware agents using npx. You can use the --list flag to choose specific skills. ```bash npx skills add zama-ai/skills ``` -------------------------------- ### App Setup with Providers Source: https://docs.zama.org/protocol/sdk/getting-started/first-confidential-dapp.md Wrap your application in Wagmi, React Query, and Zama providers. The Zama provider requires a configuration derived from your wagmi setup to automatically manage FHE operations. ```tsx import { WagmiProvider } from "wagmi"; import { QueryClientProvider } from "@tanstack/react-query"; import { ZamaProvider } from "@zama-fhe/react-sdk"; import { wagmiConfig, queryClient, zamaConfig } from "./config"; import { Dashboard } from "./Dashboard"; export default function App() { return (

Confidential Token Dashboard

); } ``` -------------------------------- ### Query Documentation with GET Request Source: https://docs.zama.org/protocol/solidity-guides/getting-started You can query this documentation dynamically by performing an HTTP GET request to the current page URL with the `ask` query parameter and an optional `goal` parameter. This is useful for retrieving specific information or context not immediately apparent on the page. ```http GET https://docs.zama.org/protocol/solidity-guides/getting-started.md?ask=&goal= ``` -------------------------------- ### useWrapperDiscovery Hook Usage Source: https://docs.zama.org/protocol/sdk/api-references/react/usewrapperdiscovery.md Example of how to use the useWrapperDiscovery hook to get the wrapper address for a token. ```APIDOC ## useWrapperDiscovery ### Description Find the confidential wrapper contract address for an ERC-20 token via the on-chain registry. The result is cached indefinitely since wrapper addresses never change. ### Import ```ts import { useWrapperDiscovery } from "@zama-fhe/react-sdk"; ``` ### Parameters #### tokenAddress `Address` Address of any confidential token you control. Used to scope the query cache key and to gate whether the query is enabled — it does not affect which wrapper the registry returns. #### erc20Address `Address | undefined` Address of the ERC-20 token to discover the wrapper for. Pass `undefined` to disable the query. ### Return Type The `data` field resolves to `Address | null` -- the wrapper contract address for the given token, or `null` if no wrapper exists. ### Caching The query uses `staleTime: Infinity`. Wrapper addresses are immutable once deployed, so the result never re-fetches automatically. ### Suspense Use `useWrapperDiscoverySuspense` inside a `` boundary to avoid manual loading state handling: ```tsx import { useWrapperDiscoverySuspense } from "@zama-fhe/react-sdk"; function WrapperInfo({ tokenAddress }: { tokenAddress: `0x${string}` }) { const { data: wrapperAddress } = useWrapperDiscoverySuspense({ tokenAddress, erc20Address: "0xUSDC", }); return

Wrapper: {wrapperAddress}

; } ``` ``` -------------------------------- ### HighestDieRoll Game Contract Interaction Source: https://docs.zama.org/protocol/examples/basic/decryption/highest-die-roll.md This snippet shows the setup and execution of a Highest Die Roll game, including contract deployment, player setup, and starting a new game. It also includes a helper function to parse the `GameCreated` event. ```typescript import { expect } from "chai"; import { ethers } from "hardhat"; import { Signers, HighestDieRoll } from "../typechain-types"; import { deployFixture } from "./fixtures/deploy"; import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers"; import { EthersT } from "ethers"; // Mock type for ClearValueType for demonstration purposes type ClearValueType = bigint; describe("HighestDieRoll", function () { let contract: HighestDieRoll; let contractAddress: string; let signers: Signers; let playerA: HardhatEthersSigner; let playerB: HardhatEthersSigner; before(async function () { // Check whether the tests are running against an FHEVM mock environment if (!hre.fhevm.isMock) { throw new Error(`This hardhat test suite cannot run on Sepolia Testnet`); } const ethSigners: HardhatEthersSigner[] = await ethers.getSigners(); signers = { owner: ethSigners[0], alice: ethSigners[1], bob: ethSigners[2] }; playerA = signers.alice; playerB = signers.bob; }); beforeEach(async function () { // Deploy a new contract each time we run a new test const deployment = await deployFixture(); contractAddress = deployment.highestDiceRoll_address; contract = deployment.highestDiceRoll; }); /** * Helper: Parses the GameCreated event from a transaction receipt. * WARNING: This function is for illustrative purposes only and is not production-ready * (it does not handle several events in same tx). */ function parseGameCreatedEvent(txReceipt: EthersT.ContractTransactionReceipt | null): { txHash: `0x${string}`; gameId: number; playerA: `0x${string}`; playerB: `0x${string}`; playerAEncryptedDiceRoll: `0x${string}`; playerBEncryptedDiceRoll: `0x${string}`; } { const gameCreatedEvents: Array<{ txHash: `0x${string}`; gameId: number; playerA: `0x${string}`; playerB: `0x${string}`; playerAEncryptedDiceRoll: `0x${string}`; playerBEncryptedDiceRoll: `0x${string}`; }> = []; if (txReceipt) { const logs = Array.isArray(txReceipt.logs) ? txReceipt.logs : [txReceipt.logs]; for (let i = 0; i < logs.length; ++i) { const parsedLog = contract.interface.parseLog(logs[i]); if (!parsedLog || parsedLog.name !== "GameCreated") { continue; } const ge = { txHash: txReceipt.hash as `0x${string}`, gameId: Number(parsedLog.args[0]), playerA: parsedLog.args[1], playerB: parsedLog.args[2], playerAEncryptedDiceRoll: parsedLog.args[3], playerBEncryptedDiceRoll: parsedLog.args[4], }; gameCreatedEvents.push(ge); } } // In this example, we expect on one single GameCreated event expect(gameCreatedEvents.length).to.eq(1); return gameCreatedEvents[0]; } // ✅ Test should succeed it("decryption should succeed", async function () { console.log(``); console.log(`🎲 HighestDieRoll Game contract address: ${contractAddress}`); console.log(` 🤖 playerA.address: ${playerA.address}`); console.log(` 🎃 playerB.address: ${playerB.address}`); console.log(``); // Starts a new Heads or Tails game. This will emit a `GameCreated` event const tx = await contract.connect(signers.owner).highestDieRoll(playerA, playerB); // Parse the `GameCreated` event const gameCreatedEvent = parseGameCreatedEvent(await tx.wait())!; // GameId is 1 since we are playing the first game expect(gameCreatedEvent.gameId).to.eq(1); expect(gameCreatedEvent.playerA).to.eq(playerA.address); expect(gameCreatedEvent.playerB).to.eq(playerB.address); expect(await contract.getGamesCount()).to.eq(1); console.log(`✅ New game #${gameCreatedEvent.gameId} created!`); console.log(JSON.stringify(gameCreatedEvent, null, 2)); const gameId = gameCreatedEvent.gameId; const playerADiceRoll = gameCreatedEvent.playerAEncryptedDiceRoll; const playerBDiceRoll = gameCreatedEvent.playerBEncryptedDiceRoll; // Call the Zama Relayer to compute the decryption const publicDecryptResults = await fhevm.publicDecrypt([playerADiceRoll, playerBDiceRoll]); // The Relayer returns a `PublicDecryptResults` object containing: // - the ORDERED clear values (here we have only one single value) // - the ORDERED clear values in ABI-encoded form // - the KMS decryption proof associated with the ORDERED clear values in ABI-encoded form const abiEncodedClearGameResult = publicDecryptResults.abiEncodedClearValues; const decryptionProof = publicDecryptResults.decryptionProof; const clearValueA: ClearValueType = publicDecryptResults.clearValues[playerADiceRoll]; const clearValueB: ClearValueType = publicDecryptResults.clearValues[playerBDiceRoll]; expect(typeof clearValueA).to.eq("bigint"); expect(typeof clearValueB).to.eq("bigint"); // playerA's 8-sided die roll result (between 1 and 8) const a = (Number(clearValueA) % 8) + 1; // playerB's 8-sided die roll result (between 1 and 8) const b = (Number(clearValueB) % 8) + 1; const isDraw = a === b; const playerAWon = a > b; const playerBWon = a < b; }); }); ``` -------------------------------- ### Get Current Fee Basis Points Source: https://docs.zama.org/protocol/protocol-apps/staking.md Retrieves the current commission fee percentage in basis points. For example, 1000 represents 10%. ```solidity // Returns the current fee in basis points (e.g., 1000 = 10%) uint16 currentFee = operatorRewarder.feeBasisPoints(); ``` -------------------------------- ### Query Documentation with GET Request Source: https://docs.zama.org/protocol/protocol-apps/addresses/mainnet.md Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter. ```http GET https://docs.zama.org/protocol/protocol-apps/addresses/mainnet.md?ask=&goal= ``` -------------------------------- ### Clone FHEVM Foundry Template Source: https://docs.zama.org/protocol/solidity-guides/getting-started/setup-1.md Clone the official FHEVM Foundry template repository to get a pre-configured setup for FHEVM smart contract development. ```bash git clone https://github.com/zama-ai/fhevm-foundry-template cd fhevm-foundry-template ``` -------------------------------- ### Set up Zama SDK with viem Source: https://docs.zama.org/protocol/sdk/getting-started/quick-start.md Configure the Zama SDK for use with viem, including setting up public and wallet clients. Replace placeholder values like YOUR_KEY and your-app.com. ```ts import { createPublicClient, createWalletClient, custom, http } from "viem"; import { sepolia } from "viem/chains"; import { createConfig } from "@zama-fhe/sdk/viem"; import { ZamaSDK } from "@zama-fhe/sdk"; import { web } from "@zama-fhe/sdk/web"; import { sepolia as sepoliaFhe, type FheChain } from "@zama-fhe/sdk/chains"; const publicClient = createPublicClient({ chain: sepolia, transport: http("https://sepolia.infura.io/v3/YOUR_KEY"), }); const walletClient = createWalletClient({ chain: sepolia, transport: custom(window.ethereum!), }); const mySepolia = { ...sepoliaFhe, relayerUrl: "https://your-app.com/api/relayer/11155111", } as const satisfies FheChain; const config = createConfig({ chains: [mySepolia], publicClient, walletClient, relayers: { [mySepolia.id]: web(), }, }); const sdk = new ZamaSDK(config); ``` -------------------------------- ### Querying Documentation Dynamically Source: https://docs.zama.org/protocol/examples/basic/fhe-operations/fheadd.md To get more information not present on the current page, make an HTTP GET request to the page URL with the `ask` query parameter and an optional `goal` parameter. The `ask` parameter should contain a specific, self-contained question in natural language, while the `goal` parameter describes the broader objective. ```http GET https://docs.zama.org/protocol/examples/basic/fhe-operations/fheadd.md?ask=&goal= ``` -------------------------------- ### Reset FHEVM Hardhat Project Source: https://docs.zama.org/protocol/solidity-guides/getting-started/setup.md Remove all example code, test files, contracts, deployment scripts, and generated artifacts/cache to start with a clean project structure. ```sh rm -rf test/* contracts/* deploy ./fhevmTemp ./artifacts ./cache ./coverage ./types ./coverage.json ./dist ``` -------------------------------- ### Configure Environment Variables for Sepolia Deployment Source: https://docs.zama.org/protocol/solidity-guides/development-guide/foundry/deploy.md Copy the example environment file and fill in your private key and RPC URL. Source the file to load these variables into your shell. ```bash cp .env.example .env ``` ```bash # .env DEPLOYER_PRIVATE_KEY=0x... RPC_URL=https://sepolia.infura.io/v3/ # ETHERSCAN_API_KEY=... # optional, for verification ``` ```bash source .env ``` -------------------------------- ### Configure fromIndex for useTokenPairsSlice Source: https://docs.zama.org/protocol/sdk/api-references/react/usetokenpairsslice.md Example of setting the `fromIndex` parameter to specify the starting point (inclusive) for fetching token pairs. Pass `undefined` to disable the query. ```typescript useTokenPairsSlice({ fromIndex: 0n, toIndex: 10n }); ``` -------------------------------- ### Querying Documentation with Parameters Source: https://docs.zama.org/protocol/protocol/overview.md Demonstrates how to perform an HTTP GET request to query the documentation dynamically. Use the `ask` parameter for your question and optionally the `goal` parameter for broader context. ```http GET https://docs.zama.org/protocol/protocol/overview.md?ask=&goal= ``` -------------------------------- ### Authorize Contracts with useGrantPermit Source: https://docs.zama.org/protocol/sdk/api-references/react/usegrantpermit.md Use the useGrantPermit hook to get a mutation function for authorizing contract addresses. This example shows how to trigger the permit granting process when a button is clicked. ```typescript import { useGrantPermit } from "@zama-fhe/react-sdk"; function AllowButton({ contracts }: { contracts: `0x${string}`[] }) { const { mutateAsync: grantPermit, isPending } = useGrantPermit(); const handleAllow = async () => { await grantPermit(contracts); // All subsequent decrypt operations reuse the cached permits }; return ( ); } ``` -------------------------------- ### Set Hardhat Configuration Variable INFURA_API_KEY Source: https://docs.zama.org/protocol/solidity-guides/getting-started/setup.md Configure the INFURA_API_KEY variable to connect to Ethereum testnets like Sepolia. Obtain your key by following the Infura + MetaMask setup guide. ```sh npx hardhat vars set INFURA_API_KEY ``` -------------------------------- ### Query Documentation with Hardhat Source: https://docs.zama.org/protocol/solidity-guides/development-guide/hardhat/write_test.md Demonstrates how to query documentation dynamically using an HTTP GET request with 'ask' and 'goal' query parameters. This is useful for retrieving specific information or clarification not explicitly found on a page. ```HTTP GET https://docs.zama.org/protocol/solidity-guides/development-guide/hardhat/write_test.md?ask=&goal= ``` -------------------------------- ### Use useConfidentialBalance in a Component Source: https://docs.zama.org/protocol/sdk/api-references/react/useconfidentialbalance.md Fetch and display a token's confidential balance. This example shows how to use the hook with wagmi's useAccount to get the connected address. It handles loading and error states. ```typescript import { useConfidentialBalance } from "@zama-fhe/react-sdk"; import { useAccount } from "wagmi"; function TokenBalance({ tokenAddress }: { tokenAddress: `0x${string}` }) { const { address } = useAccount(); const { data: balance, isLoading, error, } = useConfidentialBalance({ address: tokenAddress, account: address, }); if (isLoading) return Decrypting...; if (error) return Error: {error.message}; return {balance?.toString()}; } ``` -------------------------------- ### Querying Documentation Dynamically Source: https://docs.zama.org/protocol/sdk/api-references/react/useunwrap.md Demonstrates how to query the documentation dynamically using a GET request with 'ask' and optional 'goal' query parameters. ```http GET https://docs.zama.org/protocol/sdk/api-references/react/useunwrap.md?ask=&goal= ``` -------------------------------- ### Set up Zama SDK for Node.js with viem Source: https://docs.zama.org/protocol/sdk/getting-started/quick-start.md Configure the Zama SDK for a Node.js environment using viem. This example uses environment variables for private keys and RPC URLs and sets up memory storage for the SDK. ```ts import { createConfig } from "@zama-fhe/sdk/viem"; import { ZamaSDK, memoryStorage } from "@zama-fhe/sdk"; import { node } from "@zama-fhe/sdk/node"; import { sepolia, type FheChain } from "@zama-fhe/sdk/chains"; import { createPublicClient, createWalletClient, http } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { sepolia as sepoliaViem } from "viem/chains"; const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); const publicClient = createPublicClient({ chain: sepoliaViem, transport: http(process.env.RPC_URL), }); const walletClient = createWalletClient({ account, chain: sepoliaViem, transport: http(process.env.RPC_URL), }); const mySepolia = { ...sepolia, network: process.env.RPC_URL! } as const satisfies FheChain; const config = createConfig({ chains: [mySepolia], publicClient, walletClient, storage: memoryStorage, relayers: { [mySepolia.id]: node({ poolSize: 4 }), }, }); const sdk = new ZamaSDK(config); ``` -------------------------------- ### Check Started Source: https://docs.zama.org/protocol/protocol-apps/staking.md Checks if the rewarder has been started and is currently accepting reward claims. ```APIDOC ## Check Started ### Description Returns `true` if the rewarder has been started and is accepting reward claims. ### Method CALL (Solidity View Function) ### Endpoint N/A (Direct contract interaction) ### Parameters None ### Response #### Success Response - **started** (bool) - `true` if the rewarder is started, `false` otherwise. ### Response Example ```json { "started": true } ``` ``` -------------------------------- ### Query Documentation with Agent Source: https://docs.zama.org/protocol/solidity-guides/smart-contract/configure.md Perform an HTTP GET request to query documentation dynamically. Use the 'ask' parameter for specific questions and the optional 'goal' parameter to tailor the response. ```http GET https://docs.zama.org/protocol/solidity-guides/smart-contract/configure.md?ask=&goal= ``` -------------------------------- ### Check if Rewarder Started Source: https://docs.zama.org/protocol/protocol-apps/staking.md Returns true if the rewarder has been started and is actively accepting reward claims. ```solidity bool started = operatorRewarder.isStarted(); ``` -------------------------------- ### useUnderlyingAllowance Parameters Example Source: https://docs.zama.org/protocol/sdk/api-references/react/useunderlyingallowance.md Example demonstrating the parameters for the `useUnderlyingAllowance` hook, specifically the `address` and `owner`. ```typescript const { data: allowance } = useUnderlyingAllowance({ address: "0xWrapper", owner: "0xOwner", }); ``` -------------------------------- ### Query Documentation with `ask` and `goal` Parameters Source: https://docs.zama.org/protocol/protocol-apps/addresses/testnet/sepolia.md Use this HTTP GET request to query the documentation dynamically. The `ask` parameter specifies your question, and the optional `goal` parameter provides context for your end objective. ```http GET https://docs.zama.org/protocol/protocol-apps/addresses/testnet/sepolia.md?ask=&goal= ``` -------------------------------- ### useWrapperDiscovery Parameters Example Source: https://docs.zama.org/protocol/sdk/api-references/react/usewrapperdiscovery.md Example demonstrating the parameters for the useWrapperDiscovery hook, specifically tokenAddress and erc20Address. ```typescript useWrapperDiscovery({ tokenAddress: "0xConfidentialToken", erc20Address: "0xUSDC", }); ``` -------------------------------- ### Token Interface Usage Source: https://docs.zama.org/protocol/sdk/api-references/sdk/token.md Demonstrates how to create a Token instance using `sdk.createToken()` and perform common operations like checking the balance and transferring tokens. ```APIDOC ## Token SDK Usage ### Description This snippet shows how to instantiate the `Token` interface and use its core methods. ### Method `sdk.createToken(tokenAddress: string)` ### Parameters - **tokenAddress** (string) - Required - The address of the confidential token. ### Usage Example ```ts import { ZamaSDK } from "@zama-fhe/sdk"; // Assuming sdk is already initialized with configuration // const sdk = new ZamaSDK(config); // Replace with your actual token address and owner address const tokenAddress = "0xConfidentialToken"; const ownerAddress = "0xOwnerAddress"; const recipientAddress = "0xRecipientAddress"; const transferAmount = 500n; // Create a Token instance const token = sdk.createToken(tokenAddress); // Get the balance of an owner const balance = await token.balanceOf(ownerAddress); console.log(`Balance: ${balance}`); // Perform a confidential transfer await token.confidentialTransfer(recipientAddress, transferAmount); console.log(`Transferred ${transferAmount} tokens to ${recipientAddress}`); ``` ### Related Operations - `balanceOf(owner: string)`: Returns the balance of the specified owner. - `confidentialTransfer(recipient: string, amount: bigint)`: Transfers a specified amount of tokens to a recipient. ### Note For shield/unshield operations, refer to the `WrappedToken` documentation. ``` -------------------------------- ### Querying Documentation with GET Request Source: https://docs.zama.org/protocol/sdk/api-references/sdk/genericsigner.md To get additional information not directly on the page, perform an HTTP GET request to the current page URL with the `ask` query parameter for your question and an optional `goal` parameter for the broader objective. ```http GET https://docs.zama.org/protocol/sdk/api-references/sdk/genericsigner.md?ask=&goal= ``` -------------------------------- ### Querying Documentation with Ask Parameter Source: https://docs.zama.org/protocol/solidity-guides/smart-contract/configure/contract_addresses.md Demonstrates how to query documentation dynamically using the `ask` and optional `goal` query parameters in an HTTP GET request. This is useful for retrieving information not explicitly present on the page or for clarification. ```http GET https://docs.zama.org/protocol/solidity-guides/smart-contract/configure/contract_addresses.md?ask=&goal= ``` -------------------------------- ### Query Documentation with Ask and Goal Parameters Source: https://docs.zama.org/protocol/examples/auctions Use this GET request to query the documentation dynamically. Include your specific question in the 'ask' parameter and an optional broader goal in the 'goal' parameter. ```http GET https://docs.zama.org/protocol/examples/auctions.md?ask=&goal= ``` -------------------------------- ### React (wagmi) SDK: After v3.x Source: https://docs.zama.org/protocol/sdk/migration/migrate-v2-to-v3.md Example of setting up the ZamaProvider with wagmi adapter in version 3.x. Configuration is simplified using `createConfig` and TanStack Query is integrated. ```tsx import { ZamaProvider } from "@zama-fhe/react-sdk"; import { createConfig as createZamaConfig } from "@zama-fhe/react-sdk/wagmi"; import { indexedDBStorage } from "@zama-fhe/sdk"; import { sepolia as fheSepolia, type FheChain } from "@zama-fhe/sdk/chains"; import { web } from "@zama-fhe/sdk/web"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; const queryClient = new QueryClient(); const mySepolia = { ...fheSepolia, relayerUrl: "/api/relayer", network: SEPOLIA_RPC_URL, } as const satisfies FheChain; const zamaConfig = createZamaConfig({ chains: [mySepolia], wagmiConfig, relayers: { [mySepolia.id]: web() }, storage: indexedDBStorage, // permitStorage defaults to `storage`; pass it only to split the backing store. onEvent: handleEvent, }); {children} ; ``` -------------------------------- ### Node.js Configuration Source: https://docs.zama.org/protocol/sdk/guides/configuration.md Set up the Zama SDK for Node.js environments. This example uses viem for client configuration and specifies a network URL for the chain. ```ts import { createConfig } from "@zama-fhe/sdk/viem"; import { ZamaSDK, memoryStorage } from "@zama-fhe/sdk"; import { node } from "@zama-fhe/sdk/node"; import { sepolia, type FheChain } from "@zama-fhe/sdk/chains"; const mySepolia = { ...sepolia, network: "https://sepolia.infura.io/v3/YOUR_KEY", } as const satisfies FheChain; const config = createConfig({ chains: [mySepolia], publicClient, walletClient, storage: memoryStorage, relayers: { [mySepolia.id]: node({ poolSize: 4 }), }, }); const sdk = new ZamaSDK(config); ``` -------------------------------- ### Instantiate ViemSigner with WalletClient and Ethereum Provider (Constructor Detail) Source: https://docs.zama.org/protocol/sdk/api-references/sdk/viemsigner.md Demonstrates the constructor for ViemSigner, explicitly showing the inclusion of the raw EIP-1193 provider for wallet event subscriptions. ```typescript const signer = new ViemSigner({ walletClient, ethereum: window.ethereum, }); ``` -------------------------------- ### Example: Building Handles List for Signature Verification Source: https://docs.zama.org/protocol/solidity-guides/smart-contract/functions.md Illustrates how to use `FHE.toBytes32` to convert encrypted values into `bytes32` handles, which are then collected into an array for use with functions like `checkSignatures`. ```solidity bytes32[] memory handles = new bytes32[](2); handles[0] = FHE.toBytes32(encryptedFoo); handles[1] = FHE.toBytes32(encryptedBar); ``` -------------------------------- ### Install Dependencies with Soldeer Source: https://docs.zama.org/protocol/solidity-guides/getting-started/setup-1.md Use Soldeer to install project dependencies, including forge-fhevm, encrypted-types, and OpenZeppelin contracts, into the `dependencies/` directory. ```bash forge soldeer install ``` -------------------------------- ### React (wagmi) SDK: Before v2.x Source: https://docs.zama.org/protocol/sdk/migration/migrate-v2-to-v3.md Example of setting up the ZamaProvider with wagmi adapter in version 2.x. It shows manual configuration of the relayer and storage. ```tsx import { ZamaProvider, RelayerWeb, indexedDBStorage, IndexedDBStorage } from "@zama-fhe/react-sdk"; import { WagmiSigner } from "@zama-fhe/react-sdk/wagmi"; import { SepoliaConfig } from "@zama-fhe/sdk"; const signer = new WagmiSigner({ config: wagmiConfig }); const sessionDBStorage = new IndexedDBStorage("SessionStore"); const relayer = useMemo( () => new RelayerWeb({ getChainId: () => signer.getChainId(), transports: { [SepoliaConfig.chainId]: { ...SepoliaConfig, relayerUrl: `${window.location.origin}/api/relayer`, network: SEPOLIA_RPC_URL, }, }, }), [], ); {children} ; ``` -------------------------------- ### Set up FHEVM Test Contract Source: https://docs.zama.org/protocol/solidity-guides/development-guide/foundry/write_test.md Inherit from FhevmTest and call super.setUp() to deploy FHEVM host contracts. Ensure the contract under test has a Zama config. ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.27; import {FhevmTest} from "forge-fhevm/FhevmTest.sol"; import {FHE} from "@fhevm/solidity/lib/FHE.sol"; import "encrypted-types/EncryptedTypes.sol"; contract MyTest is FhevmTest { MyContract myContract; function setUp() public override { super.setUp(); // deploy FHEVM host contracts myContract = new MyContract(); } } ``` -------------------------------- ### Query Documentation with GitBook Agent Source: https://docs.zama.org/protocol/examples/openzeppelin-confidential-contracts/erc7984/swaperc7984toerc20.md Use this HTTP GET request to query the documentation dynamically. Include an 'ask' parameter for your specific question and an optional 'goal' parameter for broader context. The response will provide a direct answer and relevant excerpts. ```http GET https://docs.zama.org/protocol/examples/openzeppelin-confidential-contracts/erc7984/swaperc7984toerc20.md?ask=&goal= ``` -------------------------------- ### Get All Confidential (Token, Wrapper) Pairs Source: https://docs.zama.org/protocol/protocol-apps/confidential-tokens/wrapper-registry.md Retrieves all registered confidential token and wrapper pairs, including those that have been revoked. Use this to get a comprehensive list of all pairs. ```Solidity TokenWrapperPair[] memory tokenConfidentialTokenPairs = registry.getTokenConfidentialTokenPairs(); ``` -------------------------------- ### Initialize ViemSigner with WalletClient and Ethereum Provider Source: https://docs.zama.org/protocol/sdk/api-references/sdk/viemsigner.md Instantiate ViemSigner with a viem WalletClient and an EIP-1193 provider. This setup allows the signer to emit wallet lifecycle events. ```typescript import { createWalletClient, custom } from "viem"; import { sepolia } from "viem/chains"; import { ViemSigner } from "@zama-fhe/sdk/viem"; const walletClient = createWalletClient({ chain: sepolia, transport: custom(window.ethereum!), }); const signer = new ViemSigner({ walletClient, ethereum: window.ethereum }); ``` -------------------------------- ### Query Documentation API Source: https://docs.zama.org/protocol/sdk/api-references/react/usefinalizeunwrap.md Demonstrates how to query the documentation dynamically using an HTTP GET request with 'ask' and optional 'goal' query parameters. ```http GET https://docs.zama.org/protocol/sdk/api-references/react/usefinalizeunwrap.md?ask=&goal= ``` -------------------------------- ### Install FHEVM Hardhat Project Dependencies Source: https://docs.zama.org/protocol/solidity-guides/getting-started/setup.md Install all required project dependencies defined in the `package.json` file. This command should be run from the root directory of your FHEVM Hardhat project. ```sh npm install ``` -------------------------------- ### Start Local Anvil Node Source: https://docs.zama.org/protocol/solidity-guides/development-guide/foundry/deploy.md Start a local Anvil node in a separate terminal. This node will serve as the local blockchain environment for deploying and testing your FHEVM contracts. ```bash anvil ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.zama.org/protocol/sdk/guides/node-js-backend.md Use this GET request to ask specific questions about the documentation. The 'goal' parameter can be used to tailor the response to a broader objective. ```http GET https://docs.zama.org/protocol/sdk/guides/node-js-backend.md?ask=&goal= ``` -------------------------------- ### Viem Client Setup Source: https://docs.zama.org/protocol/sdk/guides/configuration.md Configure Viem clients for public and wallet access. Ensure the chain and transport (e.g., HTTP endpoint) are correctly specified. ```typescript import { createPublicClient, createWalletClient, custom, http } from "viem"; import { sepolia } from "viem/chains"; const publicClient = createPublicClient({ chain: sepolia, transport: http("https://sepolia.infura.io/v3/YOUR_KEY"), }); const walletClient = createWalletClient({ chain: sepolia, transport: custom(window.ethereum!), }); ``` -------------------------------- ### Wagmi Setup with ZamaProvider Source: https://docs.zama.org/protocol/sdk/api-references/react/zamaprovider.md Configure and wrap your application with ZamaProvider when using wagmi for blockchain interactions. This setup includes configuring both wagmi and Zama SDK chains and relayers. ```typescript import { WagmiProvider, createConfig, http } from "wagmi"; import { sepolia } from "wagmi/chains"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { ZamaProvider } from "@zama-fhe/react-sdk"; import { web } from "@zama-fhe/sdk/web"; import { createConfig as createZamaConfig } from "@zama-fhe/react-sdk/wagmi"; import { sepolia as sepoliaFhe, type FheChain } from "@zama-fhe/sdk/chains"; const wagmiConfig = createConfig({ chains: [sepolia], transports: { [sepolia.id]: http("https://sepolia.infura.io/v3/YOUR_KEY") }, }); const mySepolia = { ...sepoliaFhe, relayerUrl: "https://your-app.com/api/relayer/11155111", network: "https://sepolia.infura.io/v3/YOUR_KEY", } as const satisfies FheChain; const zamaConfig = createZamaConfig({ chains: [mySepolia], wagmiConfig, relayers: { [mySepolia.id]: web(), }, }); const queryClient = new QueryClient(); function App() { return ( ); } ``` -------------------------------- ### Verify Node.js and npm Installation Source: https://docs.zama.org/protocol/solidity-guides/getting-started/setup.md Check if Node.js and npm are installed correctly on your system. Ensure you are using an even-numbered LTS version of Node.js, as Hardhat does not support odd-numbered versions. ```sh node -v npm -v ``` -------------------------------- ### Trivial Encryption Examples Source: https://docs.zama.org/protocol/solidity-guides/smart-contract/operations/casting.md Demonstrates how to convert plaintext boolean and uint64 values into their encrypted FHE equivalents using `asEbool` and `asEuint64`. ```Solidity euint64 value64 = FHE.asEuint64(7262); // Trivial encrypt a uint64 ebool valueBool = FHE.asEbool(true); // Trivial encrypt a boolean ``` -------------------------------- ### Custom Error Example in a Function Source: https://docs.zama.org/protocol/solidity-guides/smart-contract/logics/error_handling.md This example demonstrates defining a custom error and using it within a function to handle a specific failure condition, providing clear feedback to the caller. ```solidity error NotOwner(); function transferOwnership(address newOwner) public { if (msg.sender != owner) { revert NotOwner(); } owner = newOwner; } ``` -------------------------------- ### For Loop in Solidity Source: https://docs.zama.org/protocol/solidity-guides/smart-contract/logics/loop.md Demonstrates the basic syntax of a for loop in Solidity. Use for loops when the number of iterations is known beforehand. ```solidity uint[] public numbers; function addNumbers() public { for (uint i = 0; i < 5; i++) { numbers.push(i); } } ``` -------------------------------- ### Cleartext (Local Dev) Setup with ZamaProvider Source: https://docs.zama.org/protocol/sdk/api-references/react/zamaprovider.md Configure ZamaProvider for local development using the 'cleartext' relayer. This setup is suitable for testing and development environments where direct, unencrypted communication is acceptable. ```typescript import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { ZamaProvider } from "@zama-fhe/react-sdk"; import { cleartext } from "@zama-fhe/sdk"; import { createConfig } from "@zama-fhe/sdk/viem"; import { hardhat } from "@zama-fhe/sdk/chains"; const zamaConfig = createConfig({ chains: [hardhat], publicClient, walletClient, relayers: { [hardhat.id]: cleartext(), }, }); const queryClient = new QueryClient(); function App() { return ( ); } ```