### Install Dependencies and Run Tests Source: https://github.com/iden3/contracts/blob/master/_autodocs/README.md Installs project dependencies and runs the test suite using Hardhat. Ensure you are in the 'contracts' directory before running. ```bash cd contracts npm install npx hardhat test ``` -------------------------------- ### Example: Setting a Multi-Request Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/universal-verifier.md Demonstrates how to construct and set a multi-request using the `setMultiRequest` function. This example includes individual and group request IDs. ```solidity uint256[] memory requestIds = new uint256[](2); requestIds[0] = 1; requestIds[1] = 2; uint256[] memory groupIds = new uint256[](1); groupIds[0] = 10; IVerifier.MultiRequest memory multiReq = IVerifier.MultiRequest({ multiRequestId: 100, requestIds: requestIds, groupIds: groupIds, metadata: "" }); universalVerifier.setMultiRequest(multiReq); ``` -------------------------------- ### Poseidon Hash Usage Example Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/libraries.md Demonstrates how to use the Poseidon hash functions for single, double, and triple inputs after importing the library. ```solidity using Poseidon for *; uint256 hash = Poseidon.poseidon1([value1]); uint256 hash2 = Poseidon.poseidon2([value1, value2]); uint256 hash3 = Poseidon.poseidon3([value1, value2, value3]); ``` -------------------------------- ### Nonce Management Example Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/payment-contracts.md Demonstrates how to manage nonces for preventing replay attacks. Each nonce must be unique and incremented for subsequent payments. ```solidity // First payment uint256 nonce = 1; // Second payment nonce = 2; // Must increment ``` -------------------------------- ### Example: Logging Multi-Request Proof Statuses Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/universal-verifier.md Iterates through the returned `RequestProofStatus` array to log the verification status for each request within a multi-request. ```solidity IVerifier.RequestProofStatus[] memory statuses = universalVerifier.getMultiRequestProofsStatus(100, userAddress); for (uint i = 0; i < statuses.length; i++) { console.log("Request", statuses[i].requestId, "verified:", statuses[i].isVerified); } ``` -------------------------------- ### Submit Proof Response with Web3.js Source: https://github.com/iden3/contracts/blob/master/_autodocs/README.md This example shows how to submit a proof response using Web3.js. Ensure you have the ABI and contract address correctly configured. It logs the transaction hash upon successful submission. ```javascript const web3 = new Web3(provider); const contract = new web3.eth.Contract(ABI, contractAddress); // Submit proof response const tx = await contract.methods.submitResponse( authResponse, responses, crossChainProofs ).send({from: userAddress}); console.log("Transaction hash:", tx.transactionHash); ``` -------------------------------- ### Run Hardhat Tests Source: https://github.com/iden3/contracts/blob/master/README.md Execute all tests using the Hardhat testing framework. Ensure Hardhat is installed in your project. ```shell npx hardhat test ``` -------------------------------- ### Example: Asserting Multi-Request Verification Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/universal-verifier.md Uses a `require` statement to ensure that all proofs for a multi-request have been verified before proceeding. Throws an error if verification is not complete. ```solidity bool verified = universalVerifier.isMultiRequestVerified(100, userAddress); require(verified, "Not all proofs verified yet"); ``` -------------------------------- ### Get Contract Instance with Hardhat Source: https://github.com/iden3/contracts/blob/master/_autodocs/README.md Use this snippet to get contract instances for 'IState' and 'UniversalVerifier' within a Hardhat environment. It demonstrates how to check identity existence and retrieve state information. ```typescript import { ethers } from "hardhat"; // Get contract instance const state = await ethers.getContractAt("IState", stateAddress); const verifier = await ethers.getContractAt("UniversalVerifier", verifierAddress); // Check identity exists const exists = await state.idExists(identityId); // Get current state const stateInfo = await state.getStateInfoById(identityId); console.log("Current state:", stateInfo.state); ``` -------------------------------- ### Get GIST Root Info Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/state-contract.md Retrieves information about a specific GIST root. Use this to check the validity and history of a GIST root. ```solidity function getGISTRootInfo(uint256 root) external view returns (GistRootInfo memory) ``` ```solidity IState.GistRootInfo memory rootInfo = state.getGISTRootInfo(gistRootValue); require(rootInfo.createdAtTimestamp > 0, "GIST root not found"); ``` -------------------------------- ### Get Merkle Proof for Leaf Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/libraries.md Generates a Merkle proof for a leaf at a specific index against the current root of the Sparse Merkle Tree. The returned proof includes the root and the necessary siblings. ```solidity function getProof(SmtLib.Data storage data, uint256 index) internal view returns (SmtLib.Proof memory) ``` ```javascript SmtLib.Proof memory proof = SmtLib.getProof(tree, leafIndex); console.log("Root:", proof.root); console.log("Siblings length:", proof.siblings.length); ``` -------------------------------- ### Get State Info By ID and State Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/state-contract.md Retrieves state information for a specific identity and state combination. Useful for querying historical state data. ```solidity function getStateInfoByIdAndState( uint256 id, uint256 state ) external view returns (StateInfo memory) ``` ```solidity IState.StateInfo memory historicalState = state.getStateInfoByIdAndState(identityId, oldStateValue); console.log("This state was valid for", historicalState.replacedAtTimestamp - historicalState.createdAtTimestamp, "seconds"); ``` -------------------------------- ### Hardhat Ignition Network Parameters Source: https://github.com/iden3/contracts/blob/master/_autodocs/configuration.md Store network-specific parameters for Hardhat Ignition deployments in JSON files located at `ignition/modules/params/chain-.json`. This example shows parameters for Ethereum mainnet (chainId: 1). ```json { "stateAddress": "0x3C9acB2205Aa72A05F6D77d708b5Cf85FCa3a896", "stateTransitionVerifierAddress": "0x...", "defaultIdType": "0x0001", "owner": "0x..." } ``` -------------------------------- ### Deploy System (Step 1) Source: https://github.com/iden3/contracts/blob/master/README.md Run the first step of the 2-step deployment process to deploy initial implementation contracts for the entire system using an unknown address. Replace with the target network. ```shell npx hardhat run scripts/deploy/deployment-step-1/deploySystem.ts --network ``` -------------------------------- ### Deploy System (Step 2) Source: https://github.com/iden3/contracts/blob/master/README.md Execute the second step of the 2-step deployment process to deploy final implementation contracts for the entire system using your Ledger address. Replace with the target network. ```shell npx hardhat run scripts/deploy/deployment-step-2/deploySystem.ts --network ``` -------------------------------- ### Get Contract Version Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/universal-verifier.md Retrieves the current version of the Universal Verifier contract. ```APIDOC ## version ### Description Returns the contract version. ### Method `pure` ### Returns - `string` - The contract version string (e.g., "3.0.0") ``` -------------------------------- ### Get State Contract Version Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/state-contract.md Retrieves the semantic version of the State contract implementation. This is a constant value. ```solidity string public constant VERSION = "2.6.3" ``` -------------------------------- ### Get Validator Version Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/validators.md Retrieves the current version string of the validator contract. Use this to check compatibility. ```solidity function version() external view returns (string memory) ``` -------------------------------- ### Download zk Circuits Source: https://github.com/iden3/contracts/blob/master/README.md Download the necessary zk circuits for generation and verification of proofs. Navigate to the scripts directory and execute the download script. ```bash cd ./scripts/upgrade/verifiers/helpers ./dl_circuits.sh ``` -------------------------------- ### Using SmtLib for Identity Tree Operations Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/libraries.md This snippet shows how to initialize and use SmtLib for managing an identity tree, including adding claims and retrieving proofs and roots. Ensure SmtLib is imported and the tree level is set during initialization. ```solidity pragma solidity 0.8.27; import {SmtLib} from "./lib/SmtLib.sol"; contract MyIdentityContract { using SmtLib for SmtLib.Data; SmtLib.Data internal identityTree; constructor() { identityTree.initialize(20); // 20-level tree } function addClaim(uint256 claimIndex, uint256 claimData) external { identityTree.add(claimIndex, claimData); emit ClaimAdded(claimIndex, claimData); } function getClaimProof(uint256 claimIndex) external view returns (SmtLib.Proof memory) { return identityTree.getProof(claimIndex); } function getCurrentRoot() external view returns (uint256) { return identityTree.getRoot(); } } ``` -------------------------------- ### Get Owner Balance Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/payment-contracts.md Retrieves the owner's accumulated fees. The balance is returned in wei or token units. ```solidity function getOwnerBalance() external view returns (uint256) ``` -------------------------------- ### Deploy Libraries Source: https://github.com/iden3/contracts/blob/master/README.md Deploy the library contracts required for the system. Replace with the target network. ```shell npx hardhat run scripts/deploy/deployLibraries.ts --network ``` -------------------------------- ### Get Oracle Signing Address Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/cross-chain-validator.md Retrieves the currently active oracle signing address. Returns the address of the oracle. ```solidity function getOracleSigningAddress() public view returns (address) ``` ```solidity address currentOracle = ccValidator.getOracleSigningAddress(); ``` -------------------------------- ### Get Contract Version Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/universal-verifier.md Retrieves the current version of the Universal Verifier contract. This is a pure function and does not modify the contract state. ```solidity function version() public pure returns (string memory) ``` -------------------------------- ### Get Request Owner - Solidity Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/universal-verifier.md Retrieves the current owner of a specified request. The `requestId` parameter is used to identify the request. ```solidity function getRequestOwner(uint256 requestId) public view returns (address) ``` -------------------------------- ### Postinstall script for patching Source: https://github.com/iden3/contracts/blob/master/patches/README.md This script is executed during the post-installation process to apply necessary patches to the hardhat-ledger plugin. It ensures that the plugin functions correctly on zkEVM networks. ```json "postinstall": "patch-package" ``` -------------------------------- ### Get Request Count Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/universal-verifier.md Retrieves the total number of requests that have been defined in the contract. Use this to understand the scale of registered requests. ```solidity function getRequestsCount() external view returns (uint256) ``` ```solidity uint256 count = universalVerifier.getRequestsCount(); ``` -------------------------------- ### Get Recipient Balance Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/payment-contracts.md Retrieves the claimable balance for a given recipient address. The balance is returned in wei or token units. ```solidity function getBalance(address recipient) external view returns (uint256) ``` -------------------------------- ### initialize Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/identity-tree-store.md Initializes the Identity Tree Store contract, linking it to the State contract. ```APIDOC ## initialize ### Description Initializes the Identity Tree Store contract with reference to the State contract. ### Method `public` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|---------|----------|---------|--------------------------| | state | address | Yes | — | Address of the State contract | ### Return None ### Example ```solidity identityTreeStore.initialize(stateContractAddress); ``` ``` -------------------------------- ### initialize Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/state-contract.md Initializes the State contract with the state transition verifier, default ID type, owner address, and cross-chain proof validator. ```APIDOC ## initialize ### Description Initializes the State contract with required parameters. ### Method `initialize` ### Parameters #### Parameters - **verifierContractAddr** (IStateTransitionVerifier) - Required - Address of the state transition verifier contract - **defaultIdType** (bytes2) - Required - Default ID type for Ethereum-based IDs calculation - **owner** (address) - Required - Address of the contract owner with administrative privileges - **validator** (ICrossChainProofValidator) - Required - Cross-chain proof validator contract address ### Request Example ```solidity IStateTransitionVerifier verifier = IStateTransitionVerifier(verifierAddress); ICrossChainProofValidator ccValidator = ICrossChainProofValidator(validatorAddress); state.initialize(verifier, 0x0001, ownerAddress, ccValidator); ``` ``` -------------------------------- ### initialize Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/libraries.md Initializes an empty sparse merkle tree with a specified maximum depth. ```APIDOC ## initialize ### Description Initializes an empty sparse merkle tree. ### Method internal ### Signature function initialize(SmtLib.Data storage data, uint256 maxDepth) internal ### Parameters #### Path Parameters - **data** (Data) - Storage reference - **maxDepth** (uint256) - Maximum tree depth ### Request Example ```solidity contract MyContract { SmtLib.Data internal tree; constructor() { SmtLib.initialize(tree, 20); // 20-level tree } } ``` ``` -------------------------------- ### initialize() Source: https://github.com/iden3/contracts/blob/master/_autodocs/configuration.md Initializes the Universal Verifier contract with the State contract address and the owner address. This function must be called once during deployment. ```APIDOC ## initialize() ### Description Initializes the Universal Verifier contract with the State contract address and the owner address. This function must be called once during deployment. ### Function Signature ```solidity function initialize(IState state, address owner) public initializer ``` ### Parameters #### Parameters - **state** (IState) - Yes - Address of the State contract for identity and GIST validation - **owner** (address) - Yes - Owner address for administrative functions (add validators, manage requests) ### Request Example ```solidity address stateAddr = 0x3C9acB2205Aa72A05F6D77d708b5Cf85FCa3a896; // Unified address address owner = 0xYourOwnerAddress; verifier.initialize(stateAddr, owner); ``` ### Post-Initialization Configuration After initialization, the contract owner must perform the following configurations: 1. Add validator implementations to whitelist: ```solidity verifier.addValidatorToWhitelist(authV3ValidatorAddress); verifier.addValidatorToWhitelist(credentialQueryV3ValidatorAddress); ``` 2. Set auth methods: ```solidity IVerifier.AuthMethod memory authV3 = IVerifier.AuthMethod({ authMethod: "authV3", validator: authValidator, params: abi.encode(...) }); verifier.setAuthMethod(authV3); ``` 3. Define requests (application-specific): ```solidity IVerifier.Request[] memory requests = new IVerifier.Request[](1); requests[0] = IVerifier.Request({ requestId: 1, metadata: "Age verification", validator: credentialValidator, params: abi.encode(schema, claimPath, operator, values), creator: msg.sender }); verifier.setRequests(requests); ``` ``` -------------------------------- ### Deploy State Contract Source: https://github.com/iden3/contracts/blob/master/README.md Deploy the State contract. Replace with the target network. ```shell npx hardhat run scripts/deploy/deployState.ts --network ``` -------------------------------- ### Get Owner Fee Percentage Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/payment-contracts.md Retrieves the current fee percentage set for the owner. This value is used to calculate fees on transactions. ```solidity function getOwnerPercentage() external view returns (uint8) ``` ```solidity uint8 feePercent = mcPayment.getOwnerPercentage(); console.log("Owner fee:", feePercent, "%"); ``` -------------------------------- ### Network RPC URLs for Deployment Source: https://github.com/iden3/contracts/blob/master/_autodocs/configuration.md Set these environment variables to point to the RPC endpoints of various Ethereum and EVM-compatible networks. Required for deployment scripts. ```bash ETHEREUM_MAINNET_RPC_URL=https://eth-mainnet.g.alchemy.com/v2/... ETHEREUM_SEPOLIA_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/... POLYGON_MAINNET_RPC_URL=https://polygon-mainnet.g.alchemy.com/v2/... POLYGON_AMOY_RPC_URL=https://polygon-amoy.g.alchemy.com/v2/... ZKEVM_MAINNET_RPC_URL=https://zkevm-mainnet.g.alchemy.com/v2/... ZKEVM_CARDONA_RPC_URL=https://zkevm-cardona.g.alchemy.com/v2/... LINEA_MAINNET_RPC_URL=https://linea-mainnet.infura.io/v3/... LINEA_SEPOLIA_RPC_URL=https://linea-sepolia.infura.io/v3/... BASE_MAINNET_RPC_URL=https://base-mainnet.g.alchemy.com/v2/... BASE_SEPOLIA_RPC_URL=https://base-sepolia.g.alchemy.com/v2/... BNB_MAINNET_RPC_URL=https://bsc-mainnet.infura.io/v3/... BNB_TESTNET_RPC_URL=https://bsc-testnet.infura.io/v3/... PRIVADO_MAINNET_RPC_URL=... PRIVADO_TESTNET_RPC_URL=... BILLIONS_MAINNET_RPC_URL=... BILLIONS_TESTNET_RPC_URL=... ``` -------------------------------- ### Get GIST Root Replaced Timestamp Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/state-contract.md Retrieves the Unix timestamp when a GIST root was replaced. Returns 0 if the root is current. ```solidity function getGistRootReplacedAt( bytes2 idType, uint256 root ) external view returns (uint256 replacedAtTimestamp) ``` ```solidity uint256 replacementTime = state.getGistRootReplacedAt(0x0001, gistRoot); ``` -------------------------------- ### Configure .env for Deployments Source: https://github.com/iden3/contracts/blob/master/README.md Set up your .env file with necessary environment variables for contract deployments. This includes your Ledger account address and RPC URLs for various networks. Ensure your Ledger device is configured for blind signing. ```dotenv LEDGER_ACCOUNT="" DEPLOY_STRATEGY=create2 PRIVADO_MAINNET_RPC_URL= PRIVADO_TESTNET_RPC_URL= BILLIONS_MAINNET_RPC_URL= BILLIONS_TESTNET_RPC_URL= POLYGON_MAINNET_RPC_URL= POLYGON_AMOY_RPC_URL= ETHEREUM_MAINNET_RPC_URL= ETHEREUM_SEPOLIA_RPC_URL= ZKEVM_MAINNET_RPC_URL= ZKEVM_CARDONA_RPC_URL= LINEA_MAINNET_RPC_URL= LINEA_SEPOLIA_RPC_URL= BASE_MAINNET_RPC_URL= BASE_SEPOLIA_RPC_URL= BNB_MAINNET_RPC_URL= BNB_TESTNET_RPC_URL= ETHERSCAN_API_KEY= ``` -------------------------------- ### Configuration Errors Source: https://github.com/iden3/contracts/blob/master/_autodocs/errors.md These Solidity snippets highlight configuration problems. VerifierAddressShouldNotBeZero and OracleSigningAddressShouldNotBeZero indicate that contract addresses have not been initialized. InvalidOwnerPercentage and CircuitsLengthShouldBeOne point to invalid parameter values. ```solidity // Contract not initialized VerifierAddressShouldNotBeZero() OracleSigningAddressShouldNotBeZero() // Invalid parameters InvalidOwnerPercentage() CircuitsLengthShouldBeOne() ``` -------------------------------- ### Get State Info By ID Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/state-contract.md Retrieves the latest state information for a given identity. Use this to check the current state of an identity. ```solidity function getStateInfoById(uint256 id) external view returns (StateInfo memory) ``` ```solidity IState.StateInfo memory stateInfo = state.getStateInfoById(identityId); require(stateInfo.state != 0, "Identity does not exist"); console.log("State created at block", stateInfo.createdAtBlock); ``` -------------------------------- ### MCPayment Contract Initialization and Configuration Source: https://github.com/iden3/contracts/blob/master/_autodocs/configuration.md Details on how to initialize the MCPayment contract and configure owner fees. ```APIDOC ## MCPayment Contract ### initialize() #### Description Initializes the MCPayment contract with the owner's address and their fee percentage. #### Method `initialize(address owner, uint8 ownerPercentage)` #### Parameters - **owner** (address) - Required - The contract owner and fee recipient. - **ownerPercentage** (uint8) - Required - The owner's fee percentage (0-100). #### Request Example ```solidity // 5% owner fee mcPayment.initialize(ownerAddress, 5); ``` ### setIssuerOwnerPercentage() #### Description Sets a custom fee percentage for a specific issuer. #### Method `setIssuerOwnerPercentage(address issuer, uint8 percentage)` #### Parameters - **issuer** (address) - Required - The address of the issuer. - **percentage** (uint8) - Required - The fee percentage for the issuer (0-100). #### Request Example ```solidity // Set custom fee for specific issuer mcPayment.setIssuerOwnerPercentage(issuerAddress, 10); // 10% for this issuer ``` ### setOwnerPercentage() #### Description Updates the global default owner fee percentage. #### Method `setOwnerPercentage(uint8 percentage)` #### Parameters - **percentage** (uint8) - Required - The new default fee percentage (0-100). #### Request Example ```solidity // Update global fee mcPayment.setOwnerPercentage(8); // New default fee ``` ``` -------------------------------- ### Get Grouped Requests Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/universal-verifier.md Fetches all requests associated with a given group ID. Useful for retrieving related requests for batch processing or auditing. ```solidity function getGroupedRequests(uint256 groupID) external view returns (RequestInfo[] memory) ``` ```solidity IVerifier.RequestInfo[] memory groupReqs = universalVerifier.getGroupedRequests(10); console.log("Group has", groupReqs.length, "requests"); ``` -------------------------------- ### Ledger Hardware Wallet Configuration Source: https://github.com/iden3/contracts/blob/master/_autodocs/configuration.md Configure these environment variables for deploying contracts using a hardware wallet. Specify the account address and deployment strategy. ```bash LEDGER_ACCOUNT=0x1234567890123456789012345678901234567890 DEPLOY_STRATEGY=create2 ``` -------------------------------- ### Get State Replaced Timestamp Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/state-contract.md Retrieves the Unix timestamp when a specific identity state was replaced by the next state. Returns 0 if the state is current. ```solidity function getStateReplacedAt( uint256 id, uint256 state ) external view returns (uint256 replacedAtTimestamp) ``` ```solidity uint256 replacementTime = state.getStateReplacedAt(identityId, oldState); if (replacementTime > 0) { console.log("This state was replaced at timestamp", replacementTime); } ``` -------------------------------- ### Run Tests with Gas and Costs Report Source: https://github.com/iden3/contracts/blob/master/README.md Execute tests with comprehensive gas statistics and costs reporting. Requires a CoinMarketCap API key and the REPORT_GAS variable set. ```shell COINMARKETCAP_KEY=<> REPORT_GAS=true npx hardhat test ``` -------------------------------- ### Deploy Universal Verifier Contract Source: https://github.com/iden3/contracts/blob/master/README.md Deploy the Universal Verifier contract. Replace with the target network. ```shell npx hardhat run scripts/deploy/deployUniversalVerifier.ts --network ``` -------------------------------- ### Get Default Identity Type Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/state-contract.md Use `getDefaultIdType` to retrieve the default two-byte ID type configured for Ethereum-based identity calculations. This function does not require any parameters. ```solidity function getDefaultIdType() external view returns (bytes2) ``` ```solidity bytes2 defaultType = state.getDefaultIdType(); ``` -------------------------------- ### Get Identity Type if Supported Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/state-contract.md Use `getIdTypeIfSupported` to retrieve the two-byte ID type for a given identity identifier. The function will revert if the identity type is not supported. ```solidity function getIdTypeIfSupported(uint256 id) external view returns (bytes2) ``` ```solidity bytes2 idType = state.getIdTypeIfSupported(identityId); console.log("Identity type:", idType); ``` -------------------------------- ### Deploy Identity Tree Store Contract Source: https://github.com/iden3/contracts/blob/master/README.md Deploy the Identity Tree Store contract. Replace with the target network. ```shell npx hardhat run scripts/deploy/deployIdentityTreeStore.ts --network ``` -------------------------------- ### Get Revocation Status at Historical State Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/identity-tree-store.md Query the revocation status of a credential at a specific historical state of the issuer. This is useful for auditing or verifying past states. ```solidity function getRevocationStatusByIdAndState( uint256 id, uint256 state, uint64 nonce ) external view returns (CredentialStatus memory) ``` ```solidity // Check revocation status at a historical state IOnchainCredentialStatusResolver.CredentialStatus memory historicalStatus = identityTreeStore.getRevocationStatusByIdAndState(issuerId, historicalState, nonce); ``` -------------------------------- ### Initialize Universal Verifier Contract Source: https://github.com/iden3/contracts/blob/master/_autodocs/configuration.md Use this snippet to initialize the Universal Verifier contract with the State contract address and the owner's address. Ensure the state and owner addresses are correctly defined before deployment. ```solidity address stateAddr = 0x3C9acB2205Aa72A05F6D77d708b5Cf85FCa3a896; // Unified address address owner = 0xYourOwnerAddress; verifier.initialize(stateAddr, owner); ``` -------------------------------- ### Using PoseidonLib for Hashing Pairs Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/libraries.md Demonstrates how to use PoseidonUnit2L from PoseidonLib to hash a pair of uint256 values. This is useful for cryptographic hashing within smart contracts. ```solidity import {PoseidonUnit2L} from "./lib/Poseidon.sol"; contract MyHashContract { function hashPair(uint256 a, uint256 b) external pure returns (uint256) { return PoseidonUnit2L.poseidon2([a, b]); } } ``` -------------------------------- ### Get Issuer-Specific Owner Fee Percentage Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/payment-contracts.md Retrieves the owner fee percentage configured for a particular issuer address. This allows for custom fee rates per issuer. ```solidity function getIssuerOwnerPercentage(address issuer) external view returns (uint8) ``` -------------------------------- ### Get Current Root of Sparse Merkle Tree Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/libraries.md Retrieves the current root hash of the Sparse Merkle Tree. This function is a simple view operation and does not modify the tree. ```solidity function getRoot(SmtLib.Data storage data) internal view returns (uint256) ``` -------------------------------- ### Run Tests with Gas Statistics Source: https://github.com/iden3/contracts/blob/master/README.md Run tests and generate a report detailing gas usage statistics. Set the REPORT_GAS environment variable to true. ```shell REPORT_GAS=true npx hardhat test ``` -------------------------------- ### Get Historical Roots with Pagination Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/libraries.md Retrieves a paginated list of historical root entries from the Sparse Merkle Tree. The results are limited by a specified offset and limit, and capped by ROOT_INFO_LIST_RETURN_LIMIT. ```solidity function getRootHistory( SmtLib.Data storage data, uint256 offset, uint256 limit ) internal view returns (RootEntry[] memory) ``` ```javascript SmtLib.RootEntry[] memory roots = SmtLib.getRootHistory(tree, 0, 100); console.log("Found", roots.length, "root entries"); ``` -------------------------------- ### Initialize State Contract Source: https://github.com/iden3/contracts/blob/master/_autodocs/configuration.md Use this to initialize the State contract. Ensure you provide valid addresses for the verifier, owner, and cross-chain validator, along with the appropriate default identity type for your network. ```solidity address verifier = 0xYourVerifierAddress; bytes2 idType = 0x0001; // Ethereum address owner = 0xYourOwnerAddress; address ccValidator = 0xCrossChainValidatorAddress; state.initialize(verifier, idType, owner, ccValidator); ``` -------------------------------- ### IdentityTreeStore initialize Source: https://github.com/iden3/contracts/blob/master/_autodocs/configuration.md Initializes the IdentityTreeStore contract with the address of the State contract. ```APIDOC ## initialize() IdentityTreeStore ### Description Initializes the IdentityTreeStore contract, setting the State contract address for identity validation. ### Method `initialize(address state)` ### Parameters #### Path Parameters - **state** (address) - Required - Address of the State contract for identity validation ### Request Example ```solidity address stateAddr = 0x3C9acB2205Aa72A05F6D77d708b5Cf85FCa3a896; identityTreeStore.initialize(stateAddr); ``` ``` -------------------------------- ### Initialize Identity Tree Store Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/identity-tree-store.md Initializes the contract with a reference to the State contract. Ensure the State contract address is valid before calling. ```Solidity identityTreeStore.initialize(stateContractAddress); ``` -------------------------------- ### Get Revocation Status Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/identity-tree-store.md Retrieve the current revocation status of a credential using its issuer ID and nonce. Check the `revocationStatus` field to determine if the credential is valid (0) or revoked (non-zero). ```solidity function getRevocationStatus( uint256 id, uint64 nonce ) external view returns (CredentialStatus memory) ``` ```solidity IOnchainCredentialStatusResolver.CredentialStatus memory status = identityTreeStore.getRevocationStatus(issuerId, revocationNonce); if (status.revocationStatus == 0) { console.log("Credential is valid"); } else { console.log("Credential is revoked"); } ``` -------------------------------- ### MCPayment Contract Initialization Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/payment-contracts.md Initializes the MCPayment contract with the owner's address and their fee percentage. The owner percentage must be between 0 and 100. ```APIDOC ## initialize ### Description Initializes the MCPayment contract with owner and fee percentage. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **owner** (address) - Required - The address of the contract owner. - **ownerPercentage** (uint8) - Required - The owner's fee percentage (0-100). ### Request Example ```solidity mcPayment.initialize(ownerAddress, 5); // 5% owner fee ``` ### Response #### Success Response (200) None #### Response Example None ### Throws - `InvalidOwnerPercentage()` if ownerPercentage > 100 ``` -------------------------------- ### Get Merkle Proof by Historical Root Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/libraries.md Generates a Merkle proof for a leaf at a specific index against a particular historical root of the Sparse Merkle Tree. This is useful for verifying data against past states. ```solidity function getProofByRoot( SmtLib.Data storage data, uint256 index, uint256 root ) internal view returns (SmtLib.Proof memory) ``` -------------------------------- ### Deploy Contracts to a Network Source: https://github.com/iden3/contracts/blob/master/_autodocs/README.md Deploys the State and UniversalVerifier contracts to a specified network using Hardhat. Replace with the target network identifier. ```bash npx hardhat run scripts/deploy/deployState.ts --network npx hardhat run scripts/deploy/deployUniversalVerifier.ts --network ``` -------------------------------- ### Get Legacy Oracle Signing Address Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/cross-chain-validator.md Retrieves a legacy oracle address that still accepts signatures for backward compatibility. Returns the legacy oracle address, or address(0) if none is set. ```solidity function getLegacyOracleSigningAddress() public view returns (address) ``` -------------------------------- ### getProof Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/libraries.md Generates a merkle proof for a leaf at the current root. ```APIDOC ## getProof ### Description Generates a merkle proof for a leaf at the current root. ### Method internal view ### Signature function getProof( SmtLib.Data storage data, uint256 index ) internal view returns (SmtLib.Proof memory) ### Parameters #### Path Parameters - **data** (Data) - Storage reference - **index** (uint256) - Leaf index ### Return Proof struct for the leaf ### Response Example ```solidity SmtLib.Proof memory proof = SmtLib.getProof(tree, leafIndex); console.log("Root:", proof.root); console.log("Siblings length:", proof.siblings.length); ``` ``` -------------------------------- ### Find Public Input Index by Name Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/validators.md Gets the 0-based index of a public signal within the circuit's public input array using its name. Essential for accessing specific inputs. ```solidity function inputIndexOf(string memory name) external view returns (uint256) ``` ```solidity uint256 userIdIndex = validator.inputIndexOf("userID"); console.log("userID is at index", userIdIndex); ``` -------------------------------- ### Initialize MCPayment Contract Source: https://github.com/iden3/contracts/blob/master/_autodocs/configuration.md Use this function to set the contract owner and the default owner fee percentage upon deployment. The owner percentage must be between 0 and 100. ```solidity function initialize( address owner, uint8 ownerPercentage ) public initializer ``` ```solidity // 5% owner fee mcPayment.initialize(ownerAddress, 5); ``` -------------------------------- ### Configure MCPayment Fees Source: https://github.com/iden3/contracts/blob/master/_autodocs/configuration.md After initialization, the owner can set custom fees for specific issuers or update the global owner fee percentage. Ensure percentages are within the valid range. ```solidity // Set custom fee for specific issuer mcPayment.setIssuerOwnerPercentage(issuerAddress, 10); // 10% for this issuer ``` ```solidity // Update global fee mcPayment.setOwnerPercentage(8); // New default fee ``` -------------------------------- ### Constructor Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/cross-chain-validator.md Initializes the cross-chain validator with oracle configuration. This function sets up the domain name, signature version, and the trusted oracle signer's address. ```APIDOC ## constructor CrossChainProofValidator ### Description Initializes the cross-chain validator with oracle configuration. ### Parameters #### Path Parameters - **domainName** (string) - Required - Domain name for EIP-712 (e.g., "CrossChainProofValidator") - **signatureVersion** (string) - Required - Signature version for EIP-712 (e.g., "1") - **oracleSigningAddress** (address) - Required - Address of trusted oracle signer ### Throws - `OracleSigningAddressShouldNotBeZero()` if address is 0x0 ### Example ```solidity address oracle = 0x1234...; ICrossChainProofValidator ccValidator = new CrossChainProofValidator( "CrossChainProofValidator", "1", oracle ); ``` ``` -------------------------------- ### AuthV3Validator.initialize Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/validators.md Initializes the AuthV3Validator contract, setting up essential addresses for state management and proof verification. ```APIDOC ## initialize AuthV3Validator ### Description Initializes the AuthV3Validator contract, setting up essential addresses for state management and proof verification. ### Method `initialize` ### Parameters #### Path Parameters * **_stateContractAddr** (address) - Yes - Address of the State contract * **_verifierContractAddr** (address) - Yes - Address of the Groth16 verifier contract for authV3 * **owner** (address) - Yes - Address of the contract owner ### Request Example ```solidity authValidator.initialize( stateAddress, groth16VerifierAddress, ownerAddress ); ``` ``` -------------------------------- ### Response Struct Source: https://github.com/iden3/contracts/blob/master/_autodocs/types.md Structure for submitting a proof and optional metadata for a specific request. ```solidity struct Response { uint256 requestId; bytes proof; bytes metadata; } ``` -------------------------------- ### Execute Verification Test Script Source: https://github.com/iden3/contracts/blob/master/scripts/upgrade/verifiers/README.md Use this command to run the maintenance script for testing Universal Verifier functionality after an upgrade. Replace with the target network name. ```bash npx hardhat run scripts/maintenance/checkUniversalVerifierSingleNetwork.ts --network ``` -------------------------------- ### Typical Cross-Chain State Update Flow Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/cross-chain-validator.md Illustrates the typical flow for processing cross-chain state updates. This involves off-chain signing by an oracle, followed by on-chain validation and recording of proofs. ```solidity // 1. Oracle signs state update off-chain // oracle_signer.sign(EIP712(GlobalStateMessage)) // 2. Application receives signed proof from oracle // 3. Application calls State contract with proofs bytes memory proofs = abi.encode( signedGlobalStateProof1, signedGlobalStateProof2, signedIdentityStateProof1 ); state.processCrossChainProofs(proofs); // 4. State contract validates each proof via CrossChainValidator // 5. States are recorded on-chain ``` -------------------------------- ### Deploy Validators Contracts Source: https://github.com/iden3/contracts/blob/master/README.md Deploy the contracts for the validators. Replace with the target network. ```shell npx hardhat run scripts/deploy/deployValidators.ts --network ``` -------------------------------- ### Handle Validator Errors in Solidity Source: https://github.com/iden3/contracts/blob/master/_autodocs/errors.md Demonstrates how to use a try-catch block to handle potential errors during the verification process with a validator. It logs the reason if verification fails. ```solidity try validator.verify(sender, proof, params, metadata) returns ( IRequestValidator.ResponseField[] memory fields ) { // Process verified response } catch Error(string memory reason) { if (bytes(reason).length > 0) { console.log("Verification failed:", reason); } } ``` -------------------------------- ### Publish Contracts to npm Source: https://github.com/iden3/contracts/blob/master/README.md Publish the contracts to the npm registry. Ensure you are in the contracts directory before running the publish command. ```shell cd contracts npm publish ``` -------------------------------- ### Initialize AuthV3Validator Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/validators.md Initializes the AuthV3Validator contract. Requires the addresses of the State contract, the Groth16 verifier for authV3, and the owner. ```solidity function initialize( address _stateContractAddr, address _verifierContractAddr, address owner ) public initializer ``` ```solidity authValidator.initialize( stateAddress, groth16VerifierAddress, ownerAddress ); ``` -------------------------------- ### CredentialAtomicQueryV3 Configuration Structure Source: https://github.com/iden3/contracts/blob/master/_autodocs/configuration.md Defines the structure for configuring CredentialAtomicQueryV3, including schema, claim path key, operator, values, issuer whitelist, circuit IDs, and revocation check settings. ```solidity struct CredentialAtomicQueryV3 { uint256 schema; uint256 claimPathKey; uint256 operator; uint256 slotIndex; uint256[] value; uint256 queryHash; uint256[] allowedIssuers; string[] circuitIds; bool skipClaimRevocationCheck; uint256 groupID; uint256 nullifierSessionID; uint256 proofType; uint256 verifierID; } ``` -------------------------------- ### CredentialAtomicQueryV3Validator initialize Source: https://github.com/iden3/contracts/blob/master/_autodocs/configuration.md Initializes the CredentialAtomicQueryV3Validator contract. ```APIDOC ## initialize() CredentialAtomicQueryV3Validator ### Description Initializes the CredentialAtomicQueryV3Validator contract, configuring the State contract address, the Groth16 verifier for the authV3 circuit, and the contract owner. This validator supports multiple circuit variants configured via request parameters. ### Method `initialize(address _stateContractAddr, address _verifierContractAddr, address owner)` ### Parameters #### Path Parameters - **_stateContractAddr** (address) - Required - State contract address - **_verifierContractAddr** (address) - Required - Groth16 verifier for authV3 circuit - **owner** (address) - Required - Contract owner ### Circuit-Specific Configuration (CredentialAtomicQueryV3) ```solidity struct CredentialAtomicQueryV3 { uint256 schema; // Credential schema uint256 claimPathKey; // Position in claim structure uint256 operator; // Comparison: 0=eq, 1=ne, 2=lt, etc. uint256 slotIndex; // Claim slot (0-7) uint256[] value; // Expected value(s) uint256 queryHash; // Hash of query uint256[] allowedIssuers; // Whitelist of issuer IDs (optional) string[] circuitIds; // Supported circuits ["credentialAtomicQueryV3OnChain-beta.1"] bool skipClaimRevocationCheck; // Skip revocation status check uint256 groupID; // Group ID (0 for ungrouped) uint256 nullifierSessionID; // Session ID for nullifiers uint256 proofType; // 0=simple, 1=linked uint256 verifierID; // Verifier version (must match) } ``` ``` -------------------------------- ### Initialize IdentityTreeStore Contract Source: https://github.com/iden3/contracts/blob/master/_autodocs/configuration.md Initializes the IdentityTreeStore contract with the address of the State contract for identity validation. ```solidity function initialize(address state) public initializer ``` ```solidity address stateAddr = 0x3C9acB2205Aa72A05F6D77d708b5Cf85FCa3a896; identityTreeStore.initialize(stateAddr); ``` -------------------------------- ### Request Struct Source: https://github.com/iden3/contracts/blob/master/_autodocs/types.md Defines a complete request for proof verification, including metadata, validator details, and creator information. ```solidity struct Request { uint256 requestId; string metadata; IRequestValidator validator; bytes params; address creator; } ``` -------------------------------- ### getProofByRoot Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/libraries.md Generates a merkle proof for a leaf at a specific historical root. ```APIDOC ## getProofByRoot ### Description Generates a merkle proof for a leaf at a specific historical root. ### Method internal view ### Signature function getProofByRoot( SmtLib.Data storage data, uint256 index, uint256 root ) internal view returns (SmtLib.Proof memory) ### Parameters #### Path Parameters - **data** (Data) - Storage reference - **index** (uint256) - Leaf index - **root** (uint256) - Specific root to generate proof for ### Return Proof struct for that root ``` -------------------------------- ### Initialize AuthV2Validator Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/validators.md Initializes the AuthV2Validator contract, similar to AuthV3Validator but using the authV2 verifier. ```solidity function initialize( address _stateContractAddr, address _verifierContractAddr, address owner ) public initializer ``` -------------------------------- ### Validating Configuration in Solidity Source: https://github.com/iden3/contracts/blob/master/_autodocs/errors.md This Solidity snippet demonstrates essential configuration validation checks. It ensures a validator is whitelisted and that a request ID exists before proceeding. ```solidity // Ensure validator is whitelisted require(verifier.isValidatorWhitelisted(addr), "Validator not whitelisted"); // Ensure request exists require(verifier.requestIdExists(requestId), "Request not found"); // Ensure auth method available // (handled internally but check logs for warnings) ``` -------------------------------- ### Initialize CrossChainProofValidator Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/cross-chain-validator.md Initializes the cross-chain validator with oracle configuration. Requires domain name, signature version, and the oracle's signing address. Throws if the oracle address is zero. ```solidity constructor( string memory domainName, string memory signatureVersion, address oracleSigningAddress ) ``` ```solidity address oracle = 0x1234...; ICrossChainProofValidator ccValidator = new CrossChainProofValidator( "CrossChainProofValidator", "1", oracle ); ``` -------------------------------- ### Execute Universal Verifier Upgrade Script Source: https://github.com/iden3/contracts/blob/master/scripts/upgrade/verifiers/README.md Run this command to execute the upgrade script for the Universal Verifier contract on the Amoy network. Ensure your hardhat.config.ts is configured for the target network. ```bash npx hardhat run scripts/upgrade/verifiers/universal-verifier-upgrade.ts --network amoy ``` -------------------------------- ### Retrieve Multi-Request Proof Statuses Source: https://github.com/iden3/contracts/blob/master/_autodocs/api-reference/universal-verifier.md Fetches the verification status for all proofs associated with a specific multi-request and user address. Returns an array of `RequestProofStatus` structs. ```solidity function getMultiRequestProofsStatus( uint256 multiRequestId, address userAddress ) external view returns (RequestProofStatus[] memory) ``` -------------------------------- ### GistRootInfo Structure Source: https://github.com/iden3/contracts/blob/master/_autodocs/types.md Information about a GIST (Global Identity State Tree) root with history. Used by IState.getGISTRootInfo(). ```solidity struct GistRootInfo { uint256 root; uint256 replacedByRoot; uint256 createdAtTimestamp; uint256 replacedAtTimestamp; uint256 createdAtBlock; uint256 replacedAtBlock; } ``` -------------------------------- ### Read State and Send Transaction with Ethers.js Source: https://github.com/iden3/contracts/blob/master/_autodocs/README.md This snippet demonstrates reading state information and sending a transaction using Ethers.js. It includes connecting to a provider, interacting with a contract, and waiting for transaction confirmation. ```typescript const provider = new ethers.providers.JsonRpcProvider(rpcUrl); const contract = new ethers.Contract(address, ABI, provider); // Read state const stateInfo = await contract.getStateInfoById(identityId); // Send transaction const signer = provider.getSigner(); const contractWithSigner = contract.connect(signer); const tx = await contractWithSigner.submitResponse( authResponse, responses, crossChainProofs ); await tx.wait(); ``` -------------------------------- ### Common Hardhat Commands Source: https://github.com/iden3/contracts/blob/master/README.md Execute various common Hardhat commands for contract management, including listing accounts, compiling, cleaning, running a local node, and accessing help. ```shell npx hardhat accounts ``` ```shell npx hardhat compile ``` ```shell npx hardhat clean ``` ```shell npx hardhat node ``` ```shell npx hardhat help ``` -------------------------------- ### RequestInfo Struct Source: https://github.com/iden3/contracts/blob/master/_autodocs/types.md Represents request information as returned from Verifier queries, including all details of a request. ```solidity struct RequestInfo { uint256 requestId; string metadata; IRequestValidator validator; bytes params; address creator; } ``` -------------------------------- ### Deploy Create2 Address Anchor Source: https://github.com/iden3/contracts/blob/master/README.md Deploy the create2AnchorAddress contract, which is used for unified addresses across networks. Replace with the target network. ```shell npx hardhat run scripts/deploy/deployCreate2AddressAnchor.ts --network ```