Showing preview only (923K chars total). Download the full file or copy to clipboard to get everything.
Repository: sismo-core/sismo-badges
Branch: main
Commit: 09206e396ca2
Files: 150
Total size: 870.5 KB
Directory structure:
gitextract_16i2pstn/
├── .github/
│ └── workflows/
│ ├── publish.yaml
│ └── push.yaml
├── .gitignore
├── .mocharc.json
├── .prettierrc
├── Dockerfile
├── LICENSE
├── README.md
├── contracts/
│ ├── attesters/
│ │ ├── hydra-s1/
│ │ │ ├── HydraS1AccountboundAttester.sol
│ │ │ ├── HydraS1SimpleAttester.sol
│ │ │ ├── base/
│ │ │ │ ├── HydraS1Base.sol
│ │ │ │ └── IHydraS1Base.sol
│ │ │ ├── interfaces/
│ │ │ │ ├── IHydraS1AccountboundAttester.sol
│ │ │ │ └── IHydraS1SimpleAttester.sol
│ │ │ └── libs/
│ │ │ ├── HydraS1AccountboundLib.sol
│ │ │ └── HydraS1Lib.sol
│ │ └── pythia-1/
│ │ ├── Pythia1SimpleAttester.sol
│ │ ├── base/
│ │ │ ├── IPythia1Base.sol
│ │ │ └── Pythia1Base.sol
│ │ ├── interfaces/
│ │ │ └── IPythia1SimpleAttester.sol
│ │ └── libs/
│ │ └── Pythia1Lib.sol
│ ├── core/
│ │ ├── AttestationsRegistry.sol
│ │ ├── Attester.sol
│ │ ├── Badges.sol
│ │ ├── Front.sol
│ │ ├── interfaces/
│ │ │ ├── IAttestationsRegistry.sol
│ │ │ ├── IAttestationsRegistryConfigLogic.sol
│ │ │ ├── IAttester.sol
│ │ │ ├── IBadges.sol
│ │ │ └── IFront.sol
│ │ ├── libs/
│ │ │ ├── Structs.sol
│ │ │ ├── attestations-registry/
│ │ │ │ ├── AttestationsRegistryConfigLogic.sol
│ │ │ │ ├── AttestationsRegistryState.sol
│ │ │ │ ├── InitializableLogic.sol
│ │ │ │ ├── OwnableLogic.sol
│ │ │ │ └── PausableLogic.sol
│ │ │ └── utils/
│ │ │ ├── Address.sol
│ │ │ ├── Bitmap256Bit.sol
│ │ │ ├── Context.sol
│ │ │ └── RangeLib.sol
│ │ └── utils/
│ │ ├── AddressesProvider.sol
│ │ └── interfaces/
│ │ └── IAddressesProvider.sol
│ ├── libs/
│ │ ├── SismoLib.sol
│ │ └── using-sismo/
│ │ └── UsingSismo.sol
│ ├── periphery/
│ │ └── utils/
│ │ ├── AvailableRootsRegistry.sol
│ │ ├── CommitmentMapperRegistry.sol
│ │ ├── FrontendLib.sol
│ │ ├── TransparentUpgradeableProxy.sol
│ │ └── interfaces/
│ │ ├── IAvailableRootsRegistry.sol
│ │ └── ICommitmentMapperRegistry.sol
│ ├── tests/
│ │ ├── MockHydraS1SimpleAttester.sol
│ │ └── mocks/
│ │ ├── MockAttestationsRegistry.sol
│ │ ├── MockAttester.sol
│ │ └── mockContractUsingSismoLib.sol
│ └── zkdrop/
│ └── ZKBadgeboundERC721.sol
├── hardhat.config.ts
├── helper-hardhat-config.ts
├── package.json
├── scripts/
│ └── wait-for-local-chain.sh
├── tasks/
│ ├── addresses-provider/
│ │ └── set-batch.task.ts
│ ├── available-roots-registry/
│ │ ├── register-for-attester.task.ts
│ │ └── unregister-for-attester.task.ts
│ ├── deploy-tasks/
│ │ ├── batch/
│ │ │ └── deploy-core.task.ts
│ │ ├── deployments-config.ts
│ │ ├── full/
│ │ │ ├── 0-deploy-core-and-hydra-s1-simple-and-accountbound-and-pythia1.task.ts
│ │ │ ├── 1-deploy-pythia-1-simple.task.ts
│ │ │ ├── 2-upgrade-proxies.task.ts
│ │ │ ├── 2-upgrade-proxies.test-fork.ts
│ │ │ ├── 3-new-hydra-s1-verifier-and-upgrade-hydra-s1-simple-proxy.task.ts
│ │ │ ├── 3-new-hydra-s1-verifier-and-upgrade-hydra-s1-simple-proxy.test-fork.ts
│ │ │ ├── 4-upgrade-attestations-registry-proxy-and-badges-proxy.task.ts
│ │ │ ├── 4-upgrade-attestations-registry-proxy-and-badges-proxy.test-fork.ts
│ │ │ ├── 5-upgrade-proxies-with-reinitializer/
│ │ │ │ ├── 5-upgrade-proxies-with-reinitializer-available-roots-registry.test-fork.ts
│ │ │ │ ├── 5-upgrade-proxies-with-reinitializer-commitment-mapper-registry.test-fork.ts
│ │ │ │ └── 5-upgrade-proxies-with-reinitializer-pythia1.test-fork.ts
│ │ │ ├── 5-upgrade-proxies-with-reinitializer.task.ts
│ │ │ ├── 6-7-8-fork-test/
│ │ │ │ └── 6-7-8.test-fork.ts
│ │ │ ├── 6-deploy-sismo-addresses-provider.task.ts
│ │ │ ├── 7-upgrade-hydra-s1-accountbound-and-pythia-1-proxies.task.ts
│ │ │ ├── 9-fork-test/
│ │ │ │ └── 9-upgrade-addresses-provider-on-testnets.test-fork.ts
│ │ │ ├── 9-upgrade-addresses-provider-on-testnets.task.ts
│ │ │ ├── local/
│ │ │ │ └── deploy-full-local.task.ts
│ │ │ └── staging/
│ │ │ └── deploy-sismo-addresses-provider-staging.task.ts
│ │ ├── tests/
│ │ │ ├── deploy-mock-attestations-registry.task.ts
│ │ │ ├── deploy-mock-attester-and-core.task.ts
│ │ │ ├── deploy-mock-attester.task.ts
│ │ │ ├── deploy-mock-contract-using-sismo-lib.task.ts
│ │ │ └── deploy-zk-badgebound-erc721.task.ts
│ │ ├── unit/
│ │ │ ├── attesters/
│ │ │ │ ├── hydra-s1/
│ │ │ │ │ ├── deploy-hydra-s1-accountbound-attester.task.ts
│ │ │ │ │ ├── deploy-hydra-s1-simple-attester.task.ts
│ │ │ │ │ └── deploy-hydra-s1-verifier.task.ts
│ │ │ │ └── pythia-1/
│ │ │ │ ├── deploy-pythia-1-simple-attester.task.ts
│ │ │ │ └── deploy-pythia-1-verifier.task.ts
│ │ │ ├── core/
│ │ │ │ ├── deploy-attestations-registry.task.ts
│ │ │ │ ├── deploy-badges.task.ts
│ │ │ │ ├── deploy-front.task.ts
│ │ │ │ └── deploy-sismo-addresses-provider.task.ts
│ │ │ └── periphery/
│ │ │ ├── deploy-available-roots-registry.task.ts
│ │ │ ├── deploy-commitment-mapper-registry.task.ts
│ │ │ └── deploy-frontend-lib.task.ts
│ │ ├── utils/
│ │ │ ├── deployment.ts
│ │ │ ├── deployments-config-types.ts
│ │ │ └── index.ts
│ │ └── zkdrop/
│ │ ├── deploy-mergooor-pass.task.ts
│ │ ├── deploy-ziki-pass-staging.task.ts
│ │ └── deploy-ziki-pass-testnet.task.ts
│ ├── helpers/
│ │ ├── authorizations/
│ │ │ ├── access-control-grant-role.task.ts
│ │ │ ├── access-control-revoke-role.task.ts
│ │ │ ├── attestations-registry-authorize-range.task.ts
│ │ │ ├── attestations-registry-transfer-ownership.task.ts
│ │ │ ├── change-proxy-admin.task.ts
│ │ │ └── ownable-transfer-ownership.task.ts
│ │ ├── forge-create2-transaction.task.ts
│ │ ├── print-accounts.task.ts
│ │ ├── print-storage-layout.task.ts
│ │ ├── proxy/
│ │ │ └── upgrade-proxy.task.ts
│ │ └── verify-contract.task.ts
│ └── utils/
│ ├── common-options.ts
│ ├── confirm.ts
│ ├── index.ts
│ ├── relayer.ts
│ └── types.ts
├── test/
│ ├── e2e/
│ │ └── e2e.test.ts
│ ├── unit/
│ │ ├── attesters/
│ │ │ ├── hydra-s1/
│ │ │ │ ├── hydra-s1-accountbound-attester.test.ts
│ │ │ │ └── hydra-s1-simple-attester.test.ts
│ │ │ └── pythia-1/
│ │ │ └── pythia-1-simple-attester.test.ts
│ │ ├── core/
│ │ │ ├── attestations-registry/
│ │ │ │ ├── attestations-registry-config-logic.test.ts
│ │ │ │ └── attestations-registry.test.ts
│ │ │ ├── badges.test.ts
│ │ │ ├── front.test.ts
│ │ │ └── utils/
│ │ │ └── sismo-addresses-provider.test.ts
│ │ ├── libs/
│ │ │ └── using-sismo/
│ │ │ └── using-sismo.test.ts
│ │ ├── periphery/
│ │ │ └── utils/
│ │ │ ├── available-roots-registry.test.ts
│ │ │ ├── commitment-mapper-registry.test.ts
│ │ │ └── frontend-lib.test.ts
│ │ └── zkdrop/
│ │ └── zk-badgebound-erc721.test.ts
│ └── utils/
│ ├── attestation-logic.ts
│ ├── evm.ts
│ ├── expectEvent.ts
│ ├── hydra-s1-accountbound.ts
│ ├── hydra-s1.ts
│ ├── index.ts
│ ├── pythia-1.ts
│ ├── setup.ts
│ └── test-helpers.ts
├── tsconfig.json
└── utils/
├── constants.ts
├── index.ts
├── proxy.ts
└── singletonFactory.ts
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/workflows/publish.yaml
================================================
name: Publish Docker image
on:
push:
tags:
- 'v*'
jobs:
push_to_registry:
name: Push Docker image to Docker Hub
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v3
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Log in to Docker Hub
uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
with:
images: sismo/sismo-protocol
- name: Build and push Docker image
uses: docker/build-push-action@v3
with:
context: .
push: true
platforms: linux/amd64,linux/arm64/v8
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
================================================
FILE: .github/workflows/push.yaml
================================================
name: On Push checks
on:
push:
jobs:
test:
runs-on: ubuntu-latest
name: Compile, test and test deploy
steps:
- uses: actions/checkout@v2
- name: Setup node
uses: actions/setup-node@v2
with:
node-version: '16.x'
cache: yarn
- run: yarn install --frozen-lockfile
- run: yarn compile
- name: test
run: yarn test
- name: deploy local script
run: npx concurrently --kill-others -s command-1 "npx hardhat node" "sleep 2 & npx yarn deploy:local"
================================================
FILE: .gitignore
================================================
node_modules
deployments
cache
artifacts
typechain-types
types/**
.vscode
deployments/local
save
.env
================================================
FILE: .mocharc.json
================================================
{
"require": "ts-node/register/files",
"timeout": 20000
}
================================================
FILE: .prettierrc
================================================
{
"printWidth": 100,
"trailingComma": "es5",
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"overrides": [
{
"files": "*.sol",
"options": {
"semi": true,
"printWidth": 100
}
}
]
}
================================================
FILE: Dockerfile
================================================
FROM node:16 AS build
WORKDIR /usr/src/build
# Install dependencies
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile
COPY . .
RUN yarn compile
FROM node:16-slim AS run
RUN apt-get -y update && apt-get -y install netcat
WORKDIR /usr/src/app
COPY --from=build /usr/src/build/ .
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2022 Sismo
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
<br />
<div align="center">
<img src="docs/top.png" alt="Logo" width="100" height="100" style="borderRadius: 20px">
<h3 align="center">
Sismo Protocol Contracts
</h3>
<p align="center">
Made by <a href="https://www.sismo.io/" target="_blank">Sismo</a>
</p>
<p align="center">
<a href="https://discord.gg/sismo" target="_blank">
<img src="https://img.shields.io/badge/Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white"/>
</a>
<a href="https://twitter.com/sismo_eth" target="_blank">
<img src="https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white"/>
</a>
</p>
<a href="https://www.sismo.io/" target="_blank">
</a>
</div>
<br/>
This repository contains the smart contracts of the Sismo Protocol.
There are three core contracts:
- `core/AttestationsRegistry.sol`: The registry stores all attestations. It is owned by the governance that authorizes/unauthorize issuers to record in it
- `core/Attester.sol` The standard abstract contract must be inherited by attesters. Attesters are issuers of attestations. They verify user requests and build attestations that will be recorded in the registry
- `core/Badges.sol` Reads the registry. Stateless Non Transferable Token view of attestations (ERC1155)
It also contains implementations of attester in `attesters/`:
- `HydraS1SimpleAttester.sol`: ZK Attester using the [Hydra S1 Proving Scheme](https://hydra-s1.docs.sismo.io) and the notion of nullifiers. Users must provide a ZK Proof along with their request to generate attestations
- `HydraS1AccountboundAttester.sol`: Accountbound version of the Simple Hydra S1 Simple Attester. (Users can update at will where the attestation is stored)
<br/><br/>
## Sismo protocol
A complete overview of the protocol is available in our [documentation](https://protocol.docs.sismo.io)
## Deployed contracts
Deployed contracts can be found [here](https://docs.sismo.io/sismo-docs/deployed-contract-addresses)
## Usage
### Installation
```
yarn
```
### Compile contracts
Compile contracts using hardhat
```
yarn compile
```
### Test
Launch all tests
```
yarn test
```
### Print storage layout
```
yarn storage-layout
```
### Deploy on local chain
Terminal tab 1
```
yarn chain
```
Terminal tab 2
```
yarn deploy:local
```
## Create a new Attester
To develop a new attester, you must inherit the `core/Attester.sol` abstract contract and implement the following functions:
- `_verifyRequest(request, proofData)`: You must implement the user request verification against the proof provided by the user
- `buildAttestations(request, proofData)`: You must build the attestations that will be recorded from a verified user request
Other optional hook functions that can be implemented:
- `_beforeRecordAttestations(request, proofData)`
- `_afterRecordAttestations(request, proofData)`
The `/attesters/hydra-s1/HydraS1SimpleAttester.sol` is a good example of an attester implementing those functions.
A [guide](https://attesters.docs.sismo.io) is offered in our documentation.
Feel free open a PR with your new attester in `/attester`!
## License
Distributed under the MIT License.
## Contribute
Please, feel free to open issues, PRs or simply provide feedback!
## Contact
Prefer [Discord](https://discord.gg/sismo) or [Twitter](https://twitter.com/sismo_eth)
<br/>
<img src="https://static.sismo.io/readme/bottom-main.png" alt="bottom" width="100%" >
================================================
FILE: contracts/attesters/hydra-s1/HydraS1AccountboundAttester.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
pragma experimental ABIEncoderV2;
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {IHydraS1AccountboundAttester} from './interfaces/IHydraS1AccountboundAttester.sol';
// Core protocol Protocol imports
import {Request, Attestation, Claim} from '../../core/libs/Structs.sol';
// Imports related to Hydra-S1
import {HydraS1SimpleAttester, IAttester, HydraS1Lib, HydraS1ProofData, HydraS1Claim} from './HydraS1SimpleAttester.sol';
/**
* @title Hydra-S1 Accountbound Attester
* @author Sismo
* @notice This attester is part of the family of the Hydra-S1 Attesters.
* Hydra-S1 attesters enable users to prove they have an account in a group in a privacy preserving way.
* The Hydra-S1 Simple Attester contract is inherited and holds the complex Hydra S1 verification logic.
* Request verification alongside proof verification is already implemented in the inherited HydraS1SimpleAttester, along with the buildAttestations logic.
* However, we override the buildAttestations function to encode the nullifier and its burn count in the user attestation.
* The _beforeRecordAttestations is also overriden to fit the Accountbound logic.
* We invite readers to refer to:
* - https://hydra-s1.docs.sismo.io for a full guide through the Hydra-S1 ZK Attestations
* - https://hydra-s1-circuits.docs.sismo.io for circuits, prover and verifiers of Hydra-S1
* This specific attester has the following characteristics:
* - Zero Knowledge
* One cannot deduct from an attestation what source account was used to generate the underlying proof
* - Non Strict (scores)
* If a user can generate an attestation of max value 100, they can also generate any attestation with value < 100.
* This attester generate attestations of scores
* - Nullified
* Each source account gets one nullifier per claim (i.e only one attestation per source account per claim)
* While semaphore/ tornado cash are using the following notations: nullifierHash = hash(IdNullifier, externalNullifier)
* We prefered to use the naming 'nullifier' instead of 'nullifierHash' in our contracts and documentation.
* We also renamed 'IdNullifier' in 'sourceSecret' (the secret tied to a source account) and we kept the 'externalNullifier' notation.
* Finally, here is our notations at Sismo: nullifier = hash(sourceSecret, externalNullifier)
* - Accountbound (opt-in, with cooldown period)
* The owner of this attester can set a cooldown duration for a specific group, activating the accountbound feature for this group.
* Users can update their attestation's destination by providing a new Hydra-S1 ZK proof
* It means the attestation is bound to the source account, stored on an updatable destination account.
* When deleting/ sending to a new destination, the nullifier will enter a cooldown period, so it remains occasional.
* A group that has its cooldown duration set to 0 means it has been configured to not feature accountbound attestations, attestations can not be transferred
* One can however know that the former and the new destinations were created using the same nullifier, thus creating a link between those two destinations.
* - Renewable
* A nullifier can actually be reused as long as the destination of the attestation remains the same
* It enables users to renew or update their attestations
**/
contract HydraS1AccountboundAttester is
IHydraS1AccountboundAttester,
HydraS1SimpleAttester,
Ownable
{
using HydraS1Lib for HydraS1ProofData;
using HydraS1Lib for bytes;
using HydraS1Lib for Request;
uint8 public constant IMPLEMENTATION_VERSION = 5;
/*******************************************************
Storage layout:
20 slots between HydraS1SimpleAttester and HydraS1AccountboundAttester
1 currently used by Ownable
19 place holders
2O for config
1 currently used
19 place holders
20 for logic
2 currently used
18 place holders
*******************************************************/
// keeping some space for future config logics
uint256[19] private _placeHolderBeforeHydraS1Accountbound;
// cooldown durations for each groupIndex
mapping(uint256 => uint32) internal _cooldownDurations;
// keeping some space for future config logics
uint256[19] private _placeHoldersHydraS1AccountboundConfig;
mapping(uint256 => uint32) internal _nullifiersCooldownStart;
mapping(uint256 => uint16) internal _nullifiersBurnCount;
// keeping some space for future config logics
uint256[18] private _placeHoldersHydraS1AccountboundLogic;
/*******************************************************
INITIALIZATION FUNCTIONS
*******************************************************/
/**
* @dev Constructor. Initializes the contract
* @param attestationsRegistryAddress Attestations Registry contract on which the attester will write attestations
* @param hydraS1VerifierAddress ZK Snark Hydra-S1 Verifier contract
* @param availableRootsRegistryAddress Registry storing the available groups for this attester (e.g roots of registry merkle trees)
* @param commitmentMapperAddress commitment mapper's public key registry
* @param collectionIdFirst Id of the first attestation collection in which the attester is supposed to record
* @param collectionIdLast Id of the last attestation collection in which the attester is supposed to record
* @param owner Address of attester's owner
*/
constructor(
address attestationsRegistryAddress,
address hydraS1VerifierAddress,
address availableRootsRegistryAddress,
address commitmentMapperAddress,
uint256 collectionIdFirst,
uint256 collectionIdLast,
address owner
)
HydraS1SimpleAttester(
attestationsRegistryAddress,
hydraS1VerifierAddress,
availableRootsRegistryAddress,
commitmentMapperAddress,
collectionIdFirst,
collectionIdLast
)
{
initialize(owner);
}
/**
* @dev Initialize function, to be called by the proxy delegating calls to this implementation
* @param ownerAddress Owner of the contract, has the right to authorize/unauthorize attestations issuers
* @notice The reinitializer modifier is needed to configure modules that are added through upgrades and that require initialization.
*/
function initialize(address ownerAddress) public reinitializer(IMPLEMENTATION_VERSION) {
// if proxy did not setup owner yet or if called by constructor (for implem setup)
if (owner() == address(0) || address(this).code.length == 0) {
_transferOwnership(ownerAddress);
}
}
/*******************************************************
MANDATORY FUNCTIONS TO OVERRIDE FROM ATTESTER.SOL
*******************************************************/
/**
* @dev Returns the actual attestations constructed from the user request
* @param request users request. Claim of having an account part of a group of accounts
* @param proofData snark public input as well as snark proof
*/
function buildAttestations(
Request calldata request,
bytes calldata proofData
) public view virtual override(IAttester, HydraS1SimpleAttester) returns (Attestation[] memory) {
Attestation[] memory attestations = super.buildAttestations(request, proofData);
uint256 nullifier = proofData._getNullifier();
attestations[0].extraData = abi.encode(
attestations[0].extraData, // nullifier, from HydraS1 Simple
_getNextBurnCount(nullifier, attestations[0].owner) // BurnCount
);
return (attestations);
}
/*******************************************************
OPTIONAL HOOK VIRTUAL FUNCTIONS FROM ATTESTER.SOL
*******************************************************/
/**
* @dev Hook run before recording the attestation.
* Throws if nullifier already used, not a renewal, and nullifier on cooldown.
* @param request users request. Claim of having an account part of a group of accounts
* @param proofData provided to back the request. snark input and snark proof
*/
function _beforeRecordAttestations(
Request calldata request,
bytes calldata proofData
) internal virtual override {
uint256 nullifier = proofData._getNullifier();
address previousNullifierDestination = _getDestinationOfNullifier(nullifier);
HydraS1Claim memory claim = request._claim();
// check if the nullifier has already been used previously, if so it may be on cooldown
if (
previousNullifierDestination != address(0) &&
previousNullifierDestination != claim.destination
) {
uint32 cooldownDuration = _getCooldownDurationForGroupIndex(claim.groupProperties.groupIndex);
if (cooldownDuration == 0) {
revert CooldownDurationNotSetForGroupIndex(claim.groupProperties.groupIndex);
}
if (_isOnCooldown(nullifier, cooldownDuration)) {
uint16 burnCount = _getNullifierBurnCount(nullifier);
revert NullifierOnCooldown(
nullifier,
previousNullifierDestination,
burnCount,
cooldownDuration
);
}
// Delete the old Attestation linked to the nullifier before recording the new one (accountbound feature)
_deletePreviousAttestation(claim, previousNullifierDestination);
_setNullifierOnCooldownAndIncrementBurnCount(nullifier);
}
_setDestinationForNullifier(nullifier, request.destination);
}
/*******************************************************
LOGIC FUNCTIONS RELATED TO ACCOUNTBOUND FEATURE
*******************************************************/
/**
* @dev Getter, returns the burnCount of a nullifier
* @param nullifier nullifier used
**/
function getNullifierBurnCount(uint256 nullifier) external view returns (uint16) {
return _getNullifierBurnCount(nullifier);
}
/**
* @dev Getter, returns the cooldown start of a nullifier
* @param nullifier nullifier used
**/
function getNullifierCooldownStart(uint256 nullifier) external view returns (uint32) {
return _getNullifierCooldownStart(nullifier);
}
/**
* @dev returns the nullifier for a given extraData
* @param extraData bytes where the nullifier is encoded
*/
function getNullifierFromExtraData(
bytes memory extraData
) external pure override(HydraS1SimpleAttester, IHydraS1AccountboundAttester) returns (uint256) {
(bytes memory nullifierBytes, ) = abi.decode(extraData, (bytes, uint16));
uint256 nullifier = abi.decode(nullifierBytes, (uint256));
return nullifier;
}
/**
* @dev Returns the burn count for a given extraData
* @param extraData bytes where the burnCount is encoded
*/
function getBurnCountFromExtraData(bytes memory extraData) external pure returns (uint16) {
(, uint16 burnCount) = abi.decode(extraData, (uint256, uint16));
return burnCount;
}
/**
* @dev Checks if a nullifier is on cooldown
* @param nullifier user nullifier
* @param cooldownDuration waiting time before the user can change its badge destination
*/
function _isOnCooldown(uint256 nullifier, uint32 cooldownDuration) internal view returns (bool) {
return _getNullifierCooldownStart(nullifier) + cooldownDuration > block.timestamp;
}
/**
* @dev Delete the previous attestation created with this nullifier
* @param claim user claim
* @param previousNullifierDestination previous destination chosen for this user nullifier
*/
function _deletePreviousAttestation(
HydraS1Claim memory claim,
address previousNullifierDestination
) internal {
address[] memory attestationOwners = new address[](1);
uint256[] memory attestationCollectionIds = new uint256[](1);
attestationOwners[0] = previousNullifierDestination;
attestationCollectionIds[0] = AUTHORIZED_COLLECTION_ID_FIRST + claim.groupProperties.groupIndex;
ATTESTATIONS_REGISTRY.deleteAttestations(attestationOwners, attestationCollectionIds);
}
function _setNullifierOnCooldownAndIncrementBurnCount(uint256 nullifier) internal {
_nullifiersCooldownStart[nullifier] = uint32(block.timestamp);
_nullifiersBurnCount[nullifier] += 1;
emit NullifierSetOnCooldown(nullifier, _nullifiersBurnCount[nullifier]);
}
function _getNullifierCooldownStart(uint256 nullifier) internal view returns (uint32) {
return _nullifiersCooldownStart[nullifier];
}
function _getNullifierBurnCount(uint256 nullifier) internal view returns (uint16) {
return _nullifiersBurnCount[nullifier];
}
/**
* @dev returns burn count or burn count + 1 if new burn will happen
* @param nullifier user nullifier
* @param claimDestination destination referenced in the user claim
*/
function _getNextBurnCount(
uint256 nullifier,
address claimDestination
) public view virtual returns (uint16) {
address previousNullifierDestination = _getDestinationOfNullifier(nullifier);
uint16 burnCount = _getNullifierBurnCount(nullifier);
// If the attestation is minted on a new destination address
// the burnCount that will be encoded in the extraData of the Attestation should be incremented
if (
previousNullifierDestination != address(0) && previousNullifierDestination != claimDestination
) {
burnCount += 1;
}
return burnCount;
}
/*******************************************************
GROUP CONFIGURATION LOGIC
*******************************************************/
/**
* @dev Setter, sets the cooldown duration of a groupIndex
* @notice set to 0 to deactivate the accountbound feature for this group
* @param groupIndex internal collection id
* @param cooldownDuration cooldown duration we want to set for the groupIndex
**/
function setCooldownDurationForGroupIndex(
uint256 groupIndex,
uint32 cooldownDuration
) external onlyOwner {
_cooldownDurations[groupIndex] = cooldownDuration;
emit CooldownDurationSetForGroupIndex(groupIndex, cooldownDuration);
}
/**
* @dev Getter, get the cooldown duration of a groupIndex
* @notice returns 0 when the accountbound feature is deactivated for this group
* @param groupIndex internal collection id
**/
function getCooldownDurationForGroupIndex(uint256 groupIndex) external view returns (uint32) {
return _getCooldownDurationForGroupIndex(groupIndex);
}
// = 0 means that the accountbound feature is deactivated for this group
function _getCooldownDurationForGroupIndex(uint256 groupIndex) internal view returns (uint32) {
return _cooldownDurations[groupIndex];
}
}
================================================
FILE: contracts/attesters/hydra-s1/HydraS1SimpleAttester.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
pragma experimental ABIEncoderV2;
import {IHydraS1SimpleAttester} from './interfaces/IHydraS1SimpleAttester.sol';
import {IHydraS1Base} from './base/IHydraS1Base.sol';
// Core protocol Protocol imports
import {Request, Attestation, Claim} from './../../core/libs/Structs.sol';
import {Attester, IAttester, IAttestationsRegistry} from './../../core/Attester.sol';
// Imports related to HydraS1 Proving Scheme
import {HydraS1Base, HydraS1Lib, HydraS1ProofData, HydraS1ProofInput, HydraS1Claim} from './base/HydraS1Base.sol';
/**
* @title Hydra-S1 Simple Attester
* @author Sismo
* @notice This attester is part of the family of the Hydra-S1 Attesters.
* Hydra-S1 attesters enable users to prove they have an account in a group in a privacy preserving way.
* The Hydra-S1 Base abstract contract is inherited and holds the complex Hydra S1 verification logic.
* We invite readers to refer to:
* - https://hydra-s1.docs.sismo.io for a full guide through the Hydra-S1 ZK Attestations
* - https://hydra-s1-circuits.docs.sismo.io for circuits, prover and verifiers of Hydra-S1
* This specific attester has the following characteristics:
* - Zero Knowledge
* One cannot deduct from an attestation what source account was used to generate the underlying proof
* - Non Strict (scores)
* If a user can generate an attestation of max value 100, they can also generate any attestation with value < 100.
* This attester generate attestations of scores
* - Nullified
* Each source account gets one nullifier per claim (i.e only one attestation per source account per claim)
* For people used to semaphore/ tornado cash people:
* nullifier = hash(sourceSecret, externalNullifier) <=> nullifierHash = hash(IdNullifier, externalNullifier)
* - Renewable
* A nullifier can actually be reused as long as the destination of the attestation remains the same
* It enables users to renew their attestations
**/
contract HydraS1SimpleAttester is IHydraS1SimpleAttester, HydraS1Base {
using HydraS1Lib for HydraS1ProofData;
using HydraS1Lib for bytes;
using HydraS1Lib for Request;
// The deployed contract will need to be authorized to write into the Attestation registry
// It should get write access on attestation collections from AUTHORIZED_COLLECTION_ID_FIRST to AUTHORIZED_COLLECTION_ID_LAST.
uint256 public immutable AUTHORIZED_COLLECTION_ID_FIRST;
uint256 public immutable AUTHORIZED_COLLECTION_ID_LAST;
/*******************************************************
Storage layout:
20 slots for HydraS1
1 slot used
19 place holders
*******************************************************/
mapping(uint256 => address) internal _nullifiersDestinations;
// keeping some space for future
uint256[19] private _placeHoldersHydraS1Simple;
/*******************************************************
INITIALIZATION FUNCTIONS
*******************************************************/
/**
* @dev Constructor. Initializes the contract
* @param attestationsRegistryAddress Attestations Registry contract on which the attester will write attestations
* @param hydraS1VerifierAddress ZK Snark Hydra-S1 Verifier contract
* @param availableRootsRegistryAddress Registry storing the available groups for this attester (e.g roots of registry merkle trees)
* @param commitmentMapperAddress commitment mapper's public key registry
* @param collectionIdFirst Id of the first collection in which the attester is supposed to record
* @param collectionIdLast Id of the last collection in which the attester is supposed to record
*/
constructor(
address attestationsRegistryAddress,
address hydraS1VerifierAddress,
address availableRootsRegistryAddress,
address commitmentMapperAddress,
uint256 collectionIdFirst,
uint256 collectionIdLast
)
Attester(attestationsRegistryAddress)
HydraS1Base(hydraS1VerifierAddress, availableRootsRegistryAddress, commitmentMapperAddress)
{
AUTHORIZED_COLLECTION_ID_FIRST = collectionIdFirst;
AUTHORIZED_COLLECTION_ID_LAST = collectionIdLast;
}
/*******************************************************
MANDATORY FUNCTIONS TO OVERRIDE FROM ATTESTER.SOL
*******************************************************/
/**
* @dev Throws if user request is invalid when verified against
* Look into HydraS1Base for more details
* @param request users request. Claim of having an account part of a group of accounts
* @param proofData provided to back the request. snark input and snark proof
*/
function _verifyRequest(
Request calldata request,
bytes calldata proofData
) internal virtual override {
HydraS1ProofData memory snarkProof = abi.decode(proofData, (HydraS1ProofData));
HydraS1ProofInput memory snarkInput = snarkProof._input();
HydraS1Claim memory claim = request._claim();
// verifies that the proof corresponds to the claim
_validateInput(claim, snarkInput);
// verifies the proof validity
_verifyProof(snarkProof);
}
/**
* @dev Returns attestations that will be recorded, constructed from the user request
* @param request users request. Claim of having an account part of a group of accounts
*/
function buildAttestations(
Request calldata request,
bytes calldata proofData
) public view virtual override(IAttester, Attester) returns (Attestation[] memory) {
HydraS1Claim memory claim = request._claim();
Attestation[] memory attestations = new Attestation[](1);
uint256 attestationCollectionId = AUTHORIZED_COLLECTION_ID_FIRST +
claim.groupProperties.groupIndex;
if (attestationCollectionId > AUTHORIZED_COLLECTION_ID_LAST)
revert CollectionIdOutOfBound(attestationCollectionId);
address issuer = address(this);
uint256 nullifier = proofData._getNullifier();
attestations[0] = Attestation(
attestationCollectionId,
claim.destination,
issuer,
claim.claimedValue,
claim.groupProperties.generationTimestamp,
abi.encode(nullifier)
);
return (attestations);
}
/*******************************************************
OPTIONAL HOOK VIRTUAL FUNCTIONS FROM ATTESTER.SOL
*******************************************************/
/**
* @dev Hook run before recording the attestation.
* Throws if nullifier already used and not a renewal (e.g destination different that last)
* @param request users request. Claim of having an account part of a group of accounts
* @param proofData provided to back the request. snark input and snark proof
*/
function _beforeRecordAttestations(
Request calldata request,
bytes calldata proofData
) internal virtual override {
// we get the nullifier used from the snark input in the data provided
uint256 nullifier = proofData._getNullifier();
address currentDestination = _getDestinationOfNullifier(nullifier);
if (currentDestination != address(0) && currentDestination != request.destination) {
revert NullifierUsed(nullifier);
}
_setDestinationForNullifier(nullifier, request.destination);
}
/*******************************************************
Hydra-S1 MANDATORY FUNCTIONS FROM Hydra-S1 Base Attester
*******************************************************/
/**
* @dev Returns the external nullifier from a user claim
* @param claim user Hydra-S1 claim = have an account with a specific value in a specific group
* nullifier = hash(sourceSecretHash, externalNullifier), which is verified inside the snark
* users bring sourceSecretHash as private input in snark which guarantees privacy
* Here we chose externalNullifier = hash(attesterAddress, claim.GroupId)
* Creates one nullifier per group, per user and makes sure no collision with other attester's nullifiers
**/
function _getExternalNullifierOfClaim(
HydraS1Claim memory claim
) internal view override returns (uint256) {
uint256 externalNullifier = _encodeInSnarkField(
address(this),
claim.groupProperties.groupIndex
);
return externalNullifier;
}
/**
* @dev returns the nullifier for a given extraData
* @param extraData bytes where the nullifier is encoded
*/
function getNullifierFromExtraData(
bytes memory extraData
) external pure virtual override(IHydraS1Base, HydraS1Base) returns (uint256) {
return abi.decode(extraData, (uint256));
}
/*******************************************************
Hydra-S1 Attester Specific Functions
*******************************************************/
/**
* @dev Getter, returns the last attestation destination of a nullifier
* @param nullifier nullifier used
**/
function getDestinationOfNullifier(uint256 nullifier) external view override returns (address) {
return _getDestinationOfNullifier(nullifier);
}
function _setDestinationForNullifier(uint256 nullifier, address destination) internal virtual {
_nullifiersDestinations[nullifier] = destination;
emit NullifierDestinationUpdated(nullifier, destination);
}
function _getDestinationOfNullifier(uint256 nullifier) internal view returns (address) {
return _nullifiersDestinations[nullifier];
}
function _encodeInSnarkField(address addr, uint256 nb) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(addr, nb))) % HydraS1Lib.SNARK_FIELD;
}
}
================================================
FILE: contracts/attesters/hydra-s1/base/HydraS1Base.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
pragma experimental ABIEncoderV2;
import {IHydraS1Base} from './IHydraS1Base.sol';
import {Attester} from '../../../core/Attester.sol';
import {Initializable} from '@openzeppelin/contracts/proxy/utils/Initializable.sol';
// Protocol imports
import {Request, Attestation, Claim} from '../../../core/libs/Structs.sol';
// Imports related to Hydra S1 ZK Proving Scheme
import {HydraS1Verifier, HydraS1Lib, HydraS1Claim, HydraS1ProofData, HydraS1ProofInput, HydraS1GroupProperties} from '../libs/HydraS1Lib.sol';
import {ICommitmentMapperRegistry} from '../../../periphery/utils/CommitmentMapperRegistry.sol';
import {IAvailableRootsRegistry} from '../../../periphery/utils/AvailableRootsRegistry.sol';
/**
* @title Hydra-S1 Base Attester
* @author Sismo
* @notice Abstract contract that facilitates the use of the Hydra-S1 ZK Proving Scheme.
* Hydra-S1 is single source, single group: it allows users to verify they are part of one and only one group at a time
* It is inherited by the family of Hydra-S1 attesters.
* It contains the user input checking and the ZK-SNARK proof verification.
* We invite readers to refer to the following:
* - https://hydra-s1.docs.sismo.io for a full guide through the Hydra-S1 ZK Attestations
* - https://hydra-s1-circuits.docs.sismo.io for circuits, prover and verifiers of Hydra-S1
*
*/
abstract contract HydraS1Base is IHydraS1Base, Attester, Initializable {
using HydraS1Lib for HydraS1ProofData;
// ZK-SNARK Verifier
HydraS1Verifier immutable VERIFIER;
// Registry storing the Commitment Mapper EdDSA Public key
ICommitmentMapperRegistry immutable COMMITMENT_MAPPER_REGISTRY;
// Registry storing the Registry Tree Roots of the Attester's available ClaimData
IAvailableRootsRegistry immutable AVAILABLE_ROOTS_REGISTRY;
/*******************************************************
INITIALIZATION FUNCTIONS
*******************************************************/
/**
* @dev Constructor. Initializes the contract
* @param hydraS1VerifierAddress ZK Snark Verifier contract
* @param availableRootsRegistryAddress Registry where is the Available Data (Registry Merkle Roots)
* @param commitmentMapperAddress Commitment mapper's public key registry
*/
constructor(
address hydraS1VerifierAddress,
address availableRootsRegistryAddress,
address commitmentMapperAddress
) {
VERIFIER = HydraS1Verifier(hydraS1VerifierAddress);
AVAILABLE_ROOTS_REGISTRY = IAvailableRootsRegistry(availableRootsRegistryAddress);
COMMITMENT_MAPPER_REGISTRY = ICommitmentMapperRegistry(commitmentMapperAddress);
}
/**
* @dev Getter of Hydra-S1 Verifier contract
*/
function getVerifier() external view returns (HydraS1Verifier) {
return VERIFIER;
}
/**
* @dev Getter of Commitment Mapper Registry contract
*/
function getCommitmentMapperRegistry() external view returns (ICommitmentMapperRegistry) {
return COMMITMENT_MAPPER_REGISTRY;
}
/**
* @dev Getter of Roots Registry Contract
*/
function getAvailableRootsRegistry() external view returns (IAvailableRootsRegistry) {
return AVAILABLE_ROOTS_REGISTRY;
}
/*******************************************************
Hydra-S1 SPECIFIC FUNCTIONS
*******************************************************/
/**
* @dev MANDATORY: must be implemented to return the nullifier from an attestation extraData
* @dev Getter of a nullifier encoded in extraData
* @notice Must be implemented by the inheriting contracts
* @param extraData extraData where nullifier can be encoded
*/
function getNullifierFromExtraData(
bytes memory extraData
) external view virtual returns (uint256);
/**
* @dev MANDATORY: must be implemented to return the external nullifier from a user request
* so it can be checked against snark input
* nullifier = hash(sourceSecretHash, externalNullifier), which is verified inside the snark
* users bring sourceSecretHash as private input which guarantees privacy
*
* This function MUST be implemented by Hydra-S1 attesters.
* This is the core function that implements the logic of external nullifiers
*
* Do they get one external nullifier per claim?
* Do they get 2 external nullifiers per claim?
* Do they get 1 external nullifier per claim, every month?
* Take a look at Hydra-S1 Simple Attester for an example
* @param claim user claim: part of a group of accounts, with a claimedValue for their account
*/
function _getExternalNullifierOfClaim(
HydraS1Claim memory claim
) internal view virtual returns (uint256);
/**
* @dev Checks whether the user claim and the snark public input are a match
* @param claim user claim
* @param input snark public input
*/
function _validateInput(
HydraS1Claim memory claim,
HydraS1ProofInput memory input
) internal view virtual {
if (input.accountsTreeValue != claim.groupId) {
revert AccountsTreeValueMismatch(claim.groupId, input.accountsTreeValue);
}
if (input.isStrict == claim.groupProperties.isScore) {
revert IsStrictMismatch(claim.groupProperties.isScore, input.isStrict);
}
if (input.destination != claim.destination) {
revert DestinationMismatch(claim.destination, input.destination);
}
if (input.chainId != block.chainid) revert ChainIdMismatch(block.chainid, input.chainId);
if (input.value != claim.claimedValue) revert ValueMismatch(claim.claimedValue, input.value);
if (!AVAILABLE_ROOTS_REGISTRY.isRootAvailableForMe(input.registryRoot)) {
revert RegistryRootMismatch(input.registryRoot);
}
uint256[2] memory commitmentMapperPubKey = COMMITMENT_MAPPER_REGISTRY.getEdDSAPubKey();
if (
input.commitmentMapperPubKey[0] != commitmentMapperPubKey[0] ||
input.commitmentMapperPubKey[1] != commitmentMapperPubKey[1]
) {
revert CommitmentMapperPubKeyMismatch(
commitmentMapperPubKey[0],
commitmentMapperPubKey[1],
input.commitmentMapperPubKey[0],
input.commitmentMapperPubKey[1]
);
}
uint256 externalNullifier = _getExternalNullifierOfClaim(claim);
if (input.externalNullifier != externalNullifier) {
revert ExternalNullifierMismatch(externalNullifier, input.externalNullifier);
}
}
/**
* @dev verify the groth16 mathematical proof
* @param proofData snark public input
*/
function _verifyProof(HydraS1ProofData memory proofData) internal view virtual {
try
VERIFIER.verifyProof(proofData.proof.a, proofData.proof.b, proofData.proof.c, proofData.input)
returns (bool success) {
if (!success) revert InvalidGroth16Proof('');
} catch Error(string memory reason) {
revert InvalidGroth16Proof(reason);
} catch Panic(uint256 /*errorCode*/) {
revert InvalidGroth16Proof('');
} catch (bytes memory /*lowLevelData*/) {
revert InvalidGroth16Proof('');
}
}
}
================================================
FILE: contracts/attesters/hydra-s1/base/IHydraS1Base.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
pragma experimental ABIEncoderV2;
import {IAttester} from '../../../core/interfaces/IAttester.sol';
import {HydraS1Verifier, HydraS1Lib, HydraS1ProofData} from '../libs/HydraS1Lib.sol';
import {ICommitmentMapperRegistry} from '../../../periphery/utils/CommitmentMapperRegistry.sol';
import {IAvailableRootsRegistry} from '../../../periphery/utils/AvailableRootsRegistry.sol';
/**
* @title Hydra-S1 Base Interface
* @author Sismo
* @notice Interface that facilitates the use of the Hydra-S1 ZK Proving Scheme.
* Hydra-S1 is single source, single group: it allows users to verify they are part of one and only one group at a time
* It is inherited by the family of Hydra-S1 attesters.
* It contains the errors and method specific of the Hydra-S1 attesters family and the Hydra-S1 ZK Proving Scheme
* We invite readers to refer to the following:
* - https://hydra-s1.docs.sismo.io for a full guide through the Hydra-S1 ZK Attestations
* - https://hydra-s1-circuits.docs.sismo.io for circuits, prover and verifiers of Hydra-S1
**/
interface IHydraS1Base is IAttester {
error ClaimsLengthDifferentThanOne(uint256 claimLength);
error RegistryRootMismatch(uint256 inputRoot);
error DestinationMismatch(address expectedDestination, address inputDestination);
error CommitmentMapperPubKeyMismatch(
uint256 expectedX,
uint256 expectedY,
uint256 inputX,
uint256 inputY
);
error ExternalNullifierMismatch(uint256 expectedExternalNullifier, uint256 externalNullifier);
error IsStrictMismatch(bool expectedStrictness, bool strictNess);
error ChainIdMismatch(uint256 expectedChainId, uint256 chainId);
error ValueMismatch(uint256 expectedValue, uint256 inputValue);
error AccountsTreeValueMismatch(
uint256 expectedAccountsTreeValue,
uint256 inputAccountsTreeValue
);
error InvalidGroth16Proof(string reason);
function getNullifierFromExtraData(bytes memory extraData) external view returns (uint256);
/**
* @dev Getter of Hydra-S1 Verifier contract
*/
function getVerifier() external view returns (HydraS1Verifier);
/**
* @dev Getter of Commitment Mapper Registry contract
*/
function getCommitmentMapperRegistry() external view returns (ICommitmentMapperRegistry);
/**
* @dev Getter of Roots Registry Contract
*/
function getAvailableRootsRegistry() external view returns (IAvailableRootsRegistry);
}
================================================
FILE: contracts/attesters/hydra-s1/interfaces/IHydraS1AccountboundAttester.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
pragma experimental ABIEncoderV2;
import {IHydraS1SimpleAttester} from '././IHydraS1SimpleAttester.sol';
/**
* @title Hydra-S1 Accountbound Interface
* @author Sismo
* @notice Interface of the HydraS1AccountboundAttester contract which inherits from the errors, events and methods specific to the HydraS1SimpleAttester interface.
**/
interface IHydraS1AccountboundAttester is IHydraS1SimpleAttester {
/**
* @dev Event emitted when the duration of the cooldown duration for a group index (internal collection id) has been set
* @param groupIndex internal collection id
* @param cooldownDuration the duration of the cooldown period
**/
event CooldownDurationSetForGroupIndex(uint256 indexed groupIndex, uint32 cooldownDuration);
/**
* @dev Event emitted when the nullifier has been set on cooldown. This happens when the
* attestation destination of a nullifier has been changed
* @param nullifier user nullifier
* @param burnCount the number of times the attestation destination of a nullifier has been changed
**/
event NullifierSetOnCooldown(uint256 indexed nullifier, uint16 burnCount);
/**
* @dev Error when the nullifier is on cooldown. The user have to wait the cooldownDuration
* before being able to change again the destination address.
**/
error NullifierOnCooldown(
uint256 nullifier,
address destination,
uint16 burnCount,
uint32 cooldownStart
);
/**
* @dev Error when the cooldown duration for a given groupIndex is equal to zero.
* The HydraS1AccountboundAttester behaves like the HydraS1SimpleAttester.
**/
error CooldownDurationNotSetForGroupIndex(uint256 groupIndex);
/**
* @dev Initializes the contract, to be called by the proxy delegating calls to this implementation
* @param owner Owner of the contract, can update public key and address
*/
function initialize(address owner) external;
/**
* @dev returns the nullifier for a given extraData
* @param extraData bytes where the nullifier is encoded
*/
function getNullifierFromExtraData(bytes memory extraData) external pure returns (uint256);
/**
* @dev Returns the burn count for a given extraData
* @param extraData bytes where the burnCount is encoded
*/
function getBurnCountFromExtraData(bytes memory extraData) external pure returns (uint16);
/**
* @dev Getter, returns the cooldown start of a nullifier
* @param nullifier nullifier used
**/
function getNullifierCooldownStart(uint256 nullifier) external view returns (uint32);
/**
* @dev Getter, returns the burnCount of a nullifier
* @param nullifier nullifier used
**/
function getNullifierBurnCount(uint256 nullifier) external view returns (uint16);
/**
* @dev Setter, sets the cooldown duration of a groupIndex
* @param groupIndex internal collection id
* @param cooldownDuration cooldown duration we want to set for the groupIndex
**/
function setCooldownDurationForGroupIndex(uint256 groupIndex, uint32 cooldownDuration) external;
/*/**
* @dev Getter, get the cooldown duration of a groupIndex
* @notice returns 0 when the accountbound feature is deactivated for this group
* @param groupIndex internal collection id
**/
function getCooldownDurationForGroupIndex(uint256 groupIndex) external view returns (uint32);
}
================================================
FILE: contracts/attesters/hydra-s1/interfaces/IHydraS1SimpleAttester.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
pragma experimental ABIEncoderV2;
import {Attestation} from '../../../core/libs/Structs.sol';
import {CommitmentMapperRegistry} from '../../../periphery/utils/CommitmentMapperRegistry.sol';
import {AvailableRootsRegistry} from '../../../periphery/utils/AvailableRootsRegistry.sol';
import {HydraS1Lib, HydraS1ProofData, HydraS1ProofInput} from './../libs/HydraS1Lib.sol';
import {IHydraS1Base} from './../base/IHydraS1Base.sol';
/**
* @title Hydra-S1 Accountbound Interface
* @author Sismo
* @notice Interface with errors, events and methods specific to the HydraS1SimpleAttester.
**/
interface IHydraS1SimpleAttester is IHydraS1Base {
/**
* @dev Error when the nullifier is already used for a destination address
**/
error NullifierUsed(uint256 nullifier);
/**
* @dev Error when the collectionId of an attestation overflow the AUTHORIZED_COLLECTION_ID_LAST
**/
error CollectionIdOutOfBound(uint256 collectionId);
/**
* @dev Event emitted when the nullifier is associated to a destination address.
**/
event NullifierDestinationUpdated(uint256 nullifier, address newOwner);
/**
* @dev Getter, returns the last attestation destination of a nullifier
* @param nullifier nullifier used
**/
function getDestinationOfNullifier(uint256 nullifier) external view returns (address);
/**
* @dev Getter
* returns of the first collection in which the attester is supposed to record
**/
function AUTHORIZED_COLLECTION_ID_FIRST() external view returns (uint256);
/**
* @dev Getter
* returns of the last collection in which the attester is supposed to record
**/
function AUTHORIZED_COLLECTION_ID_LAST() external view returns (uint256);
}
================================================
FILE: contracts/attesters/hydra-s1/libs/HydraS1AccountboundLib.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
import {Claim, Request} from '../../../core/libs/Structs.sol';
import {HydraS1Lib, HydraS1Claim, HydraS1GroupProperties} from './HydraS1Lib.sol';
// user Hydra-S1 claim retrieved form his request
struct HydraS1AccountboundClaim {
uint256 groupId; // user claims to have an account in this group
uint256 claimedValue; // user claims this value for its account in the group
address destination; // user claims to own this destination[]
HydraS1AccountboundGroupProperties groupProperties; // user claims the group has the following properties
}
struct HydraS1AccountboundGroupProperties {
uint128 groupIndex;
uint32 generationTimestamp;
uint32 cooldownDuration;
bool isScore;
}
library HydraS1AccountboundLib {
error GroupIdAndPropertiesMismatch(uint256 expectedGroupId, uint256 groupId);
function _hydraS1claim(Request memory self) internal pure returns (HydraS1Claim memory) {
Claim memory claim = self.claims[0];
_validateClaim(claim);
HydraS1AccountboundGroupProperties memory groupProperties = abi.decode(
claim.extraData,
(HydraS1AccountboundGroupProperties)
);
HydraS1GroupProperties memory hydraS1GroupProperties = HydraS1GroupProperties(
groupProperties.groupIndex,
groupProperties.generationTimestamp,
groupProperties.isScore
);
return (
HydraS1Claim(claim.groupId, claim.claimedValue, self.destination, hydraS1GroupProperties)
);
}
function _hydraS1Accountboundclaim(
Request memory self
) internal pure returns (HydraS1AccountboundClaim memory) {
Claim memory claim = self.claims[0];
_validateClaim(claim);
HydraS1AccountboundGroupProperties memory hydraS1AccountboundGroupProperties = abi.decode(
claim.extraData,
(HydraS1AccountboundGroupProperties)
);
return (
HydraS1AccountboundClaim(
claim.groupId,
claim.claimedValue,
self.destination,
hydraS1AccountboundGroupProperties
)
);
}
function _generateGroupIdFromEncodedProperties(
bytes memory encodedProperties
) internal pure returns (uint256) {
return uint256(keccak256(encodedProperties)) % HydraS1Lib.SNARK_FIELD;
}
function _validateClaim(Claim memory claim) internal pure {
uint256 expectedGroupId = _generateGroupIdFromEncodedProperties(claim.extraData);
if (claim.groupId != expectedGroupId)
revert GroupIdAndPropertiesMismatch(expectedGroupId, claim.groupId);
}
}
================================================
FILE: contracts/attesters/hydra-s1/libs/HydraS1Lib.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
import {Claim, Request} from '../../../core/libs/Structs.sol';
import {HydraS1Verifier} from '@sismo-core/hydra-s1/contracts/HydraS1Verifier.sol';
// user Hydra-S1 claim retrieved form his request
struct HydraS1Claim {
uint256 groupId; // user claims to have an account in this group
uint256 claimedValue; // user claims this value for its account in the group
address destination; // user claims to own this destination[]
HydraS1GroupProperties groupProperties; // user claims the group has the following properties
}
struct HydraS1GroupProperties {
uint128 groupIndex;
uint32 generationTimestamp;
bool isScore;
}
struct HydraS1CircomSnarkProof {
uint256[2] a;
uint256[2][2] b;
uint256[2] c;
}
struct HydraS1ProofData {
HydraS1CircomSnarkProof proof;
uint256[10] input;
// destination
// chainId
// commitmentMapperPubKey.x
// commitmentMapperPubKey.y
// registryTreeRoot
// externalNullifier
// nullifier
// claimedValue
// accountsTreeValue
// isStrict
}
struct HydraS1ProofInput {
address destination;
uint256 chainId;
uint256 registryRoot;
uint256 externalNullifier;
uint256 nullifier;
uint256 value;
uint256 accountsTreeValue;
bool isStrict;
uint256[2] commitmentMapperPubKey;
}
library HydraS1Lib {
uint256 constant SNARK_FIELD =
21888242871839275222246405745257275088548364400416034343698204186575808495617;
error GroupIdAndPropertiesMismatch(uint256 expectedGroupId, uint256 groupId);
function _input(HydraS1ProofData memory self) internal pure returns (HydraS1ProofInput memory) {
return
HydraS1ProofInput(
_getDestination(self),
_getChainId(self),
_getRegistryRoot(self),
_getExpectedExternalNullifier(self),
_getNullifier(self),
_getValue(self),
_getAccountsTreeValue(self),
_getIsStrict(self),
_getCommitmentMapperPubKey(self)
);
}
function _claim(Request memory self) internal pure returns (HydraS1Claim memory) {
Claim memory claim = self.claims[0];
_validateClaim(claim);
HydraS1GroupProperties memory groupProperties = abi.decode(
claim.extraData,
(HydraS1GroupProperties)
);
return (HydraS1Claim(claim.groupId, claim.claimedValue, self.destination, groupProperties));
}
function _toCircomFormat(
HydraS1ProofData memory self
)
internal
pure
returns (uint256[2] memory, uint256[2][2] memory, uint256[2] memory, uint256[10] memory)
{
return (self.proof.a, self.proof.b, self.proof.c, self.input);
}
function _getDestination(HydraS1ProofData memory self) internal pure returns (address) {
return address(uint160(self.input[0]));
}
function _getChainId(HydraS1ProofData memory self) internal pure returns (uint256) {
return self.input[1];
}
function _getCommitmentMapperPubKey(
HydraS1ProofData memory self
) internal pure returns (uint256[2] memory) {
return [self.input[2], self.input[3]];
}
function _getRegistryRoot(HydraS1ProofData memory self) internal pure returns (uint256) {
return self.input[4];
}
function _getExpectedExternalNullifier(
HydraS1ProofData memory self
) internal pure returns (uint256) {
return self.input[5];
}
function _getNullifier(HydraS1ProofData memory self) internal pure returns (uint256) {
return self.input[6];
}
function _getValue(HydraS1ProofData memory self) internal pure returns (uint256) {
return self.input[7];
}
function _getAccountsTreeValue(HydraS1ProofData memory self) internal pure returns (uint256) {
return self.input[8];
}
function _getIsStrict(HydraS1ProofData memory self) internal pure returns (bool) {
return self.input[9] == 1;
}
function _getNullifier(bytes calldata self) internal pure returns (uint256) {
HydraS1ProofData memory snarkProofData = abi.decode(self, (HydraS1ProofData));
uint256 nullifier = uint256(_getNullifier(snarkProofData));
return nullifier;
}
function _generateGroupIdFromProperties(
uint128 groupIndex,
uint32 generationTimestamp,
bool isScore
) internal pure returns (uint256) {
return
_generateGroupIdFromEncodedProperties(
_encodeGroupProperties(groupIndex, generationTimestamp, isScore)
);
}
function _generateGroupIdFromEncodedProperties(
bytes memory encodedProperties
) internal pure returns (uint256) {
return uint256(keccak256(encodedProperties)) % HydraS1Lib.SNARK_FIELD;
}
function _encodeGroupProperties(
uint128 groupIndex,
uint32 generationTimestamp,
bool isScore
) internal pure returns (bytes memory) {
return abi.encode(groupIndex, generationTimestamp, isScore);
}
function _validateClaim(Claim memory claim) internal pure {
uint256 expectedGroupId = _generateGroupIdFromEncodedProperties(claim.extraData);
if (claim.groupId != expectedGroupId)
revert GroupIdAndPropertiesMismatch(expectedGroupId, claim.groupId);
}
}
================================================
FILE: contracts/attesters/pythia-1/Pythia1SimpleAttester.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
pragma experimental ABIEncoderV2;
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {IPythia1SimpleAttester} from './interfaces/IPythia1SimpleAttester.sol';
// Core protocol Protocol imports
import {Request, Attestation, Claim} from './../../core/libs/Structs.sol';
import {Attester, IAttester, IAttestationsRegistry} from './../../core/Attester.sol';
// Imports related to Pythia1 Proving Scheme
import {Pythia1Base, Pythia1Lib, Pythia1ProofData, Pythia1ProofInput, Pythia1Claim} from './base/Pythia1Base.sol';
/**
* @title Pythia-1 Simple Attester
* @author Sismo
* @notice This attester is part of the family of the Pythia-1 Attesters.
* Pythia-1 attesters enable users to prove they have a claim and its proof issued by an
* offchain service in a privacy preserving way.
* That means no-one can make the link between the account used in the offchain service
* and the onchain account where the attestation is stored.
* The Pythia-1 Base abstract contract is inherited and holds the complex Pythia 1 verification logic.
* We invite readers to refer to:
* - https://pythia-1.docs.sismo.io for a full guide through the Pythia-1 ZK Attestations
* - https://pythia-1-circuits.docs.sismo.io for circuits, prover and verifiers of Pythia-1
* This specific attester has the following characteristics:
* - Zero Knowledge
* One cannot deduct from an attestation what offchain issuer's account was used to generate the underlying proof
* - Non Strict (scores)
* If a user can generate an attestation of max value 100, they can also generate any attestation with value < 100.
* This attester generate attestations of scores
* - Ticketed
* Each users gets one userTicket per claim
* For people used to semaphore/ tornado cash people:
* userTicket = hash(secret, ticketIdentifier) <=> nullifierHash = hash(IdNullifier, externalNullifier)
**/
contract Pythia1SimpleAttester is IPythia1SimpleAttester, Pythia1Base, Attester, Ownable {
using Pythia1Lib for Pythia1ProofData;
using Pythia1Lib for bytes;
using Pythia1Lib for Request;
uint8 public constant IMPLEMENTATION_VERSION = 4;
// The deployed contract will need to be authorized to write into the Attestation registry
// It should get write access on attestation collections from AUTHORIZED_COLLECTION_ID_FIRST to AUTHORIZED_COLLECTION_ID_LAST.
uint256 public immutable AUTHORIZED_COLLECTION_ID_FIRST;
uint256 public immutable AUTHORIZED_COLLECTION_ID_LAST;
uint256[2] internal _commitmentSignerPubKey;
mapping(uint256 => address) internal _ticketsDestinations;
/*******************************************************
INITIALIZATION FUNCTIONS
*******************************************************/
/**
* @dev Constructor. Initializes the contract
* @param attestationsRegistryAddress Attestations Registry contract on which the attester will write attestations
* @param collectionIdFirst Id of the first collection in which the attester is supposed to record
* @param collectionIdLast Id of the last collection in which the attester is supposed to record
* @param pythia1VerifierAddress ZK Snark Pythia-1 Verifier contract
* @param commitmentSignerPubKey The EdDSA public key of the commitment signer for the Pythia 1 Proving Scheme
* @param owner The owner of the contract that can update the commitment signer pub key
*/
constructor(
address attestationsRegistryAddress,
uint256 collectionIdFirst,
uint256 collectionIdLast,
address pythia1VerifierAddress,
uint256[2] memory commitmentSignerPubKey,
address owner
) Attester(attestationsRegistryAddress) Pythia1Base(pythia1VerifierAddress) {
AUTHORIZED_COLLECTION_ID_FIRST = collectionIdFirst;
AUTHORIZED_COLLECTION_ID_LAST = collectionIdLast;
initialize(commitmentSignerPubKey, owner);
}
/**
* @dev Initializes the contract, to be called by the proxy delegating calls to this implementation
* @param commitmentSignerPubKey EdDSA public key of the commitment signer
* @param ownerAddress Owner of the contract, can update public key and address
* @notice The reinitializer modifier is needed to configure modules that are added through upgrades and that require initialization.
*/
function initialize(
uint256[2] memory commitmentSignerPubKey,
address ownerAddress
) public reinitializer(IMPLEMENTATION_VERSION) {
// if proxy did not setup owner yet or if called by constructor (for implem setup)
if (owner() == address(0) || address(this).code.length == 0) {
_transferOwnership(ownerAddress);
_updateCommitmentSignerPubKey(commitmentSignerPubKey);
}
}
/*******************************************************
MANDATORY FUNCTIONS TO OVERRIDE FROM ATTESTER.SOL
*******************************************************/
/**
* @dev Throws if user request is invalid when verified against
* Look into Pythia1Base for more details
* @param request users request. Claim of having an account part of a group of accounts
* @param proofData provided to back the request. snark input and snark proof
*/
function _verifyRequest(
Request calldata request,
bytes calldata proofData
) internal virtual override {
Pythia1ProofData memory snarkProof = abi.decode(proofData, (Pythia1ProofData));
Pythia1ProofInput memory snarkInput = snarkProof._input();
Pythia1Claim memory claim = request._claim();
// verifies that the proof corresponds to the claim
_validateInput(claim, snarkInput);
// verifies the proof validity
_verifyProof(snarkProof);
}
/**
* @dev Returns attestations that will be recorded, constructed from the user request
* @param request users request. Claim of having an account part of a group of accounts
*/
function buildAttestations(
Request calldata request,
bytes calldata
) public view virtual override(IAttester, Attester) returns (Attestation[] memory) {
Pythia1Claim memory claim = request._claim();
Attestation[] memory attestations = new Attestation[](1);
uint256 attestationCollectionId = AUTHORIZED_COLLECTION_ID_FIRST +
claim.groupProperties.internalCollectionId;
if (attestationCollectionId > AUTHORIZED_COLLECTION_ID_LAST)
revert CollectionIdOutOfBound(attestationCollectionId);
address issuer = address(this);
attestations[0] = Attestation(
attestationCollectionId,
claim.destination,
issuer,
claim.claimedValue,
uint32(block.timestamp),
''
);
return (attestations);
}
/*******************************************************
OPTIONAL HOOK VIRTUAL FUNCTIONS FROM ATTESTER.SOL
*******************************************************/
/**
* @dev Hook run before recording the attestation.
* Throws if ticket already used
* @param request users request. Claim of beiing part of a group.
* @param proofData provided to back the request. snark input and snark proof
*/
function _beforeRecordAttestations(
Request calldata request,
bytes calldata proofData
) internal virtual override {
// we get the ticket used from the snark input in the data provided
uint256 userTicket = proofData._getTicket();
address currentDestination = _getDestinationOfTicket(userTicket);
if (currentDestination != address(0)) {
revert TicketUsed(userTicket);
}
_setDestinationForTicket(userTicket, request.destination);
}
/*******************************************************
Pythia-1 MANDATORY FUNCTIONS FROM Pythia-1 Base Attester
*******************************************************/
/**
* @dev Returns the ticket identifier from a user claim
* @param claim user Pythia-1 claim = have an offchain account with a specific value in a specific group
* ticket = hash(secretHash, ticketIdentifier), which is verified inside the snark
* users bring secretHash as private input in snark which guarantees privacy
* the secretHash is only known by the user and never escape the user's browser
* Here we chose ticketIdentifier = hash(attesterAddress, claim.GroupId)
* Creates one ticket per group, per user and makes sure no collision with other attester's tickets
**/
function _getTicketIdentifierOfClaim(
Pythia1Claim memory claim
) internal view override returns (uint256) {
uint256 ticketIdentifier = _encodeInSnarkField(
address(this),
claim.groupProperties.internalCollectionId
);
return ticketIdentifier;
}
function _getCommitmentSignerPubKey() internal view override returns (uint256[2] memory) {
return _commitmentSignerPubKey;
}
/*******************************************************
Pythia-1 Attester Specific Functions
*******************************************************/
function updateCommitmentSignerPubKey(
uint256[2] memory commitmentSignerPubKey
) external onlyOwner {
_updateCommitmentSignerPubKey(commitmentSignerPubKey);
}
function _updateCommitmentSignerPubKey(uint256[2] memory commitmentSignerPubKey) internal {
_commitmentSignerPubKey = commitmentSignerPubKey;
emit CommitmentSignerPubKeyUpdated(commitmentSignerPubKey);
}
/**
* @dev Getter, returns the last attestation destination of a ticket
* @param userTicket ticket used
**/
function getDestinationOfTicket(uint256 userTicket) external view override returns (address) {
return _getDestinationOfTicket(userTicket);
}
function _setDestinationForTicket(uint256 userTicket, address destination) internal virtual {
_ticketsDestinations[userTicket] = destination;
emit TicketDestinationUpdated(userTicket, destination);
}
function _getDestinationOfTicket(uint256 userTicket) internal view returns (address) {
return _ticketsDestinations[userTicket];
}
function _encodeInSnarkField(address addr, uint256 nb) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(addr, nb))) % Pythia1Lib.SNARK_FIELD;
}
}
================================================
FILE: contracts/attesters/pythia-1/base/IPythia1Base.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
pragma experimental ABIEncoderV2;
import {Pythia1Verifier, Pythia1Lib, Pythia1ProofData} from '../libs/Pythia1Lib.sol';
interface IPythia1Base {
error DestinationMismatch(address expectedDestination, address inputDestination);
error UserShouldOwnItsDestination(address sender, address inputdestination);
error CommitmentSignerPubKeyMismatch(
uint256 expectedX,
uint256 expectedY,
uint256 inputX,
uint256 inputY
);
error TicketIdentifierMismatch(uint256 expectedTicketIdentifier, uint256 ticketIdentifier);
error IsStrictMismatch(bool expectedStrictness, bool strictNess);
error ChainIdMismatch(uint256 expectedChainId, uint256 chainId);
error ValueMismatch(uint256 expectedValue, uint256 inputValue);
error GroupIdMismatch(uint256 expectedAccountsTreeValue, uint256 inputAccountsTreeValue);
error InvalidGroth16Proof(string reason);
/**
* @dev Getter of Pythia-1 Verifier contract
*/
function getVerifier() external view returns (Pythia1Verifier);
/**
* @dev Getter of the Commitment Signer EdDSA Public Key
*/
function getCommitmentSignerPubKey() external view returns (uint256[2] memory);
}
================================================
FILE: contracts/attesters/pythia-1/base/Pythia1Base.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
pragma experimental ABIEncoderV2;
import {IPythia1Base} from './IPythia1Base.sol';
import {Initializable} from '@openzeppelin/contracts/proxy/utils/Initializable.sol';
// Protocol imports
import {Request, Attestation, Claim} from '../../../core/libs/Structs.sol';
// Imports related to Pythia 1 ZK Proving Scheme
import {Pythia1Verifier, Pythia1Lib, Pythia1Claim, Pythia1ProofData, Pythia1ProofInput, Pythia1GroupProperties} from '../libs/Pythia1Lib.sol';
/**
* @title Pythia-1 Base Attester
* @author Sismo
* @notice Abstract contract that facilitates the use of the Pythia-1 ZK Proving Scheme.
* Pythia-1: it allows issuing attestations from an offchain service and send it onchain
* without anyone being able to make the link between the offchain service and the onchain service.
* It is inherited by the family of Pythia-1 attesters.
* It contains the user input checking and the ZK-SNARK proof verification.
* We invite readers to refer to:
* - https://pythia-1.docs.sismo.io for a full guide through the Pythia-1 ZK Attestations
* - https://pythia-1-circuits.docs.sismo.io for circuits, prover and verifiers of Pythia-1
**/
abstract contract Pythia1Base is IPythia1Base, Initializable {
using Pythia1Lib for Pythia1ProofData;
// ZK-SNARK Verifier
Pythia1Verifier immutable VERIFIER;
/*******************************************************
INITIALIZATION FUNCTIONS
*******************************************************/
/**
* @dev Constructor. Initializes the contract
* @param Pythia1VerifierAddress ZK Snark Verifier contract
*/
constructor(address Pythia1VerifierAddress) {
VERIFIER = Pythia1Verifier(Pythia1VerifierAddress);
}
/**
* @dev Getter of Pythia-1 Verifier contract
*/
function getVerifier() external view returns (Pythia1Verifier) {
return VERIFIER;
}
/**
* @dev Getter of the Commitment signer Eddsa Public key
*/
function getCommitmentSignerPubKey() external view returns (uint256[2] memory) {
return _getCommitmentSignerPubKey();
}
/*******************************************************
Pythia-1 SPECIFIC FUNCTIONS
*******************************************************/
/**
* @dev MANDATORY: must be implemented to return the ticket identifier from a user request
* so it can be checked against snark input
* ticket = hash(secretHash, ticketIdentifier), which is verified inside the snark
* the secretHash is a number only known by the user and is used in
* the zero knowledge as a private input which guarantees privacy
* This function MUST be implemented by Pythia-1 attesters.
* This is the core function that implements the logic of tickets
* Do they get one ticket per claim?
* Do they get 2 tickets per claim?
* Do they get 1 ticket per claim, every month?
* Take a look at Pythia-1 Simple Attester for an example
* @param claim user claim: a particular claim that a user have that he can prove s right.
*/
function _getTicketIdentifierOfClaim(
Pythia1Claim memory claim
) internal view virtual returns (uint256);
/**
* @dev MANDATORY: must be implemented to return the commitment signer that allows to
* prove the claim was correctly issued for the user.
*/
function _getCommitmentSignerPubKey() internal view virtual returns (uint256[2] memory);
/**
* @dev Checks whether the user claim and the snark public input are a match
* @param claim user claim
* @param input snark public input
*/
function _validateInput(
Pythia1Claim memory claim,
Pythia1ProofInput memory input
) internal view virtual {
if (input.groupId != claim.groupId) revert GroupIdMismatch(claim.groupId, input.groupId);
if (input.isStrict == claim.groupProperties.isScore)
revert IsStrictMismatch(claim.groupProperties.isScore, input.isStrict);
if (input.destination != claim.destination)
revert DestinationMismatch(claim.destination, input.destination);
if (claim.destination != msg.sender)
revert UserShouldOwnItsDestination(msg.sender, claim.destination);
if (input.chainId != block.chainid) revert ChainIdMismatch(block.chainid, input.chainId);
if (input.value != claim.claimedValue) revert ValueMismatch(claim.claimedValue, input.value);
uint256[2] memory commitmentSignerPubKey = _getCommitmentSignerPubKey();
if (
input.commitmentSignerPubKey[0] != commitmentSignerPubKey[0] ||
input.commitmentSignerPubKey[1] != commitmentSignerPubKey[1]
)
revert CommitmentSignerPubKeyMismatch(
commitmentSignerPubKey[0],
commitmentSignerPubKey[1],
input.commitmentSignerPubKey[0],
input.commitmentSignerPubKey[1]
);
uint256 ticketIdentifier = _getTicketIdentifierOfClaim(claim);
if (input.ticketIdentifier != ticketIdentifier)
revert TicketIdentifierMismatch(ticketIdentifier, input.ticketIdentifier);
}
/**
* @dev verify the plonk mathematical proof using the circom verifier contract
* @param proofData snark public input
*/
function _verifyProof(Pythia1ProofData memory proofData) internal view virtual {
try
VERIFIER.verifyProof(proofData.proof.a, proofData.proof.b, proofData.proof.c, proofData.input)
returns (bool success) {
if (!success) revert InvalidGroth16Proof('');
} catch Error(string memory reason) {
revert InvalidGroth16Proof(reason);
} catch Panic(uint256 /*errorCode*/) {
revert InvalidGroth16Proof('');
} catch (bytes memory /*lowLevelData*/) {
revert InvalidGroth16Proof('');
}
}
}
================================================
FILE: contracts/attesters/pythia-1/interfaces/IPythia1SimpleAttester.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
pragma experimental ABIEncoderV2;
import {Attestation} from '../../../core/libs/Structs.sol';
import {IAttester} from '../../../core/interfaces/IAttester.sol';
import {Pythia1Lib, Pythia1ProofData, Pythia1ProofInput} from './../libs/Pythia1Lib.sol';
import {IPythia1Base} from './../base/IPythia1Base.sol';
interface IPythia1SimpleAttester is IPythia1Base, IAttester {
error TicketUsed(uint256 userTicket);
error CollectionIdOutOfBound(uint256 collectionId);
event TicketDestinationUpdated(uint256 ticket, address newOwner);
event CommitmentSignerPubKeyUpdated(uint256[2] newCommitmentSignerPubKey);
/**
* @dev Initializes the contract, to be called by the proxy delegating calls to this implementation
* @param commitmentSignerPubKey EdDSA public key of the commitment signer
* @param owner Owner of the contract, can update public key and address
* @notice The reinitializer modifier is needed to configure modules that are added through upgrades and that require initialization.
*/
function initialize(uint256[2] memory commitmentSignerPubKey, address owner) external;
/**
* @dev Getter, returns the last attestation destination of a ticket
* @param userTicket ticket used
**/
function getDestinationOfTicket(uint256 userTicket) external view returns (address);
/**
* @dev Getter
* returns of the first collection in which the attester is supposed to record
**/
function AUTHORIZED_COLLECTION_ID_FIRST() external view returns (uint256);
/**
* @dev Getter
* returns of the last collection in which the attester is supposed to record
**/
function AUTHORIZED_COLLECTION_ID_LAST() external view returns (uint256);
}
================================================
FILE: contracts/attesters/pythia-1/libs/Pythia1Lib.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
import {Claim, Request} from '../../../core/libs/Structs.sol';
import {Pythia1Verifier} from '@sismo-core/pythia-1/contracts/Pythia1Verifier.sol';
// user Pythia-1 claim retrieved form his request
struct Pythia1Claim {
uint256 groupId; // user claims be part of this group
uint256 claimedValue; // user claims this value for its account in the group
address destination; // user claims to own this destination[]
Pythia1GroupProperties groupProperties; // user claims the group has the following properties
}
struct Pythia1GroupProperties {
uint128 internalCollectionId;
bool isScore;
}
struct Pythia1CircomSnarkProof {
uint256[2] a;
uint256[2][2] b;
uint256[2] c;
}
struct Pythia1ProofData {
Pythia1CircomSnarkProof proof;
uint256[9] input;
// destination;
// chainId;
// commitmentSignerPubKey.x;
// commitmentSignerPubKey.y;
// groupId;
// ticketIdentifier;
// userTicket;
// value;
// isStrict;
}
struct Pythia1ProofInput {
address destination;
uint256 chainId;
uint256 groupId;
uint256 ticketIdentifier;
uint256 ticket;
uint256 value;
bool isStrict;
uint256[2] commitmentSignerPubKey;
}
library Pythia1Lib {
uint256 constant SNARK_FIELD =
21888242871839275222246405745257275088548364400416034343698204186575808495617;
error GroupIdAndPropertiesMismatch(uint256 expectedGroupId, uint256 groupId);
function _input(Pythia1ProofData memory self) internal pure returns (Pythia1ProofInput memory) {
return
Pythia1ProofInput(
_getDestination(self),
_getChainId(self),
_getGroupId(self),
_getExpectedExternalNullifier(self),
_getTicket(self),
_getValue(self),
_getIsStrict(self),
_getCommitmentMapperPubKey(self)
);
}
function _claim(Request memory self) internal pure returns (Pythia1Claim memory) {
Claim memory claim = self.claims[0];
_validateClaim(claim);
Pythia1GroupProperties memory groupProperties = abi.decode(
claim.extraData,
(Pythia1GroupProperties)
);
return (Pythia1Claim(claim.groupId, claim.claimedValue, self.destination, groupProperties));
}
function _toCircomFormat(
Pythia1ProofData memory self
)
internal
pure
returns (uint256[2] memory, uint256[2][2] memory, uint256[2] memory, uint256[9] memory)
{
return (self.proof.a, self.proof.b, self.proof.c, self.input);
}
function _getDestination(Pythia1ProofData memory self) internal pure returns (address) {
return address(uint160(self.input[0]));
}
function _getChainId(Pythia1ProofData memory self) internal pure returns (uint256) {
return self.input[1];
}
function _getCommitmentMapperPubKey(
Pythia1ProofData memory self
) internal pure returns (uint256[2] memory) {
return [self.input[2], self.input[3]];
}
function _getGroupId(Pythia1ProofData memory self) internal pure returns (uint256) {
return self.input[4];
}
function _getExpectedExternalNullifier(
Pythia1ProofData memory self
) internal pure returns (uint256) {
return self.input[5];
}
function _getTicket(Pythia1ProofData memory self) internal pure returns (uint256) {
return self.input[6];
}
function _getValue(Pythia1ProofData memory self) internal pure returns (uint256) {
return self.input[7];
}
function _getIsStrict(Pythia1ProofData memory self) internal pure returns (bool) {
return self.input[8] == 1;
}
function _getTicket(bytes calldata self) internal pure returns (uint256) {
Pythia1ProofData memory snarkProofData = abi.decode(self, (Pythia1ProofData));
uint256 userTicket = uint256(_getTicket(snarkProofData));
return userTicket;
}
function _generateGroupIdFromProperties(
uint128 internalCollectionId,
bool isScore
) internal pure returns (uint256) {
return
_generateGroupIdFromEncodedProperties(_encodeGroupProperties(internalCollectionId, isScore));
}
function _generateGroupIdFromEncodedProperties(
bytes memory encodedProperties
) internal pure returns (uint256) {
return uint256(keccak256(encodedProperties)) % Pythia1Lib.SNARK_FIELD;
}
function _encodeGroupProperties(
uint128 internalCollectionId,
bool isScore
) internal pure returns (bytes memory) {
return abi.encode(internalCollectionId, isScore);
}
function _validateClaim(Claim memory claim) internal pure {
uint256 expectedGroupId = _generateGroupIdFromEncodedProperties(claim.extraData);
if (claim.groupId != expectedGroupId)
revert GroupIdAndPropertiesMismatch(expectedGroupId, claim.groupId);
}
}
================================================
FILE: contracts/core/AttestationsRegistry.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
import {IAttestationsRegistry} from './interfaces/IAttestationsRegistry.sol';
import {AttestationsRegistryConfigLogic} from './libs/attestations-registry/AttestationsRegistryConfigLogic.sol';
import {AttestationsRegistryState} from './libs/attestations-registry/AttestationsRegistryState.sol';
import {Range, RangeUtils} from './libs/utils/RangeLib.sol';
import {Attestation, AttestationData} from './libs/Structs.sol';
import {IBadges} from './interfaces/IBadges.sol';
/**
* @title Attestations Registry
* @author Sismo
* @notice Main contract of Sismo, stores all recorded attestations in attestations collections
* Only authorized attestations issuers can record attestation in the registry
* Attesters that expect to record in the Attestations Registry must be authorized issuers
* For more information: https://attestations-registry.docs.sismo.io
* For each attestation recorded, a badge is received by the user
* The badge is the Non transferrable NFT representation of an attestation
* Its ERC1155 contract is stateless, balances are read directly from the registry. Badge balances <=> Attestations values
* After the creation or update of an attestation, the registry triggers a TransferSingle event from the ERC1155 Badges contracts
* It enables off-chain apps such as opensea to catch the "shadow mint" of the badge
**/
contract AttestationsRegistry is
AttestationsRegistryState,
IAttestationsRegistry,
AttestationsRegistryConfigLogic
{
uint8 public constant IMPLEMENTATION_VERSION = 3;
IBadges immutable BADGES;
/**
* @dev Constructor.
* @param owner Owner of the contract, has the right to authorize/unauthorize attestations issuers
* @param badgesAddress Stateless ERC1155 Badges contract
*/
constructor(address owner, address badgesAddress) {
BADGES = IBadges(badgesAddress);
initialize(owner);
}
/**
* @dev Initialize function, to be called by the proxy delegating calls to this implementation
* @param ownerAddress Owner of the contract, has the right to authorize/unauthorize attestations issuers
* @notice The reinitializer modifier is needed to configure modules that are added through upgrades and that require initialization.
*/
function initialize(address ownerAddress) public reinitializer(IMPLEMENTATION_VERSION) {
// if proxy did not setup owner yet or if called by constructor (for implem setup)
if (owner() == address(0) || address(this).code.length == 0) {
_transferOwnership(ownerAddress);
}
}
/**
* @dev Main function to be called by authorized issuers
* @param attestations Attestations to be recorded (creates a new one or overrides an existing one)
*/
function recordAttestations(Attestation[] calldata attestations) external override whenNotPaused {
address issuer = _msgSender();
for (uint256 i = 0; i < attestations.length; i++) {
if (!_isAuthorized(issuer, attestations[i].collectionId))
revert IssuerNotAuthorized(issuer, attestations[i].collectionId);
uint256 previousAttestationValue = _attestationsData[attestations[i].collectionId][
attestations[i].owner
].value;
_attestationsData[attestations[i].collectionId][attestations[i].owner] = AttestationData(
attestations[i].issuer,
attestations[i].value,
attestations[i].timestamp,
attestations[i].extraData
);
_triggerBadgeTransferEvent(
attestations[i].collectionId,
attestations[i].owner,
previousAttestationValue,
attestations[i].value
);
emit AttestationRecorded(attestations[i]);
}
}
/**
* @dev Delete function to be called by authorized issuers
* @param owners The owners of the attestations to be deleted
* @param collectionIds The collection ids of the attestations to be deleted
*/
function deleteAttestations(
address[] calldata owners,
uint256[] calldata collectionIds
) external override whenNotPaused {
if (owners.length != collectionIds.length)
revert OwnersAndCollectionIdsLengthMismatch(owners, collectionIds);
address issuer = _msgSender();
for (uint256 i = 0; i < owners.length; i++) {
AttestationData memory attestationData = _attestationsData[collectionIds[i]][owners[i]];
if (!_isAuthorized(issuer, collectionIds[i]))
revert IssuerNotAuthorized(issuer, collectionIds[i]);
delete _attestationsData[collectionIds[i]][owners[i]];
_triggerBadgeTransferEvent(collectionIds[i], owners[i], attestationData.value, 0);
emit AttestationDeleted(
Attestation(
collectionIds[i],
owners[i],
attestationData.issuer,
attestationData.value,
attestationData.timestamp,
attestationData.extraData
)
);
}
}
/**
* @dev Returns whether a user has an attestation from a collection
* @param collectionId Collection identifier of the targeted attestation
* @param owner Owner of the targeted attestation
*/
function hasAttestation(
uint256 collectionId,
address owner
) external view override returns (bool) {
return _getAttestationValue(collectionId, owner) != 0;
}
/**
* @dev Getter of the data of a specific attestation
* @param collectionId Collection identifier of the targeted attestation
* @param owner Owner of the targeted attestation
*/
function getAttestationData(
uint256 collectionId,
address owner
) external view override returns (AttestationData memory) {
return _getAttestationData(collectionId, owner);
}
/**
* @dev Getter of the value of a specific attestation
* @param collectionId Collection identifier of the targeted attestation
* @param owner Owner of the targeted attestation
*/
function getAttestationValue(
uint256 collectionId,
address owner
) external view override returns (uint256) {
return _getAttestationValue(collectionId, owner);
}
/**
* @dev Getter of the data of a specific attestation as tuple
* @param collectionId Collection identifier of the targeted attestation
* @param owner Owner of the targeted attestation
*/
function getAttestationDataTuple(
uint256 collectionId,
address owner
) external view override returns (address, uint256, uint32, bytes memory) {
AttestationData memory attestationData = _attestationsData[collectionId][owner];
return (
attestationData.issuer,
attestationData.value,
attestationData.timestamp,
attestationData.extraData
);
}
/**
* @dev Getter of the extraData of a specific attestation
* @param collectionId Collection identifier of the targeted attestation
* @param owner Owner of the targeted attestation
*/
function getAttestationExtraData(
uint256 collectionId,
address owner
) external view override returns (bytes memory) {
return _attestationsData[collectionId][owner].extraData;
}
/**
* @dev Getter of the issuer of a specific attestation
* @param collectionId Collection identifier of the targeted attestation
* @param owner Owner of the targeted attestation
*/
function getAttestationIssuer(
uint256 collectionId,
address owner
) external view override returns (address) {
return _attestationsData[collectionId][owner].issuer;
}
/**
* @dev Getter of the timestamp of a specific attestation
* @param collectionId Collection identifier of the targeted attestation
* @param owner Owner of the targeted attestation
*/
function getAttestationTimestamp(
uint256 collectionId,
address owner
) external view override returns (uint32) {
return _attestationsData[collectionId][owner].timestamp;
}
/**
* @dev Getter of the data of specific attestations
* @param collectionIds Collection identifiers of the targeted attestations
* @param owners Owners of the targeted attestations
*/
function getAttestationDataBatch(
uint256[] memory collectionIds,
address[] memory owners
) external view override returns (AttestationData[] memory) {
AttestationData[] memory attestationsDataArray = new AttestationData[](collectionIds.length);
for (uint256 i = 0; i < collectionIds.length; i++) {
attestationsDataArray[i] = _getAttestationData(collectionIds[i], owners[i]);
}
return attestationsDataArray;
}
/**
* @dev Getter of the values of specific attestations
* @param collectionIds Collection identifiers of the targeted attestations
* @param owners Owners of the targeted attestations
*/
function getAttestationValueBatch(
uint256[] memory collectionIds,
address[] memory owners
) external view override returns (uint256[] memory) {
uint256[] memory attestationsValues = new uint256[](collectionIds.length);
for (uint256 i = 0; i < collectionIds.length; i++) {
attestationsValues[i] = _getAttestationValue(collectionIds[i], owners[i]);
}
return attestationsValues;
}
/**
* @dev Function that trigger a TransferSingle event from the stateless ERC1155 Badges contract
* It enables off-chain apps such as opensea to catch the "shadow mints/burns" of badges
*/
function _triggerBadgeTransferEvent(
uint256 badgeTokenId,
address owner,
uint256 previousValue,
uint256 newValue
) internal {
bool isGreaterValue = newValue > previousValue;
address operator = address(this);
address from = isGreaterValue ? address(0) : owner;
address to = isGreaterValue ? owner : address(0);
uint256 value = isGreaterValue ? newValue - previousValue : previousValue - newValue;
// if isGreaterValue is true, function triggers mint event. Otherwise triggers burn event.
BADGES.triggerTransferEvent(operator, from, to, badgeTokenId, value);
}
function _getAttestationData(
uint256 collectionId,
address owner
) internal view returns (AttestationData memory) {
return (_attestationsData[collectionId][owner]);
}
function _getAttestationValue(
uint256 collectionId,
address owner
) internal view returns (uint256) {
return _attestationsData[collectionId][owner].value;
}
}
================================================
FILE: contracts/core/Attester.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
import {IAttester} from './interfaces/IAttester.sol';
import {IAttestationsRegistry} from './interfaces/IAttestationsRegistry.sol';
import {Request, Attestation, AttestationData} from './libs/Structs.sol';
/**
* @title Attester Abstract Contract
* @author Sismo
* @notice Contract to be inherited by Attesters
* All attesters that expect to be authorized in Sismo Protocol (i.e write access on the registry)
* are recommended to implemented this abstract contract
* Take a look at the HydraS1SimpleAttester.sol for example on how to implement this abstract contract
*
* This contracts is built around two main external standard functions.
* They must NOT be override them, unless your really know what you are doing
* - generateAttestations(request, proof) => will write attestations in the registry
* 1. (MANDATORY) Implement the buildAttestations() view function which generate attestations from user request
* 2. (MANDATORY) Implement teh _verifyRequest() internal function where to write checks
* 3. (OPTIONAL) Override _beforeRecordAttestations and _afterRecordAttestations hooks
* - deleteAttestations(collectionId, owner, proof) => will delete attestations in the registry
* 1. (DEFAULT) By default this function throws (see _verifyAttestationsDeletionRequest)
* 2. (OPTIONAL) Override the _verifyAttestationsDeletionRequest so it no longer throws
* 3. (OPTIONAL) Override _beforeDeleteAttestations and _afterDeleteAttestations hooks
* For more information: https://attesters.docs.sismo.io
**/
abstract contract Attester is IAttester {
// Registry where all attestations are stored
IAttestationsRegistry internal immutable ATTESTATIONS_REGISTRY;
/**
* @dev Constructor
* @param attestationsRegistryAddress The address of the AttestationsRegistry contract storing attestations
*/
constructor(address attestationsRegistryAddress) {
ATTESTATIONS_REGISTRY = IAttestationsRegistry(attestationsRegistryAddress);
}
/**
* @dev Main external function. Allows to generate attestations by making a request and submitting proof
* @param request User request
* @param proofData Data sent along the request to prove its validity
* @return attestations Attestations that has been recorded
*/
function generateAttestations(
Request calldata request,
bytes calldata proofData
) public override returns (Attestation[] memory) {
// Verify if request is valid by verifying against proof
_verifyRequest(request, proofData);
// Generate the actual attestations from user request
Attestation[] memory attestations = buildAttestations(request, proofData);
_beforeRecordAttestations(request, proofData);
ATTESTATIONS_REGISTRY.recordAttestations(attestations);
_afterRecordAttestations(attestations);
for (uint256 i = 0; i < attestations.length; i++) {
emit AttestationGenerated(attestations[i]);
}
return attestations;
}
/**
* @dev High level function to generate attestations by making a request and submitting proof
* @param request User request
* @param proofData Data sent along the request to prove its validity
* @return badges owner, badges tokenIds and badges values
*/
function mintBadges(
Request calldata request,
bytes calldata proofData
) external returns (address, uint256[] memory, uint256[] memory) {
Attestation[] memory attestations = generateAttestations(request, proofData);
uint256[] memory collectionIds = new uint256[](attestations.length);
uint256[] memory values = new uint256[](attestations.length);
for (uint256 i = 0; i < attestations.length; i++) {
collectionIds[i] = attestations[i].collectionId;
values[i] = attestations[i].value;
}
return (attestations[0].owner, collectionIds, values);
}
/**
* @dev External facing function. Allows to delete attestations by submitting proof
* @param collectionIds Collection identifier of attestations to delete
* @param attestationsOwner Owner of attestations to delete
* @param proofData Data sent along the deletion request to prove its validity
* @return attestations Attestations that were deleted
*/
function deleteAttestations(
uint256[] calldata collectionIds,
address attestationsOwner,
bytes calldata proofData
) external override returns (Attestation[] memory) {
address[] memory attestationOwners = new address[](collectionIds.length);
uint256[] memory attestationCollectionIds = new uint256[](collectionIds.length);
Attestation[] memory attestations = new Attestation[](collectionIds.length);
for (uint256 i = 0; i < collectionIds.length; i++) {
// fetch attestations from the registry
(
address issuer,
uint256 attestationValue,
uint32 timestamp,
bytes memory extraData
) = ATTESTATIONS_REGISTRY.getAttestationDataTuple(collectionIds[i], attestationsOwner);
attestationOwners[i] = attestationsOwner;
attestationCollectionIds[i] = collectionIds[i];
attestations[i] = (
Attestation(
collectionIds[i],
attestationsOwner,
issuer,
attestationValue,
timestamp,
extraData
)
);
}
_verifyAttestationsDeletionRequest(attestations, proofData);
_beforeDeleteAttestations(attestations, proofData);
ATTESTATIONS_REGISTRY.deleteAttestations(attestationOwners, attestationCollectionIds);
_afterDeleteAttestations(attestations, proofData);
for (uint256 i = 0; i < collectionIds.length; i++) {
emit AttestationDeleted(attestations[i]);
}
return attestations;
}
/**
* @dev MANDATORY: must be implemented in attesters
* It should build attestations from the user request and the proof
* @param request User request
* @param proofData Data sent along the request to prove its validity
* @return attestations Attestations that will be recorded
*/
function buildAttestations(
Request calldata request,
bytes calldata proofData
) public view virtual returns (Attestation[] memory);
/**
* @dev Attestation registry getter
* @return attestationRegistry
*/
function getAttestationRegistry() external view override returns (IAttestationsRegistry) {
return ATTESTATIONS_REGISTRY;
}
/**
* @dev MANDATORY: must be implemented in attesters
* It should verify the user request is valid
* @param request User request
* @param proofData Data sent along the request to prove its validity
*/
function _verifyRequest(Request calldata request, bytes calldata proofData) internal virtual;
/**
* @dev Optional: must be overridden by attesters that want to feature attestations deletion
* Default behavior: throws
* It should verify attestations deletion request is valid
* @param attestations Attestations that will be deleted
* @param proofData Data sent along the request to prove its validity
*/
function _verifyAttestationsDeletionRequest(
Attestation[] memory attestations,
bytes calldata proofData
) internal virtual {
revert AttestationDeletionNotImplemented();
}
/**
* @dev Optional: Hook, can be overridden in attesters
* Will be called before recording attestations in the registry
* @param request User request
* @param proofData Data sent along the request to prove its validity
*/
function _beforeRecordAttestations(
Request calldata request,
bytes calldata proofData
) internal virtual {}
/**
* @dev (Optional) Can be overridden in attesters inheriting this contract
* Will be called after recording an attestation
* @param attestations Recorded attestations
*/
function _afterRecordAttestations(Attestation[] memory attestations) internal virtual {}
/**
* @dev Optional: Hook, can be overridden in attesters
* Will be called before deleting attestations from the registry
* @param attestations Attestations to delete
* @param proofData Data sent along the deletion request to prove its validity
*/
function _beforeDeleteAttestations(
Attestation[] memory attestations,
bytes calldata proofData
) internal virtual {}
/**
* @dev Optional: Hook, can be overridden in attesters
* Will be called after deleting attestations from the registry
* @param attestations Attestations to delete
* @param proofData Data sent along the deletion request to prove its validity
*/
function _afterDeleteAttestations(
Attestation[] memory attestations,
bytes calldata proofData
) internal virtual {}
}
================================================
FILE: contracts/core/Badges.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
import {ERC1155} from '@openzeppelin/contracts/token/ERC1155/ERC1155.sol';
import {Initializable} from '@openzeppelin/contracts/proxy/utils/Initializable.sol';
import {ERC1155Pausable} from '@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Pausable.sol';
import {AccessControl} from '@openzeppelin/contracts/access/AccessControl.sol';
import {IAttestationsRegistry} from './interfaces/IAttestationsRegistry.sol';
import {IBadges} from './interfaces/IBadges.sol';
/**
* @title Badges contract
* @author Sismo
* @notice Stateless, Non-transferrable ERC1155 contract. Reads balance from the values of attestations
* The associated attestations registry triggers TransferSingle events from this contract
* It allows badge "shadow mints and burns" to be caught by off-chain platforms
* For more information: https://badges.docs.sismo.io
*/
contract Badges is IBadges, Initializable, AccessControl, ERC1155 {
uint8 public constant IMPLEMENTATION_VERSION = 3;
IAttestationsRegistry internal _attestationsRegistry;
bytes32 public constant EVENT_TRIGGERER_ROLE = keccak256('EVENT_TRIGGERER_ROLE');
/**
* @dev Constructor
* @param uri Uri for the metadata of badges
* @param owner Owner of the contract, super admin, can setup roles and update the attestation registry
*/
constructor(
string memory uri,
address owner // This is Sismo Frontend Contract
) ERC1155(uri) {
initialize(uri, owner);
}
/**
* @dev Initializes the contract, to be called by the proxy delegating calls to this implementation
* @param uri Uri for the metadata of badges
* @param owner Owner of the contract, super admin, can setup roles and update the attestation registry
* @notice The reinitializer modifier is needed to configure modules that are added through upgrades and that require initialization.
*/
function initialize(
string memory uri,
address owner
) public reinitializer(IMPLEMENTATION_VERSION) {
// if proxy did not setup uri yet or if called by constructor (for implem setup)
if (bytes(ERC1155.uri(0)).length == 0 || address(this).code.length == 0) {
_setURI(uri);
_grantRole(DEFAULT_ADMIN_ROLE, owner);
}
}
/**
* @dev Main function of the ERC1155 badge
* The balance of a user is equal to the value of the underlying attestation.
* attestationCollectionId == badgeId
* @param account Address to check badge balance (= value of attestation)
* @param id Badge Id to check (= attestationCollectionId)
*/
function balanceOf(
address account,
uint256 id
) public view virtual override(ERC1155, IBadges) returns (uint256) {
return _attestationsRegistry.getAttestationValue(id, account);
}
/**
* @dev Reverts, this is a non transferable ERC115 contract
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
revert BadgesNonTransferrable();
}
/**
* @dev Reverts, this is a non transferable ERC115 contract
*/
function isApprovedForAll(
address account,
address operator
) public view virtual override returns (bool) {
revert BadgesNonTransferrable();
}
/**
* @dev Emits a TransferSingle event, so subgraphs and other off-chain apps relying on events can see badge minting/burning
* can only be called by address having the EVENT_TRIGGERER_ROLE (attestations registry address)
* @param operator who is calling the TransferEvent
* @param from address(0) if minting, address of the badge holder if burning
* @param to address of the badge holder is minting, address(0) if burning
* @param id badgeId for which to trigger the event
* @param value minted/burned balance
*/
function triggerTransferEvent(
address operator,
address from,
address to,
uint256 id,
uint256 value
) external onlyRole(EVENT_TRIGGERER_ROLE) {
emit TransferSingle(operator, from, to, id, value);
}
/**
* @dev Set the attestations registry address. Can only be called by owner (default admin)
* @param attestationsRegistry new attestations registry address
*/
function setAttestationsRegistry(
address attestationsRegistry
) external override onlyRole(DEFAULT_ADMIN_ROLE) {
_attestationsRegistry = IAttestationsRegistry(attestationsRegistry);
}
/**
* @dev Set the URI. Can only be called by owner (default admin)
* @param uri new attestations registry address
*/
function setUri(string memory uri) external override onlyRole(DEFAULT_ADMIN_ROLE) {
_setURI(uri);
}
/**
* @dev Getter of the attestations registry
*/
function getAttestationsRegistry() external view override returns (address) {
return address(_attestationsRegistry);
}
/**
* @dev Getter of the badge issuer
* @param account Address that holds the badge
* @param id Badge Id to check (= attestationCollectionId)
*/
function getBadgeIssuer(address account, uint256 id) external view returns (address) {
return _attestationsRegistry.getAttestationIssuer(id, account);
}
/**
* @dev Getter of the badge timestamp
* @param account Address that holds the badge
* @param id Badge Id to check (= attestationCollectionId)
*/
function getBadgeTimestamp(address account, uint256 id) external view returns (uint32) {
return _attestationsRegistry.getAttestationTimestamp(id, account);
}
/**
* @dev Getter of the badge extra data (it can store nullifier and burnCount)
* @param account Address that holds the badge
* @param id Badge Id to check (= attestationCollectionId)
*/
function getBadgeExtraData(address account, uint256 id) external view returns (bytes memory) {
return _attestationsRegistry.getAttestationExtraData(id, account);
}
/**
* @dev Getter of the value of a specific badge attribute
* @param id Badge Id to check (= attestationCollectionId)
* @param index Index of the attribute
*/
function getAttributeValueForBadge(uint256 id, uint8 index) external view returns (uint8) {
return _attestationsRegistry.getAttributeValueForAttestationsCollection(id, index);
}
/**
* @dev Getter of all badge attributes and their values for a specific badge
* @param id Badge Id to check (= attestationCollectionId)
*/
function getAttributesNamesAndValuesForBadge(
uint256 id
) external view returns (bytes32[] memory, uint8[] memory) {
return _attestationsRegistry.getAttributesNamesAndValuesForAttestationsCollection(id);
}
/**
* @dev ERC165
*/
function supportsInterface(
bytes4 interfaceId
) public view virtual override(AccessControl, ERC1155) returns (bool) {
return super.supportsInterface(interfaceId);
}
/**
* @dev Reverts, this is a non transferable ERC115 contract
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
revert BadgesNonTransferrable();
}
}
================================================
FILE: contracts/core/Front.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
import {IFront} from './interfaces/IFront.sol';
import {IAttester} from './interfaces/IAttester.sol';
import {IAttestationsRegistry} from './interfaces/IAttestationsRegistry.sol';
import {Request, Attestation} from './libs/Structs.sol';
/**
* @title Front
* @author Sismo
* @notice This is the Front contract of the Sismo protocol
* Behind a proxy, it routes attestations request to the targeted attester and can perform some actions
* This specific implementation rewards early users with a early user attestation if they used sismo before ethcc conference
* For more information: https://front.docs.sismo.io
*/
contract Front is IFront {
IAttestationsRegistry public immutable ATTESTATIONS_REGISTRY;
uint256 public constant EARLY_USER_COLLECTION = 0;
uint32 public constant EARLY_USER_BADGE_END_DATE = 1663200000; // Sept 15
/**
* @dev Constructor
* @param attestationsRegistryAddress Attestations registry contract address
*/
constructor(address attestationsRegistryAddress) {
ATTESTATIONS_REGISTRY = IAttestationsRegistry(attestationsRegistryAddress);
}
/**
* @dev Forward a request to an attester and generates an early user attestation
* @param attester Attester targeted by the request
* @param request Request sent to the attester
* @param proofData Data provided to the attester to back the request
*/
function generateAttestations(
address attester,
Request calldata request,
bytes calldata proofData
) external override returns (Attestation[] memory) {
Attestation[] memory attestations = _forwardAttestationsGeneration(
attester,
request,
proofData
);
_generateEarlyUserAttestation(request.destination);
return attestations;
}
/**
* @dev generate multiple attestations at once, to the same destination, generates an early user attestation
* @param attesters Attesters targeted by the attesters
* @param requests Requests sent to attester
* @param proofDataArray Data sent with each request
*/
function batchGenerateAttestations(
address[] calldata attesters,
Request[] calldata requests,
bytes[] calldata proofDataArray
) external override returns (Attestation[][] memory) {
Attestation[][] memory attestations = new Attestation[][](attesters.length);
address destination = requests[0].destination;
for (uint256 i = 0; i < attesters.length; i++) {
if (requests[i].destination != destination) revert DifferentRequestsDestinations();
attestations[i] = _forwardAttestationsGeneration(
attesters[i],
requests[i],
proofDataArray[i]
);
}
_generateEarlyUserAttestation(destination);
return attestations;
}
/**
* @dev build the attestations from a user request targeting a specific attester.
* Forwards to the build function of targeted attester
* @param attester Targeted attester
* @param request User request
* @param proofData Data sent along the request to prove its validity
* @return attestations Attestations that will be recorded
*/
function buildAttestations(
address attester,
Request calldata request,
bytes calldata proofData
) external view override returns (Attestation[] memory) {
return _forwardAttestationsBuild(attester, request, proofData);
}
/**
* @dev build the attestations from multiple user requests.
* Forwards to the build function of targeted attester
* @param attesters Targeted attesters
* @param requests User requests
* @param proofDataArray Data sent along the request to prove its validity
* @return attestations Attestations that will be recorded
*/
function batchBuildAttestations(
address[] calldata attesters,
Request[] calldata requests,
bytes[] calldata proofDataArray
) external view override returns (Attestation[][] memory) {
Attestation[][] memory attestations = new Attestation[][](attesters.length);
for (uint256 i = 0; i < attesters.length; i++) {
attestations[i] = _forwardAttestationsBuild(attesters[i], requests[i], proofDataArray[i]);
}
return attestations;
}
function _forwardAttestationsBuild(
address attester,
Request calldata request,
bytes calldata proofData
) internal view returns (Attestation[] memory) {
return IAttester(attester).buildAttestations(request, proofData);
}
function _forwardAttestationsGeneration(
address attester,
Request calldata request,
bytes calldata proofData
) internal returns (Attestation[] memory) {
return IAttester(attester).generateAttestations(request, proofData);
}
function _generateEarlyUserAttestation(address destination) internal {
uint32 currentTimestamp = uint32(block.timestamp);
if (currentTimestamp < EARLY_USER_BADGE_END_DATE) {
bool alreadyHasAttestation = ATTESTATIONS_REGISTRY.hasAttestation(
EARLY_USER_COLLECTION,
destination
);
if (!alreadyHasAttestation) {
Attestation[] memory attestations = new Attestation[](1);
attestations[0] = Attestation(
EARLY_USER_COLLECTION,
destination,
address(this),
1,
currentTimestamp,
'With strong love from Sismo'
);
ATTESTATIONS_REGISTRY.recordAttestations(attestations);
emit EarlyUserAttestationGenerated(destination);
}
}
}
}
================================================
FILE: contracts/core/interfaces/IAttestationsRegistry.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
import {Attestation, AttestationData} from '../libs/Structs.sol';
import {IAttestationsRegistryConfigLogic} from './IAttestationsRegistryConfigLogic.sol';
/**
* @title IAttestationsRegistry
* @author Sismo
* @notice This is the interface of the AttestationRegistry
*/
interface IAttestationsRegistry is IAttestationsRegistryConfigLogic {
error IssuerNotAuthorized(address issuer, uint256 collectionId);
error OwnersAndCollectionIdsLengthMismatch(address[] owners, uint256[] collectionIds);
event AttestationRecorded(Attestation attestation);
event AttestationDeleted(Attestation attestation);
/**
* @dev Main function to be called by authorized issuers
* @param attestations Attestations to be recorded (creates a new one or overrides an existing one)
*/
function recordAttestations(Attestation[] calldata attestations) external;
/**
* @dev Delete function to be called by authorized issuers
* @param owners The owners of the attestations to be deleted
* @param collectionIds The collection ids of the attestations to be deleted
*/
function deleteAttestations(address[] calldata owners, uint256[] calldata collectionIds) external;
/**
* @dev Returns whether a user has an attestation from a collection
* @param collectionId Collection identifier of the targeted attestation
* @param owner Owner of the targeted attestation
*/
function hasAttestation(uint256 collectionId, address owner) external returns (bool);
/**
* @dev Getter of the data of a specific attestation
* @param collectionId Collection identifier of the targeted attestation
* @param owner Owner of the targeted attestation
*/
function getAttestationData(
uint256 collectionId,
address owner
) external view returns (AttestationData memory);
/**
* @dev Getter of the value of a specific attestation
* @param collectionId Collection identifier of the targeted attestation
* @param owner Owner of the targeted attestation
*/
function getAttestationValue(uint256 collectionId, address owner) external view returns (uint256);
/**
* @dev Getter of the data of a specific attestation as tuple
* @param collectionId Collection identifier of the targeted attestation
* @param owner Owner of the targeted attestation
*/
function getAttestationDataTuple(
uint256 collectionId,
address owner
) external view returns (address, uint256, uint32, bytes memory);
/**
* @dev Getter of the extraData of a specific attestation
* @param collectionId Collection identifier of the targeted attestation
* @param owner Owner of the targeted attestation
*/
function getAttestationExtraData(
uint256 collectionId,
address owner
) external view returns (bytes memory);
/**
* @dev Getter of the issuer of a specific attestation
* @param collectionId Collection identifier of the targeted attestation
* @param owner Owner of the targeted attestation
*/
function getAttestationIssuer(
uint256 collectionId,
address owner
) external view returns (address);
/**
* @dev Getter of the timestamp of a specific attestation
* @param collectionId Collection identifier of the targeted attestation
* @param owner Owner of the targeted attestation
*/
function getAttestationTimestamp(
uint256 collectionId,
address owner
) external view returns (uint32);
/**
* @dev Getter of the data of specific attestations
* @param collectionIds Collection identifiers of the targeted attestations
* @param owners Owners of the targeted attestations
*/
function getAttestationDataBatch(
uint256[] memory collectionIds,
address[] memory owners
) external view returns (AttestationData[] memory);
/**
* @dev Getter of the values of specific attestations
* @param collectionIds Collection identifiers of the targeted attestations
* @param owners Owners of the targeted attestations
*/
function getAttestationValueBatch(
uint256[] memory collectionIds,
address[] memory owners
) external view returns (uint256[] memory);
}
================================================
FILE: contracts/core/interfaces/IAttestationsRegistryConfigLogic.sol
================================================
// SPDX-License-Identifier: MIT
// Forked from, removed storage, OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.14;
import {Range, RangeUtils} from '../libs/utils/RangeLib.sol';
interface IAttestationsRegistryConfigLogic {
error AttesterNotFound(address issuer);
error RangeIndexOutOfBounds(address issuer, uint256 expectedArrayLength, uint256 rangeIndex);
error IdsMismatch(
address issuer,
uint256 rangeIndex,
uint256 expectedFirstId,
uint256 expectedLastId,
uint256 FirstId,
uint256 lastCollectionId
);
error AttributeDoesNotExist(uint8 attributeIndex);
error AttributeAlreadyExists(uint8 attributeIndex);
error ArgsLengthDoesNotMatch();
event NewAttributeCreated(uint8 attributeIndex, bytes32 attributeName);
event AttributeNameUpdated(
uint8 attributeIndex,
bytes32 newAttributeName,
bytes32 previousAttributeName
);
event AttributeDeleted(uint8 attributeIndex, bytes32 deletedAttributeName);
event AttestationsCollectionAttributeSet(
uint256 collectionId,
uint8 attributeIndex,
uint8 attributeValue
);
event IssuerAuthorized(address issuer, uint256 firstCollectionId, uint256 lastCollectionId);
event IssuerUnauthorized(address issuer, uint256 firstCollectionId, uint256 lastCollectionId);
/**
* @dev Returns whether an attestationsCollection has a specific attribute referenced by its index
* @param collectionId Collection Id of the targeted attestationsCollection
* @param index Index of the attribute. Can go from 0 to 63.
*/
function attestationsCollectionHasAttribute(
uint256 collectionId,
uint8 index
) external view returns (bool);
function attestationsCollectionHasAttributes(
uint256 collectionId,
uint8[] memory indices
) external view returns (bool);
/**
* @dev Returns the attribute's value (from 1 to 15) of an attestationsCollection
* @param collectionId Collection Id of the targeted attestationsCollection
* @param attributeIndex Index of the attribute. Can go from 0 to 63.
*/
function getAttributeValueForAttestationsCollection(
uint256 collectionId,
uint8 attributeIndex
) external view returns (uint8);
function getAttributesValuesForAttestationsCollection(
uint256 collectionId,
uint8[] memory indices
) external view returns (uint8[] memory);
/**
* @dev Set a value for an attribute of an attestationsCollection. The attribute should already be created.
* @param collectionId Collection Id of the targeted attestationsCollection
* @param index Index of the attribute (must be between 0 and 63)
* @param value Value of the attribute we want to set for this attestationsCollection. Can take the value 0 to 15
*/
function setAttributeValueForAttestationsCollection(
uint256 collectionId,
uint8 index,
uint8 value
) external;
function setAttributesValuesForAttestationsCollections(
uint256[] memory collectionIds,
uint8[] memory indices,
uint8[] memory values
) external;
/**
* @dev Returns all the enabled attributes names and their values for a specific attestationsCollection
* @param collectionId Collection Id of the targeted attestationsCollection
*/
function getAttributesNamesAndValuesForAttestationsCollection(
uint256 collectionId
) external view returns (bytes32[] memory, uint8[] memory);
/**
* @dev Authorize an issuer for a specific range
* @param issuer Issuer that will be authorized
* @param firstCollectionId First collection Id of the range for which the issuer will be authorized
* @param lastCollectionId Last collection Id of the range for which the issuer will be authorized
*/
function authorizeRange(
address issuer,
uint256 firstCollectionId,
uint256 lastCollectionId
) external;
/**
* @dev Unauthorize an issuer for a specific range
* @param issuer Issuer that will be unauthorized
* @param rangeIndex Index of the range to be unauthorized
* @param firstCollectionId First collection Id of the range for which the issuer will be unauthorized
* @param lastCollectionId Last collection Id of the range for which the issuer will be unauthorized
*/
function unauthorizeRange(
address issuer,
uint256 rangeIndex,
uint256 firstCollectionId,
uint256 lastCollectionId
) external;
/**
* @dev Authorize an issuer for specific ranges
* @param issuer Issuer that will be authorized
* @param ranges Ranges for which the issuer will be authorized
*/
function authorizeRanges(address issuer, Range[] memory ranges) external;
/**
* @dev Unauthorize an issuer for specific ranges
* @param issuer Issuer that will be unauthorized
* @param ranges Ranges for which the issuer will be unauthorized
*/
function unauthorizeRanges(
address issuer,
Range[] memory ranges,
uint256[] memory rangeIndexes
) external;
/**
* @dev Returns whether a specific issuer is authorized or not to record in a specific attestations collection
* @param issuer Issuer to be checked
* @param collectionId Collection Id for which the issuer will be checked
*/
function isAuthorized(address issuer, uint256 collectionId) external view returns (bool);
/**
* @dev Pauses the registry. Issuers can no longer record or delete attestations
*/
function pause() external;
/**
* @dev Unpauses the registry
*/
function unpause() external;
/**
* @dev Create a new attribute.
* @param index Index of the attribute. Can go from 0 to 63.
* @param name Name in bytes32 of the attribute
*/
function createNewAttribute(uint8 index, bytes32 name) external;
function createNewAttributes(uint8[] memory indices, bytes32[] memory names) external;
/**
* @dev Update the name of an existing attribute
* @param index Index of the attribute. Can go from 0 to 63. The attribute must exist
* @param newName new name in bytes32 of the attribute
*/
function updateAttributeName(uint8 index, bytes32 newName) external;
function updateAttributesName(uint8[] memory indices, bytes32[] memory names) external;
/**
* @dev Delete an existing attribute
* @param index Index of the attribute. Can go from 0 to 63. The attribute must exist
*/
function deleteAttribute(uint8 index) external;
function deleteAttributes(uint8[] memory indices) external;
}
================================================
FILE: contracts/core/interfaces/IAttester.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
import {Request, Attestation} from '../libs/Structs.sol';
import {IAttestationsRegistry} from '../interfaces/IAttestationsRegistry.sol';
/**
* @title IAttester
* @author Sismo
* @notice This is the interface for the attesters in Sismo Protocol
*/
interface IAttester {
event AttestationGenerated(Attestation attestation);
event AttestationDeleted(Attestation attestation);
error AttestationDeletionNotImplemented();
/**
* @dev Main external function. Allows to generate attestations by making a request and submitting proof
* @param request User request
* @param proofData Data sent along the request to prove its validity
* @return attestations Attestations that has been recorded
*/
function generateAttestations(
Request calldata request,
bytes calldata proofData
) external returns (Attestation[] memory);
/**
* @dev High level function to generate attestations by making a request and submitting proof
* @param request User request
* @param proofData Data sent along the request to prove its validity
* @return badges owner, badges tokenIds and badges values
*/
function mintBadges(
Request calldata request,
bytes calldata proofData
) external returns (address, uint256[] memory, uint256[] memory);
/**
* @dev External facing function. Allows to delete an attestation by submitting proof
* @param collectionIds Collection identifier of attestations to delete
* @param attestationsOwner Owner of attestations to delete
* @param proofData Data sent along the deletion request to prove its validity
* @return attestations Attestations that was deleted
*/
function deleteAttestations(
uint256[] calldata collectionIds,
address attestationsOwner,
bytes calldata proofData
) external returns (Attestation[] memory);
/**
* @dev MANDATORY: must be implemented in attesters
* It should build attestations from the user request and the proof
* @param request User request
* @param proofData Data sent along the request to prove its validity
* @return attestations Attestations that will be recorded
*/
function buildAttestations(
Request calldata request,
bytes calldata proofData
) external view returns (Attestation[] memory);
/**
* @dev Attestation registry address getter
* @return attestationRegistry Address of the registry
*/
function getAttestationRegistry() external view returns (IAttestationsRegistry);
}
================================================
FILE: contracts/core/interfaces/IBadges.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
/**
* @title Interface for Badges contract
* @author Sismo
* @notice Stateless ERC1155 contract. Reads balance from the values of attestations
* The associated attestations registry triggers TransferSingle events from this contract
* It allows badge "shadow mints and burns" to be caught by off-chain platforms
*/
interface IBadges {
error BadgesNonTransferrable();
/**
* @dev Initializes the contract, to be called by the proxy delegating calls to this implementation
* @param uri Uri for the metadata of badges
* @param owner Owner of the contract, super admin, can setup roles and update the attestation registry
* @notice The reinitializer modifier is needed to configure modules that are added through upgrades and that require initialization.
*/
function initialize(string memory uri, address owner) external;
/**
* @dev Main function of the ERC1155 badge
* The balance of a user is equal to the value of the underlying attestation.
* attestationCollectionId == badgeId
* @param account Address to check badge balance (= value of attestation)
* @param id Badge Id to check (= attestationCollectionId)
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev Emits a TransferSingle event, so subgraphs and other off-chain apps relying on events can see badge minting/burning
* can only be called by address having the EVENT_TRIGGERER_ROLE (attestations registry address)
* @param operator who is calling the TransferEvent
* @param from address(0) if minting, address of the badge holder if burning
* @param to address of the badge holder is minting, address(0) if burning
* @param id badgeId for which to trigger the event
* @param value minted/burned balance
*/
function triggerTransferEvent(
address operator,
address from,
address to,
uint256 id,
uint256 value
) external;
/**
* @dev Set the attestations registry address. Can only be called by owner (default admin)
* @param attestationsRegistry new attestations registry address
*/
function setAttestationsRegistry(address attestationsRegistry) external;
/**
* @dev Set the URI. Can only be called by owner (default admin)
* @param uri new attestations registry address
*/
function setUri(string memory uri) external;
/**
* @dev Getter of the attestations registry
*/
function getAttestationsRegistry() external view returns (address);
/**
* @dev Getter of the badge issuer
* @param account Address that holds the badge
* @param id Badge Id to check (= attestationCollectionId)
*/
function getBadgeIssuer(address account, uint256 id) external view returns (address);
/**
* @dev Getter of the badge timestamp
* @param account Address that holds the badge
* @param id Badge Id to check (= attestationCollectionId)
*/
function getBadgeTimestamp(address account, uint256 id) external view returns (uint32);
/**
* @dev Getter of the badge extra data (it can store nullifier and burnCount)
* @param account Address that holds the badge
* @param id Badge Id to check (= attestationCollectionId)
*/
function getBadgeExtraData(address account, uint256 id) external view returns (bytes memory);
/**
* @dev Getter of the value of a specific badge attribute
* @param id Badge Id to check (= attestationCollectionId)
* @param index Index of the attribute
*/
function getAttributeValueForBadge(uint256 id, uint8 index) external view returns (uint8);
/**
* @dev Getter of all badge attributes and their values for a specific badge
* @param id Badge Id to check (= attestationCollectionId)
*/
function getAttributesNamesAndValuesForBadge(
uint256 id
) external view returns (bytes32[] memory, uint8[] memory);
}
================================================
FILE: contracts/core/interfaces/IFront.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
import {Request, Attestation} from '../libs/Structs.sol';
/**
* @title IFront
* @author Sismo
* @notice This is the interface of the Front Contract
*/
interface IFront {
error DifferentRequestsDestinations();
event EarlyUserAttestationGenerated(address destination);
/**
* @dev Forward a request to an attester and generates an early user attestation
* @param attester Attester targeted by the request
* @param request Request sent to the attester
* @param proofData Data provided to the attester to back the request
*/
function generateAttestations(
address attester,
Request calldata request,
bytes calldata proofData
) external returns (Attestation[] memory);
/**
* @dev generate multiple attestations at once, to the same destination
* @param attesters Attesters targeted by the attesters
* @param requests Requests sent to attester
* @param proofDataArray Data sent with each request
*/
function batchGenerateAttestations(
address[] calldata attesters,
Request[] calldata requests,
bytes[] calldata proofDataArray
) external returns (Attestation[][] memory);
/**
* @dev build the attestations from a user request targeting a specific attester.
* Forwards to the build function of targeted attester
* @param attester Targeted attester
* @param request User request
* @param proofData Data sent along the request to prove its validity
* @return attestations Attestations that will be recorded
*/
function buildAttestations(
address attester,
Request calldata request,
bytes calldata proofData
) external view returns (Attestation[] memory);
/**
* @dev build the attestations from multiple user requests.
* Forwards to the build function(s) of targeted attester(s)
* @param attesters Targeted attesters
* @param requests User requests
* @param proofDataArray Data sent along the request to prove its validity
* @return attestations Attestations that will be recorded
*/
function batchBuildAttestations(
address[] calldata attesters,
Request[] calldata requests,
bytes[] calldata proofDataArray
) external view returns (Attestation[][] memory);
}
================================================
FILE: contracts/core/libs/Structs.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
/**
* @title Attestations Registry State
* @author Sismo
* @notice This contract holds all of the storage variables and data
* structures used by the AttestationsRegistry and parent
* contracts.
*/
// User Attestation Request, can be made by any user
// The context of an Attestation Request is a specific attester contract
// Each attester has groups of accounts in its available data
// eg: for a specific attester:
// group 1 <=> accounts that sent txs on mainnet
// group 2 <=> accounts that sent txs on polygon
// eg: for another attester:
// group 1 <=> accounts that sent eth txs in 2022
// group 2 <=> accounts sent eth txs in 2021
struct Request {
// implicit address attester;
// implicit uint256 chainId;
Claim[] claims;
address destination; // destination that will receive the end attestation
}
struct Claim {
uint256 groupId; // user claims to have an account in this group
uint256 claimedValue; // user claims this value for its account in the group
bytes extraData; // arbitrary data, may be required by the attester to verify claims or generate a specific attestation
}
/**
* @dev Attestation Struct. This is the struct receive as argument by the Attestation Registry.
* @param collectionId Attestation collection
* @param owner Attestation collection
* @param issuer Attestation collection
* @param value Attestation collection
* @param timestamp Attestation collection
* @param extraData Attestation collection
*/
struct Attestation {
// implicit uint256 chainId;
uint256 collectionId; // Id of the attestation collection (in the registry)
address owner; // Owner of the attestation
address issuer; // Contract that created or last updated the record.
uint256 value; // Value of the attestation
uint32 timestamp; // Timestamp chosen by the attester, should correspond to the effective date of the attestation
// it is different from the recording timestamp (date when the attestation was recorded)
// e.g a proof of NFT ownership may have be recorded today which is 2 month old data.
bytes extraData; // arbitrary data that can be added by the attester
}
// Attestation Data, stored in the registry
// The context is a specific owner of a specific collection
struct AttestationData {
// implicit uint256 chainId
// implicit uint256 collectionId - from context
// implicit owner
address issuer; // Address of the contract that recorded the attestation
uint256 value; // Value of the attestation
uint32 timestamp; // Effective date of issuance of the attestation. (can be different from the recording timestamp)
bytes extraData; // arbitrary data that can be added by the attester
}
================================================
FILE: contracts/core/libs/attestations-registry/AttestationsRegistryConfigLogic.sol
================================================
// SPDX-License-Identifier: MIT
// Forked from, removed storage, OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.14;
import './OwnableLogic.sol';
import './PausableLogic.sol';
import './InitializableLogic.sol';
import './AttestationsRegistryState.sol';
import {IAttestationsRegistryConfigLogic} from './../../interfaces/IAttestationsRegistryConfigLogic.sol';
import {Range, RangeUtils} from '../utils/RangeLib.sol';
import {Bitmap256Bit} from '../utils/Bitmap256Bit.sol';
/**
* @title Attestations Registry Config Logic contract
* @author Sismo
* @notice Holds the logic of how to authorize/ unauthorize issuers of attestations in the registry
**/
contract AttestationsRegistryConfigLogic is
AttestationsRegistryState,
IAttestationsRegistryConfigLogic,
OwnableLogic,
PausableLogic,
InitializableLogic
{
using RangeUtils for Range[];
using Bitmap256Bit for uint256;
using Bitmap256Bit for uint8;
/******************************************
*
* ATTESTATION REGISTRY WRITE ACCESS MANAGEMENT (ISSUERS)
*
*****************************************/
/**
* @dev Pauses the registry. Issuers can no longer record or delete attestations
*/
function pause() external override onlyOwner {
_pause();
}
/**
* @dev Unpauses the registry
*/
function unpause() external override onlyOwner {
_unpause();
}
/**
* @dev Authorize an issuer for a specific range
* @param issuer Issuer that will be authorized
* @param firstCollectionId First collection Id of the range for which the issuer will be authorized
* @param lastCollectionId Last collection Id of the range for which the issuer will be authorized
*/
function authorizeRange(
address issuer,
uint256 firstCollectionId,
uint256 lastCollectionId
) external override onlyOwner {
_authorizeRange(issuer, firstCollectionId, lastCollectionId);
}
/**
* @dev Unauthorize an issuer for a specific range
* @param issuer Issuer that will be unauthorized
* @param rangeIndex Index of the range to be unauthorized
* @param firstCollectionId First collection Id of the range for which the issuer will be unauthorized
* @param lastCollectionId Last collection Id of the range for which the issuer will be unauthorized
*/
function unauthorizeRange(
address issuer,
uint256 rangeIndex,
uint256 firstCollectionId,
uint256 lastCollectionId
) external override onlyOwner {
_unauthorizeRange(issuer, rangeIndex, firstCollectionId, lastCollectionId);
}
/**
* @dev Authorize an issuer for specific ranges
* @param issuer Issuer that will be authorized
* @param ranges Ranges for which the issuer will be authorized
*/
function authorizeRanges(address issuer, Range[] memory ranges) external override onlyOwner {
for (uint256 i = 0; i < ranges.length; i++) {
_authorizeRange(issuer, ranges[i].min, ranges[i].max);
}
}
/**
* @dev Unauthorize an issuer for specific ranges
* @param issuer Issuer that will be unauthorized
* @param ranges Ranges for which the issuer will be unauthorized
*/
function unauthorizeRanges(
address issuer,
Range[] memory ranges,
uint256[] memory rangeIndexes
) external override onlyOwner {
for (uint256 i = 0; i < rangeIndexes.length; i++) {
_unauthorizeRange(issuer, rangeIndexes[i] - i, ranges[i].min, ranges[i].max);
}
}
/**
* @dev Returns whether a specific issuer is authorized or not to record in a specific attestations collection
* @param issuer Issuer to be checked
* @param collectionId Collection Id for which the issuer will be checked
*/
function isAuthorized(address issuer, uint256 collectionId) external view returns (bool) {
return _isAuthorized(issuer, collectionId);
}
/******************************************
*
* ATTRIBUTES CONFIG LOGIC
*
*****************************************/
/**
* @dev Create a new attribute.
* @param index Index of the attribute. Can go from 0 to 63.
* @param name Name in bytes32 of the attribute
*/
function createNewAttribute(uint8 index, bytes32 name) public onlyOwner {
index._checkIndexIsValid();
if (_isAttributeCreated(index)) {
revert AttributeAlreadyExists(index);
}
_createNewAttribute(index, name);
}
function createNewAttributes(uint8[] memory indices, bytes32[] memory names) external onlyOwner {
if (indices.length != names.length) {
revert ArgsLengthDoesNotMatch();
}
for (uint256 i = 0; i < indices.length; i++) {
createNewAttribute(indices[i], names[i]);
}
}
/**
* @dev Update the name of an existing attribute
* @param index Index of the attribute. Can go from 0 to 63. The attribute must exist
* @param newName new name in bytes32 of the attribute
*/
function updateAttributeName(uint8 index, bytes32 newName) public onlyOwner {
index._checkIndexIsValid();
if (!_isAttributeCreated(index)) {
revert AttributeDoesNotExist(index);
}
_updateAttributeName(index, newName);
}
function updateAttributesName(
uint8[] memory indices,
bytes32[] memory newNames
) external onlyOwner {
if (indices.length != newNames.length) {
revert ArgsLengthDoesNotMatch();
}
for (uint256 i = 0; i < indices.length; i++) {
updateAttributeName(indices[i], newNames[i]);
}
}
/**
* @dev Delete an existing attribute
* @param index Index of the attribute. Can go from 0 to 63. The attribute must already exist
*/
function deleteAttribute(uint8 index) public onlyOwner {
index._checkIndexIsValid();
if (!_isAttributeCreated(index)) {
revert AttributeDoesNotExist(index);
}
_deleteAttribute(index);
}
function deleteAttributes(uint8[] memory indices) external onlyOwner {
for (uint256 i = 0; i < indices.length; i++) {
deleteAttribute(indices[i]);
}
}
/**
* @dev Set a value for an attribute of an attestationsCollection. The attribute should already be created.
* @param collectionId Collection Id of the targeted attestationsCollection
* @param index Index of the attribute (must be between 0 and 63)
* @param value Value of the attribute we want to set for this attestationsCollection. Can take the value 0 to 15
*/
function setAttributeValueForAttestationsCollection(
uint256 collectionId,
uint8 index,
uint8 value
) public onlyOwner {
index._checkIndexIsValid();
if (!_isAttributeCreated(index)) {
revert AttributeDoesNotExist(index);
}
_setAttributeForAttestationsCollection(collectionId, index, value);
}
function setAttributesValuesForAttestationsCollections(
uint256[] memory collectionIds,
uint8[] memory indices,
uint8[] memory values
) external onlyOwner {
if (collectionIds.length != indices.length || collectionIds.length != values.length) {
revert ArgsLengthDoesNotMatch();
}
for (uint256 i = 0; i < collectionIds.length; i++) {
setAttributeValueForAttestationsCollection(collectionIds[i], indices[i], values[i]);
}
}
/**
* @dev Returns the attribute's value (from 0 to 15) of an attestationsCollection
* @param collectionId Collection Id of the targeted attestationsCollection
* @param index Index of the attribute. Can go from 0 to 63.
*/
function getAttributeValueForAttestationsCollection(
uint256 collectionId,
uint8 index
) public view returns (uint8) {
uint256 currentAttributesValues = _getAttributesValuesBitmapForAttestationsCollection(
collectionId
);
return currentAttributesValues._get(index);
}
function getAttributesValuesForAttestationsCollection(
uint256 collectionId,
uint8[] memory indices
) external view returns (uint8[] memory) {
uint8[] memory attributesValues = new uint8[](indices.length);
for (uint256 i = 0; i < indices.length; i++) {
attributesValues[i] = getAttributeValueForAttestationsCollection(collectionId, indices[i]);
}
return attributesValues;
}
/**
* @dev Returns whether an attestationsCollection has a specific attribute referenced by its index
* @param collectionId Collection Id of the targeted attestationsCollection
* @param index Index of the attribute. Can go from 0 to 63.
*/
function attestationsCollectionHasAttribute(
uint256 collectionId,
uint8 index
) public view returns (bool) {
uint256 currentAttributeValues = _getAttributesValuesBitmapForAttestationsCollection(
collectionId
);
return currentAttributeValues._get(index) > 0;
}
function attestationsCollectionHasAttributes(
uint256 collectionId,
uint8[] memory indices
) external view returns (bool) {
for (uint256 i = 0; i < indices.length; i++) {
if (!attestationsCollectionHasAttribute(collectionId, indices[i])) {
return false;
}
}
return true;
}
/**
* @dev Returns all the enabled attributes names and their values for a specific attestationsCollection
* @param collectionId Collection Id of the targeted attestationsCollection
*/
function getAttributesNamesAndValuesForAttestationsCollection(
uint256 collectionId
) public view returns (bytes32[] memory, uint8[] memory) {
uint256 currentAttributesValues = _getAttributesValuesBitmapForAttestationsCollection(
collectionId
);
(
uint8[] memory indices,
uint8[] memory values,
uint8 nbOfNonZeroValues
) = currentAttributesValues._getAllNonZeroValues();
bytes32[] memory attributesNames = new bytes32[](nbOfNonZeroValues);
uint8[] memory attributesValues = new uint8[](nbOfNonZeroValues);
for (uint8 i = 0; i < nbOfNonZeroValues; i++) {
attributesNames[i] = _attributesNames[indices[i]];
attributesValues[i] = values[i];
}
return (attributesNames, attributesValues);
}
/*****************************
*
* INTERNAL FUNCTIONS
*
*****************************/
function _authorizeRange(
address issuer,
uint256 firstCollectionId,
uint256 lastCollectionId
) internal {
Range memory newRange = Range(firstCollectionId, lastCollectionId);
_authorizedRanges[issuer].push(newRange);
emit IssuerAuthorized(issuer, firstCollectionId, lastCollectionId);
}
function _unauthorizeRange(
address issuer,
uint256 rangeIndex,
uint256 firstCollectionId,
uint256 lastCollectionId
) internal onlyOwner {
if (rangeIndex >= _authorizedRanges[issuer].length)
revert RangeIndexOutOfBounds(issuer, _authorizedRanges[issuer].length, rangeIndex);
uint256 expectedFirstId = _authorizedRanges[issuer][rangeIndex].min;
uint256 expectedLastId = _authorizedRanges[issuer][rangeIndex].max;
if (firstCollectionId != expectedFirstId || lastCollectionId != expectedLastId)
revert IdsMismatch(
issuer,
rangeIndex,
expectedFirstId,
expectedLastId,
firstCollectionId,
lastCollectionId
);
_authorizedRanges[issuer][rangeIndex] = _authorizedRanges[issuer][
_authorizedRanges[issuer].length - 1
];
_authorizedRanges[issuer].pop();
emit IssuerUnauthorized(issuer, firstCollectionId, lastCollectionId);
}
function _isAuthorized(address issuer, uint256 collectionId) internal view returns (bool) {
return _authorizedRanges[issuer]._includes(collectionId);
}
function _setAttributeForAttestationsCollection(
uint256 collectionId,
uint8 index,
uint8 value
) internal {
uint256 currentAttributes = _getAttributesValuesBitmapForAttestationsCollection(collectionId);
_attestationsCollectionAttributesValuesBitmap[collectionId] = currentAttributes._set(
index,
value
);
emit AttestationsCollectionAttributeSet(collectionId, index, value);
}
function _createNewAttribute(uint8 index, bytes32 name) internal {
_attributesNames[index] = name;
emit NewAttributeCreated(index, name);
}
function _updateAttributeName(uint8 index, bytes32 newName) internal {
bytes32 previousName = _attributesNames[index];
_attributesNames[index] = newName;
emit AttributeNameUpdated(index, newName, previousName);
}
function _deleteAttribute(uint8 index) internal {
bytes32 deletedName = _attributesNames[index];
delete _attributesNames[index];
emit AttributeDeleted(index, deletedName);
}
function _getAttributesValuesBitmapForAttestationsCollection(
uint256 collectionId
) internal view returns (uint256) {
return _attestationsCollectionAttributesValuesBitmap[collectionId];
}
function _isAttributeCreated(uint8 index) internal view returns (bool) {
if (_attributesNames[index] == 0) {
return false;
}
return true;
}
}
================================================
FILE: contracts/core/libs/attestations-registry/AttestationsRegistryState.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
import {Range} from '../utils/RangeLib.sol';
import {Attestation, AttestationData} from '../Structs.sol';
contract AttestationsRegistryState {
/*******************************************************
Storage layout:
19 slots for config
4 currently used for _initialized, _initializing, _paused, _owner
15 place holders
16 slots for logic
3 currently used for _authorizedRanges, _attestationsCollectionAttributesValuesBitmap, _attributesNames
13 place holders
1 slot for _attestationsData
*******************************************************/
// main config
// changed `_initialized` from bool to uint8
// as we were using OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
// and changed to OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/Initializable.sol)
// PR: https://github.com/sismo-core/sismo-protocol/pull/41
uint8 internal _initialized;
bool internal _initializing;
bool internal _paused;
address internal _owner;
// keeping some space for future
uint256[15] private _placeHoldersAdmin;
// storing the authorized ranges for each attesters
mapping(address => Range[]) internal _authorizedRanges;
// Storing the attributes values used for each attestations collection
// Each attribute value is an hexadecimal
mapping(uint256 => uint256) internal _attestationsCollectionAttributesValuesBitmap;
// Storing the attribute name for each attributes index
mapping(uint8 => bytes32) internal _attributesNames;
// keeping some space for future
uint256[13] private _placeHoldersConfig;
// storing the data of attestations
// =collectionId=> =owner=> attestationData
mapping(uint256 => mapping(address => AttestationData)) internal _attestationsData;
}
================================================
FILE: contracts/core/libs/attestations-registry/InitializableLogic.sol
================================================
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/Initializable.sol)
// Forked from, removed storage, OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.14;
import '../utils/Address.sol';
import './AttestationsRegistryState.sol';
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract InitializableLogic is AttestationsRegistryState {
// only diff with oz
// /**
// * @dev Indicates that the contract has been initialized.
// */
// bool private _initialized;
// /**
// * @dev Indicates that the contract is in the process of being initialized.
// */
// bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) ||
(!Address.isContract(address(this)) && _initialized == 1),
'Initializable: contract is already initialized'
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(
!_initializing && _initialized < version,
'Initializable: contract is already initialized'
);
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, 'Initializable: contract is not initializing');
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, 'Initializable: contract is initializing');
if (_initialized < type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Internal function that returns the initialized version. Returns `_initialized`
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Internal function that returns the initialized version. Returns `_initializing`
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
================================================
FILE: contracts/core/libs/attestations-registry/OwnableLogic.sol
================================================
// SPDX-License-Identifier: MIT
// Forked from, removed storage, OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.14;
import '../utils/Context.sol';
import './AttestationsRegistryState.sol';
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableLogic is Context, AttestationsRegistryState {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// This is the only diff with OZ contract
// address private _owner;
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), 'Ownable: caller is not the owner');
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), 'Ownable: new owner is the zero address');
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
================================================
FILE: contracts/core/libs/attestations-registry/PausableLogic.sol
================================================
// SPDX-License-Identifier: MIT
// Forked from, removed storage, OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.14;
import '../utils/Context.sol';
import './AttestationsRegistryState.sol';
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableLogic is Context, AttestationsRegistryState {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
// this is the only diff with OZ contract
// bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), 'Pausable: paused');
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), 'Pausable: not paused');
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
================================================
FILE: contracts/core/libs/utils/Address.sol
================================================
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, 'Address: insufficient balance');
(bool success, ) = recipient.call{value: amount}('');
require(success, 'Address: unable to send value, recipient may have reverted');
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, 'Address: low-level call failed');
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, 'Address: low-level call with value failed');
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, 'Address: insufficient balance for call');
require(isContract(target), 'Address: call to non-contract');
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data
) internal view returns (bytes memory) {
return functionStaticCall(target, data, 'Address: low-level static call failed');
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), 'Address: static call to non-contract');
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, 'Address: low-level delegate call failed');
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), 'Address: delegate call to non-contract');
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
================================================
FILE: contracts/core/libs/utils/Bitmap256Bit.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
/*
* The 256-bit bitmap is structured in 64 chuncks of 4 bits each.
* The 4 bits can encode any value from 0 to 15.
chunck63 chunck2 chunck1 chunck0
bits bits bits bits
┌────────────┐ ┌────────────┬────────────┬────────────┐
│ 1 1 1 1 │ .... │ 1 0 1 1 │ 0 0 0 0 │ 0 0 0 1 │
└────────────┘ └────────────┴────────────┴────────────┘
value 15 value 11 value 0 value 1
* A chunck index must be between 0 and 63.
* A value must be between 0 and 15.
**/
library Bitmap256Bit {
uint256 constant MAX_INT = 2 ** 256 - 1;
error IndexOutOfBounds(uint8 index);
error ValueOutOfBounds(uint8 value);
/**
* @dev Return the value at a given index of a 256-bit bitmap
* @param index index where the value can be found. Can be between 0 and 63
*/
function _get(uint256 self, uint8 index) internal pure returns (uint8) {
uint256 currentValues = self;
// Get the encoded 4-bit value by right shifting to the `index` position
uint256 shifted = currentValues >> (4 * index);
// Get the value by only masking the last 4 bits with an AND operator
return uint8(shifted & (2 ** 4 - 1));
}
/**
* @dev Set a value at a chosen index in a 256-bit bitmap
* @param index index where the value will be stored. Can be between 0 and 63
* @param value value to store. Can be between 0 and 15
*/
function _set(uint256 self, uint8 index, uint8 value) internal pure returns (uint256) {
_checkIndexIsValid(index);
_checkValueIsValid(value);
uint256 currentValues = self;
// 1. first we need to remove the current value for the inputed `index`
// Left Shift 4 bits mask (1111 mask) to the `index` position
uint256 mask = (2 ** 4 - 1) << (4 * index);
// Apply a XOR operation to obtain a mask with all bits set to 1 except the 4 bits that we want to remove
uint256 negativeMask = MAX_INT ^ mask;
// Apply a AND operation between the current values and the negative mask to remove the wanted bits
uint256 newValues = currentValues & negativeMask;
// 2. We set the new value wanted at the `index` position
// Create the 4 bits encoding the new value and left shift them to the `index` position
uint256 newValueMask = uint256(value) << (4 * index);
// Apply an OR operation between the current values and the newValueMask to reference new value
return newValues | newValueMask;
}
/**
* @dev Get all the non-zero values in a 256-bit bitmap
* @param self a 256-bit bitmap
*/
function _getAllNonZeroValues(
uint256 self
) internal pure returns (uint8[] memory, uint8[] memory, uint8) {
uint8[] memory indices = new uint8[](64);
uint8[] memory values = new uint8[](64);
uint8 nbOfNonZeroValues = 0;
for (uint8 i = 0; i < 63; i++) {
uint8 value = _get(self, i);
if (value > 0) {
indices[nbOfNonZeroValues] = i;
values[nbOfNonZeroValues] = value;
nbOfNonZeroValues++;
}
}
return (indices, values, nbOfNonZeroValues);
}
/**
* @dev Check if the index is valid (is between 0 and 63)
* @param index index of a chunck
*/
function _checkIndexIsValid(uint8 index) internal pure {
if (index > 63) {
revert IndexOutOfBounds(index);
}
}
/**
* @dev Check if the value is valid (is between 0 and 15)
* @param value value to encode in a chunck
*/
function _checkValueIsValid(uint8 value) internal pure {
if (value > 15) {
revert ValueOutOfBounds(value);
}
}
}
================================================
FILE: contracts/core/libs/utils/Context.sol
================================================
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.14;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
================================================
FILE: contracts/core/libs/utils/RangeLib.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
struct Range {
uint256 min;
uint256 max;
}
// Range [0;3] includees 0 and 3
library RangeUtils {
function _includes(Range[] storage ranges, uint256 collectionId) internal view returns (bool) {
for (uint256 i = 0; i < ranges.length; i++) {
if (collectionId >= ranges[i].min && collectionId <= ranges[i].max) {
return true;
}
}
return false;
}
}
================================================
FILE: contracts/core/utils/AddressesProvider.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {Initializable} from '@openzeppelin/contracts/proxy/utils/Initializable.sol';
import {IAddressesProvider} from './interfaces/IAddressesProvider.sol';
// import core contracts
import {Badges} from '../Badges.sol';
import {AttestationsRegistry} from '../AttestationsRegistry.sol';
import {Front} from '../Front.sol';
import {HydraS1AccountboundAttester} from '../../attesters/hydra-s1/HydraS1AccountboundAttester.sol';
import {AvailableRootsRegistry} from '../../periphery/utils/AvailableRootsRegistry.sol';
import {CommitmentMapperRegistry} from '../../periphery/utils/CommitmentMapperRegistry.sol';
import {HydraS1Verifier} from '@sismo-core/hydra-s1/contracts/HydraS1Verifier.sol';
contract AddressesProvider is IAddressesProvider, Initializable, Ownable {
uint8 public constant IMPLEMENTATION_VERSION = 2;
Badges public immutable BADGES;
AttestationsRegistry public immutable ATTESTATIONS_REGISTRY;
Front public immutable FRONT;
HydraS1AccountboundAttester public immutable HYDRA_S1_ACCOUNTBOUND_ATTESTER;
AvailableRootsRegistry public immutable AVAILABLE_ROOTS_REGISTRY;
CommitmentMapperRegistry public immutable COMMITMENT_MAPPER_REGISTRY;
HydraS1Verifier public immutable HYDRA_S1_VERIFIER;
mapping(bytes32 => address) private _contractAddresses;
string[] private _contractNames;
event ContractAddressSet(address contractAddress, string contractName);
constructor(
address badgesAddress,
address attestationsRegistryAddress,
address frontAddress,
address hydraS1AccountboundAttesterAddress,
address availableRootsRegistryAddress,
address commitmentMapperRegistryAddress,
address hydraS1VerifierAddress,
address ownerAddress
) {
BADGES = Badges(badgesAddress);
ATTESTATIONS_REGISTRY = AttestationsRegistry(attestationsRegistryAddress);
FRONT = Front(frontAddress);
HYDRA_S1_ACCOUNTBOUND_ATTESTER = HydraS1AccountboundAttester(
hydraS1AccountboundAttesterAddress
);
AVAILABLE_ROOTS_REGISTRY = AvailableRootsRegistry(availableRootsRegistryAddress);
COMMITMENT_MAPPER_REGISTRY = CommitmentMapperRegistry(commitmentMapperRegistryAddress);
HYDRA_S1_VERIFIER = HydraS1Verifier(hydraS1VerifierAddress);
initialize(ownerAddress);
}
function initialize(address ownerAddress) public reinitializer(IMPLEMENTATION_VERSION) {
// if proxy did not setup owner yet or if called by constructor (for implem setup)
if (owner() == address(0) || address(this).code.length == 0) {
_transferOwnership(ownerAddress);
_set(address(BADGES), 'Badges');
_set(address(ATTESTATIONS_REGISTRY), 'AttestationsRegistry');
_set(address(FRONT), 'Front');
_set(address(HYDRA_S1_ACCOUNTBOUND_ATTESTER), 'HydraS1AccountboundAttester');
_set(address(AVAILABLE_ROOTS_REGISTRY), 'AvailableRootsRegistry');
_set(address(COMMITMENT_MAPPER_REGISTRY), 'CommitmentMapperRegistry');
_set(address(HYDRA_S1_VERIFIER), 'HydraS1Verifier');
}
}
/**
* @dev Sets the address of a contract.
* @param contractAddress Address of the contract.
* @param contractName Name of the contract.
*/
function set(address contractAddress, string memory contractName) public onlyOwner {
_set(contractAddress, contractName);
}
/**
* @dev Sets the address of multiple contracts.
* @param contractAddresses Addresses of the contracts.
* @param contractNames Names of the contracts.
*/
function setBatch(
address[] calldata contractAddresses,
string[] calldata contractNames
) external onlyOwner {
for (uint256 i = 0; i < contractAddresses.length; i++) {
_set(contractAddresses[i], contractNames[i]);
}
}
/**
* @dev Returns the address of a contract.
* @param contractName Name of the contract (string).
* @return Address of the contract.
*/
function get(string memory contractName) public view returns (address) {
bytes32 contractNameHash = keccak256(abi.encodePacked(contractName));
return _contractAddresses[contractNameHash];
}
/**
* @dev Returns the address of a contract.
* @param contractNameHash Hash of the name of the contract (bytes32).
* @return Address of the contract.
*/
function get(bytes32 contractNameHash) public view returns (address) {
return _contractAddresses[contractNameHash];
}
/**
* @dev Returns the addresses of all contracts inputed.
* @param contractNames Names of the contracts as strings.
*/
function getBatch(string[] calldata contractNames) external view returns (address[] memory) {
address[] memory contractAddresses = new address[](contractNames.length);
for (uint256 i = 0; i < contractNames.length; i++) {
contractAddresses[i] = get(contractNames[i]);
}
return contractAddresses;
}
/**
* @dev Returns the addresses of all contracts inputed.
* @param contractNamesHash Names of the contracts as bytes32.
*/
function getBatch(bytes32[] calldata contractNamesHash) external view returns (address[] memory) {
address[] memory contractAddresses = new address[](contractNamesHash.length);
for (uint256 i = 0; i < contractNamesHash.length; i++) {
contractAddresses[i] = get(contractNamesHash[i]);
}
return contractAddresses;
}
/**
* @dev Returns the addresses of all contracts in `_contractNames`
* @return Names, Hashed Names and Addresses of all contracts.
*/
function getAll() external view returns (string[] memory, bytes32[] memory, address[] memory) {
string[] memory contractNames = _contractNames;
bytes32[] memory contractNamesHash = new bytes32[](contractNames.length);
address[] memory contractAddresses = new address[](contractNames.length);
for (uint256 i = 0; i < contractNames.length; i++) {
contractAddresses[i] = get(contractNames[i]);
contractNamesHash[i] = keccak256(abi.encodePacked(contractNames[i]));
}
return (contractNames, contractNamesHash, contractAddresses);
}
/**
* @dev Sets the address of a contract.
* @param contractAddress Address of the contract.
* @param contractName Name of the contract.
*/
function _set(address contractAddress, string memory contractName) internal {
bytes32 contractNameHash = keccak256(abi.encodePacked(contractName));
if (_contractAddresses[contractNameHash] == address(0)) {
_contractNames.push(contractName);
}
_contractAddresses[contractNameHash] = contractAddress;
emit ContractAddressSet(contractAddress, contractName);
}
}
================================================
FILE: contracts/core/utils/interfaces/IAddressesProvider.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
interface IAddressesProvider {
/**
* @dev Sets the address of a contract.
* @param contractAddress Address of the contract.
* @param contractName Name of the contract.
*/
function set(address contractAddress, string memory contractName) external;
/**
* @dev Sets the address of multiple contracts.
* @param contractAddresses Addresses of the contracts.
* @param contractNames Names of the contracts.
*/
function setBatch(address[] calldata contractAddresses, string[] calldata contractNames) external;
/**
* @dev Returns the address of a contract.
* @param contractName Name of the contract (string).
* @return Address of the contract.
*/
function get(string memory contractName) external view returns (address);
/**
* @dev Returns the address of a contract.
* @param contractNameHash Hash of the name of the contract (bytes32).
* @return Address of the contract.
*/
function get(bytes32 contractNameHash) external view returns (address);
/**
* @dev Returns the addresses of all contracts inputed.
* @param contractNames Names of the contracts as strings.
*/
function getBatch(string[] calldata contractNames) external view returns (address[] memory);
/**
* @dev Returns the addresses of all contracts inputed.
* @param contractNamesHash Names of the contracts as strings.
*/
function getBatch(bytes32[] calldata contractNamesHash) external view returns (address[] memory);
/**
* @dev Returns the addresses of all contracts in `_contractNames`
* @return Names, Hashed Names and Addresses of all contracts.
*/
function getAll() external view returns (string[] memory, bytes32[] memory, address[] memory);
}
================================================
FILE: contracts/libs/SismoLib.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
/**
* @title SismoLib
* @author Sismo
* @notice This is the Sismo Library of the Sismo protocol
* It is designed to be the only contract that needs to be imported to integrate Sismo in a smart contract.
* Its aim is to provide a set of sub-libraries with high-level functions to interact with the Sismo protocol easily.
*/
import './using-sismo/UsingSismo.sol';
================================================
FILE: contracts/libs/using-sismo/UsingSismo.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
import {AddressesProvider} from '../../core/utils/AddressesProvider.sol';
import {Badges} from '../../core/Badges.sol';
import {Attester} from '../../core/Attester.sol';
import {HydraS1AccountboundAttester} from '../../attesters/hydra-s1/HydraS1AccountboundAttester.sol';
import {Context} from '@openzeppelin/contracts/utils/Context.sol';
import {Request, Claim, Attestation} from '../../core/libs/Structs.sol';
enum BalanceRequirementType {
gte,
lte,
equal
}
/**
* @title UsingSismo
* @author Sismo
* @notice This contract is intended to be used by other contracts that need to mint Sismo Badges from Sismo proofs or check if an user holds certain Sismo Badges thanks
* to high level functions such as `_mintSismoBadge` and `_requireBadges`.
*
* This contract can be viewed as a library that goes by pair with the "Prove With Sismo" off-chain flow. The "Prove With Sismo" off-chain flow is a flow that allows
* users to prove that they are eligible to a specific Sismo Badge and mint it on-chain thanks to a Sismo proof and a request.
* There are two different "Prove With Sismo" flows for on-chain gating:
*
* 2-txs flow: #1(tx) user is directed to Sismo and mints the Badge.
* #2(tx) app smart contract uses the onlyBadgeOwner modifier
* or _requireBadges check function
* to gate their function to Badge holders only
* 1-tx flow: #1(off-chain) user is directed to Sismo to create a Sismo Proof of Badge eligibility
* #(tx): app smart contract uses the _mintSismoBadge function that forwards the proof to the Attester
* The Attester checks the proof (and mints the Sismo Badge).
*
*/
contract UsingSismo is Context {
uint256 public constant SISMO_LIB_VERSION = 1;
AddressesProvider public immutable ADDRESSES_PROVIDER =
AddressesProvider(0x3340Ac0CaFB3ae34dDD53dba0d7344C1Cf3EFE05);
HydraS1AccountboundAttester public immutable HYDRA_S1_ACCOUNTBOUND_ATTESTER;
Badges public immutable BADGES;
error UserDoesNotMeetAllRequirements(uint256 badgeTokenId, uint256 minBalance);
error UserDoesNotMeetRequirements();
error InvalidArgumentsLength();
error WrongBalanceRequirementType();
constructor() {
string[] memory contractNames = new string[](2);
contractNames[0] = 'HydraS1AccountboundAttester';
contractNames[1] = 'Badges';
address[] memory contractAddresses = ADDRESSES_PROVIDER.getBatch(contractNames);
HYDRA_S1_ACCOUNTBOUND_ATTESTER = HydraS1AccountboundAttester(contractAddresses[0]);
BADGES = Badges(contractAddresses[1]);
}
/*******************************************************
1. MINT BADGES from sismoProof received by "Prove With Sismo" off-chain flow
*******************************************************/
/**
* @dev Mint badge from sismoProof received by "Prove With Sismo" off-chain flow
* @param request user request
* @param sismoProof Sismo proof
* @param attester Attester address (default = HYDRA_S1_ACCOUNTBOUND_ATTESTER, see the next function)
* @return Address of the owner of the badges, tokenIds of the badges minted and levels of the badges minted
* @notice This function will use the default attester (HYDRA_S1_ACCOUNTBOUND_ATTESTER) if no attester is specified.
*/
function _mintSismoBadge(
Request memory request,
bytes memory sismoProof,
address attester // default == HYDRA_S1_ACCOUNTBOUND_ATTESTER, see next function.
) public returns (address, uint256, uint256) {
(address owner, uint256[] memory badgesTokenIds, uint256[] memory badgesLevels) = Attester(
attester
).mintBadges(request, sismoProof);
return (owner, badgesTokenIds[0], badgesLevels[0]);
}
/**
* @dev Mint badge from sismoProof received by "Prove With Sismo" off-chain flow (DEFAULT ATTESTER USAGE)
* @param request user request
* @param sismoProof Sismo proof
* @return Address of the owner of the badges, tokenIds of the badges minted and levels of the badges minted
*/
function _mintSismoBadge(
Request memory request,
bytes memory sismoProof
) internal returns (address, uint256, uint256) {
(
address owner,
uint256[] memory badgesTokenIds,
uint256[] memory badgesLevels
) = HYDRA_S1_ACCOUNTBOUND_ATTESTER.mintBadges(request, sismoProof);
return (owner, badgesTokenIds[0], badgesLevels[0]);
}
/**
* @dev Mint badges from sismoProof received by "Prove With Sismo" off-chain flow
* @param request user request
* @param sismoProof Sismo proof
* @param attester Attester address (default = HYDRA_S1_ACCOUNTBOUND_ATTESTER, see the next function)
* @return Address of the owner of the badges, tokenIds of the badges minted and levels of the badges minted
* @notice This function will use the default attester (HYDRA_S1_ACCOUNTBOUND_ATTESTER) if no attester is specified.
*/
function _mintSismoBadges(
Request memory request,
bytes memory sismoProof,
address attester // default == HYDRA_S1_ACCOUNTBOUND_ATTESTER, see next function.
) public returns (address, uint256[] memory, uint256[] memory) {
(address owner, uint256[] memory badgesTokenIds, uint256[] memory badgesLevels) = Attester(
attester
).mintBadges(request, sismoProof);
return (owner, badgesTokenIds, badgesLevels);
}
/**
* @dev Mint badges from sismoProof received by "Prove With Sismo" off-chain flow (DEFAULT ATTESTER USAGE)
* @param request user request
* @param sismoProof Sismo proof
* @return Address of the owner of the badges, tokenIds of the badges minted and levels of the badges minted
*/
function _mintSismoBadges(
Request memory request,
bytes memory sismoProof
) internal returns (address, uint256[] memory, uint256[] memory) {
(
address owner,
uint256[] memory badgesTokenIds,
uint256[] memory badgesLevels
) = HYDRA_S1_ACCOUNTBOUND_ATTESTER.mintBadges(request, sismoProof);
return (owner, badgesTokenIds, badgesLevels);
}
/*******************************************************
2. CORE BADGE REQUIREMENTS FUNCTIONS
(with default values, see section 4)
*******************************************************/
/**
* @dev Check if the user has the required badges
* @param account User address
* @param badgeTokenIds TokenIds of the required badges
* @param isEachBadgeRequired If true, the user must have all the badges required. If false, the user must have at least one of the badges required. Default = false (see section 4).
* @param requiredBalances Required balances of the required badges. Default = [1, .., 1] (see section 4).
* @param balanceRequirementType Balance requirement type. Default = gte (see section 4).
*/
function _requireBadges(
address account,
uint256[] memory badgeTokenIds,
bool isEachBadgeRequired, // default = false, see Section 4.
uint256[] memory requiredBalances, // default = [1, .., 1], see Section 4.
BalanceRequirementType balanceRequirementType // default = [gte], see Section 4.
) internal view {
_checkArgumentsLength(badgeTokenIds, requiredBalances);
bool atLeastOneRequirementOk = false;
for (uint32 i = 0; i < badgeTokenIds.length; i++) {
uint256 balance = BADGES.balanceOf(account, badgeTokenIds[i]);
uint256 requiredBalance = requiredBalances[i];
if (_isBalanceRequirementOk(balance, requiredBalance, balanceRequirementType) == true) {
atLeastOneRequirementOk = true;
} else {
if (isEachBadgeRequired) {
revert UserDoesNotMeetAllRequirements(badgeTokenIds[i], requiredBalance);
}
}
}
if (!atLeastOneRequirementOk) {
revert UserDoesNotMeetRequirements();
}
}
function _requireBadge(
address account,
uint256 badgeTokenId,
uint256 requiredBalance, // default = 1, see Section 3.
BalanceRequirementType balanceRequirementType // default = gte, see Section 3.
) internal view {
uint256[] memory badgeTokenIds = new uint256[](1);
badgeTokenIds[0] = badgeTokenId;
uint256[] memory requiredBalances = new uint256[](1);
requiredBalances[0] = requiredBalance;
_requireBadges(account, badgeTokenIds, false, requiredBalances, balanceRequirementType);
}
/*******************************************************
3. MODIFIERS
*******************************************************/
/**
* @dev Modifier to check if msg.sender has the required badge
* @param badgeTokenId TokenId of the badge required
*/
modifier onlyBadgeHolders(uint256 badgeTokenId) {
_requireBadge(_msgSender(), badgeTokenId);
_;
}
/**
* @dev Modifier to check if msg.sender has the required badges
* @param badgeTokenIds TokenIds of the badges required
* @param isEachBadgeRequired If true, the user must have all the badges required. If false, the user must have at least one of the badges required. Default = false (see section 4).
*/
modifier onlyBadgesHolders(uint256[] memory badgeTokenIds, bool isEachBadgeRequired) {
_requireBadges(_msgSender(), badgeTokenIds, isEachBadgeRequired);
_;
}
modifier onlyBadgeHoldersWithGreaterBalance(uint256 badgeTokenId, uint256 minBalance) {
_requireBadge(_msgSender(), badgeTokenId, minBalance);
_;
}
modifier onlyBadgeHoldersWithLowerBalance(uint256 badgeTokenId, uint256 maxBalance) {
_requireBadge(_msgSender(), badgeTokenId, maxBalance, BalanceRequirementType.lte);
_;
}
modifier onlyBadgeHoldersWithExactBalance(uint256 badgeTokenId, uint256 exactBalance) {
_requireBadge(_msgSender(), badgeTokenId, exactBalance, BalanceRequirementType.equal);
_;
}
modifier onlyBadgesHoldersWithGreaterBalance(
uint256[] memory badgeTokenIds,
uint256[] memory minBalances,
bool isEachBadgeRequired
) {
_requireBadges(_msgSender(), badgeTokenIds, isEachBadgeRequired, minBalances);
_;
}
modifier onlyBadgesHoldersWithLowerBalance(
uint256[] memory badgeTokenIds,
uint256[] memory maxBalances,
bool isEachBadgeRequired
) {
_requireBadges(
_msgSender(),
badgeTokenIds,
isEachBadgeRequired,
maxBalances,
BalanceRequirementType.lte
);
_;
}
modifier onlyBadgesHoldersWithExactBalance(
uint256[] memory badgeTokenIds,
uint256[] memory exactBalances,
bool isEachBadgeRequired
) {
_requireBadges(
_msgSender(),
badgeTokenIds,
isEachBadgeRequired,
exactBalances,
BalanceRequirementType.equal
);
_;
}
/*******************************************************
4. CORE FUNCTIONS WITH DEFAULT VALUES HARD CODED (SAME NAME, DIFFERENT SIGNATURES)
*******************************************************/
function _requireBadges(
address account,
uint256[] memory badgeTokenIds,
bool isEachBadgeRequired,
uint256[] memory minBalances
) internal view {
_requireBadges(
account,
badgeTokenIds,
isEachBadgeRequired,
minBalances,
BalanceRequirementType.gte
);
}
function _requireBadges(
address account,
uint256[] memory badgeTokenIds,
bool isEachBadgeRequired
) internal view {
uint256[] memory arrayOfOnes = new uint256[](badgeTokenIds.length);
// by default, we require at least a balance of 1 for each badge
for (uint32 i = 0; i < badgeTokenIds.length; i++) {
arrayOfOnes[i] = 1;
}
_requireBadges(account, badgeTokenIds, isEachBadgeRequired, arrayOfOnes);
}
function _requireBadge(
address account,
uint256 badgeTokenId,
uint256 requiredBalance
) internal view {
uint256[] memory badgeTokenIds = new uint256[](1);
badgeTokenIds[0] = badgeTokenId;
uint256[] memory requiredBalances = new uint256[](1);
requiredBalances[0] = requiredBalance;
_requireBadges(account, badgeTokenIds, false, requiredBalances, BalanceRequirementType.gte);
}
function _requireBadges(address account, uint256[] memory badgeTokenIds) internal view {
_requireBadges(account, badgeTokenIds, false);
}
function _requireBadge(address account, uint256 badgeTokenId) internal view {
uint256[] memory badgeTokenIds = new uint256[](1);
badgeTokenIds[0] = badgeTokenId;
_requireBadges(account, badgeTokenIds);
}
/**
* @dev Check if the arguments have the same length
* @param badgeTokenIds Token ID of the badges
* @param minBalances Minimum balances (= levels) of the badges
*/
function _checkArgumentsLength(
uint256[] memory badgeTokenIds,
uint256[] memory minBalances
) internal pure {
if (badgeTokenIds.length != minBalances.length) {
revert InvalidArgumentsLength();
}
}
/**
* @dev Check if the balance of the badge meets the requirement
* @param balance Balance of the badge
* @param requiredBalance Required balance of the badge
* @param balanceRequirementType Type of the balance requirement (gte, lte, equal)
*/
function _isBalanceRequirementOk(
uint256 balance,
uint256 requiredBalance,
BalanceRequirementType balanceRequirementType
) internal pure returns (bool) {
if (balanceRequirementType == BalanceRequirementType.gte) {
return balance >= requiredBalance;
} else if (balanceRequirementType == BalanceRequirementType.lte) {
return balance <= requiredBalance && balance > 0;
} else if (balanceRequirementType == BalanceRequirementType.equal) {
return balance == requiredBalance;
} else {
revert WrongBalanceRequirementType();
}
}
}
================================================
FILE: contracts/periphery/utils/AvailableRootsRegistry.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {IAvailableRootsRegistry} from './interfaces/IAvailableRootsRegistry.sol';
import {Initializable} from '@openzeppelin/contracts/proxy/utils/Initializable.sol';
/**
* @title Attesters Groups Registry
* @author Sismo
* @notice This contract stores that data required by attesters to be available so they can verify user claims
* This contract is deployed behind a proxy and this implementation is focused on storing merkle roots
* For more information: https://available-roots-registry.docs.sismo.io
*
**/
contract AvailableRootsRegistry is IAvailableRootsRegistry, Initializable, Ownable {
uint8 public constant IMPLEMENTATION_VERSION = 2;
mapping(address => mapping(uint256 => bool)) public _roots;
/**
* @dev Constructor
* @param owner Owner of the contract, can register/ unregister roots
*/
constructor(address owner) {
initialize(owner);
}
/**
* @dev Initializes the contract, to be called by the proxy delegating calls to this implementation
* @param ownerAddress Owner of the contract, can update public key and address
* @notice The reinitializer modifier is needed to configure modules that are added through upgrades and that require initialization.
*/
function initialize(address ownerAddress) public reinitializer(IMPLEMENTATION_VERSION) {
// if proxy did not setup owner yet or if called by constructor (for implem setup)
if (owner() == address(0) || address(this).code.length == 0) {
_transferOwnership(ownerAddress);
}
}
/**
* @dev Register a root available for an attester
* @param attester Attester which will have the root available
* @param root Root to register
*/
function regi
gitextract_16i2pstn/
├── .github/
│ └── workflows/
│ ├── publish.yaml
│ └── push.yaml
├── .gitignore
├── .mocharc.json
├── .prettierrc
├── Dockerfile
├── LICENSE
├── README.md
├── contracts/
│ ├── attesters/
│ │ ├── hydra-s1/
│ │ │ ├── HydraS1AccountboundAttester.sol
│ │ │ ├── HydraS1SimpleAttester.sol
│ │ │ ├── base/
│ │ │ │ ├── HydraS1Base.sol
│ │ │ │ └── IHydraS1Base.sol
│ │ │ ├── interfaces/
│ │ │ │ ├── IHydraS1AccountboundAttester.sol
│ │ │ │ └── IHydraS1SimpleAttester.sol
│ │ │ └── libs/
│ │ │ ├── HydraS1AccountboundLib.sol
│ │ │ └── HydraS1Lib.sol
│ │ └── pythia-1/
│ │ ├── Pythia1SimpleAttester.sol
│ │ ├── base/
│ │ │ ├── IPythia1Base.sol
│ │ │ └── Pythia1Base.sol
│ │ ├── interfaces/
│ │ │ └── IPythia1SimpleAttester.sol
│ │ └── libs/
│ │ └── Pythia1Lib.sol
│ ├── core/
│ │ ├── AttestationsRegistry.sol
│ │ ├── Attester.sol
│ │ ├── Badges.sol
│ │ ├── Front.sol
│ │ ├── interfaces/
│ │ │ ├── IAttestationsRegistry.sol
│ │ │ ├── IAttestationsRegistryConfigLogic.sol
│ │ │ ├── IAttester.sol
│ │ │ ├── IBadges.sol
│ │ │ └── IFront.sol
│ │ ├── libs/
│ │ │ ├── Structs.sol
│ │ │ ├── attestations-registry/
│ │ │ │ ├── AttestationsRegistryConfigLogic.sol
│ │ │ │ ├── AttestationsRegistryState.sol
│ │ │ │ ├── InitializableLogic.sol
│ │ │ │ ├── OwnableLogic.sol
│ │ │ │ └── PausableLogic.sol
│ │ │ └── utils/
│ │ │ ├── Address.sol
│ │ │ ├── Bitmap256Bit.sol
│ │ │ ├── Context.sol
│ │ │ └── RangeLib.sol
│ │ └── utils/
│ │ ├── AddressesProvider.sol
│ │ └── interfaces/
│ │ └── IAddressesProvider.sol
│ ├── libs/
│ │ ├── SismoLib.sol
│ │ └── using-sismo/
│ │ └── UsingSismo.sol
│ ├── periphery/
│ │ └── utils/
│ │ ├── AvailableRootsRegistry.sol
│ │ ├── CommitmentMapperRegistry.sol
│ │ ├── FrontendLib.sol
│ │ ├── TransparentUpgradeableProxy.sol
│ │ └── interfaces/
│ │ ├── IAvailableRootsRegistry.sol
│ │ └── ICommitmentMapperRegistry.sol
│ ├── tests/
│ │ ├── MockHydraS1SimpleAttester.sol
│ │ └── mocks/
│ │ ├── MockAttestationsRegistry.sol
│ │ ├── MockAttester.sol
│ │ └── mockContractUsingSismoLib.sol
│ └── zkdrop/
│ └── ZKBadgeboundERC721.sol
├── hardhat.config.ts
├── helper-hardhat-config.ts
├── package.json
├── scripts/
│ └── wait-for-local-chain.sh
├── tasks/
│ ├── addresses-provider/
│ │ └── set-batch.task.ts
│ ├── available-roots-registry/
│ │ ├── register-for-attester.task.ts
│ │ └── unregister-for-attester.task.ts
│ ├── deploy-tasks/
│ │ ├── batch/
│ │ │ └── deploy-core.task.ts
│ │ ├── deployments-config.ts
│ │ ├── full/
│ │ │ ├── 0-deploy-core-and-hydra-s1-simple-and-accountbound-and-pythia1.task.ts
│ │ │ ├── 1-deploy-pythia-1-simple.task.ts
│ │ │ ├── 2-upgrade-proxies.task.ts
│ │ │ ├── 2-upgrade-proxies.test-fork.ts
│ │ │ ├── 3-new-hydra-s1-verifier-and-upgrade-hydra-s1-simple-proxy.task.ts
│ │ │ ├── 3-new-hydra-s1-verifier-and-upgrade-hydra-s1-simple-proxy.test-fork.ts
│ │ │ ├── 4-upgrade-attestations-registry-proxy-and-badges-proxy.task.ts
│ │ │ ├── 4-upgrade-attestations-registry-proxy-and-badges-proxy.test-fork.ts
│ │ │ ├── 5-upgrade-proxies-with-reinitializer/
│ │ │ │ ├── 5-upgrade-proxies-with-reinitializer-available-roots-registry.test-fork.ts
│ │ │ │ ├── 5-upgrade-proxies-with-reinitializer-commitment-mapper-registry.test-fork.ts
│ │ │ │ └── 5-upgrade-proxies-with-reinitializer-pythia1.test-fork.ts
│ │ │ ├── 5-upgrade-proxies-with-reinitializer.task.ts
│ │ │ ├── 6-7-8-fork-test/
│ │ │ │ └── 6-7-8.test-fork.ts
│ │ │ ├── 6-deploy-sismo-addresses-provider.task.ts
│ │ │ ├── 7-upgrade-hydra-s1-accountbound-and-pythia-1-proxies.task.ts
│ │ │ ├── 9-fork-test/
│ │ │ │ └── 9-upgrade-addresses-provider-on-testnets.test-fork.ts
│ │ │ ├── 9-upgrade-addresses-provider-on-testnets.task.ts
│ │ │ ├── local/
│ │ │ │ └── deploy-full-local.task.ts
│ │ │ └── staging/
│ │ │ └── deploy-sismo-addresses-provider-staging.task.ts
│ │ ├── tests/
│ │ │ ├── deploy-mock-attestations-registry.task.ts
│ │ │ ├── deploy-mock-attester-and-core.task.ts
│ │ │ ├── deploy-mock-attester.task.ts
│ │ │ ├── deploy-mock-contract-using-sismo-lib.task.ts
│ │ │ └── deploy-zk-badgebound-erc721.task.ts
│ │ ├── unit/
│ │ │ ├── attesters/
│ │ │ │ ├── hydra-s1/
│ │ │ │ │ ├── deploy-hydra-s1-accountbound-attester.task.ts
│ │ │ │ │ ├── deploy-hydra-s1-simple-attester.task.ts
│ │ │ │ │ └── deploy-hydra-s1-verifier.task.ts
│ │ │ │ └── pythia-1/
│ │ │ │ ├── deploy-pythia-1-simple-attester.task.ts
│ │ │ │ └── deploy-pythia-1-verifier.task.ts
│ │ │ ├── core/
│ │ │ │ ├── deploy-attestations-registry.task.ts
│ │ │ │ ├── deploy-badges.task.ts
│ │ │ │ ├── deploy-front.task.ts
│ │ │ │ └── deploy-sismo-addresses-provider.task.ts
│ │ │ └── periphery/
│ │ │ ├── deploy-available-roots-registry.task.ts
│ │ │ ├── deploy-commitment-mapper-registry.task.ts
│ │ │ └── deploy-frontend-lib.task.ts
│ │ ├── utils/
│ │ │ ├── deployment.ts
│ │ │ ├── deployments-config-types.ts
│ │ │ └── index.ts
│ │ └── zkdrop/
│ │ ├── deploy-mergooor-pass.task.ts
│ │ ├── deploy-ziki-pass-staging.task.ts
│ │ └── deploy-ziki-pass-testnet.task.ts
│ ├── helpers/
│ │ ├── authorizations/
│ │ │ ├── access-control-grant-role.task.ts
│ │ │ ├── access-control-revoke-role.task.ts
│ │ │ ├── attestations-registry-authorize-range.task.ts
│ │ │ ├── attestations-registry-transfer-ownership.task.ts
│ │ │ ├── change-proxy-admin.task.ts
│ │ │ └── ownable-transfer-ownership.task.ts
│ │ ├── forge-create2-transaction.task.ts
│ │ ├── print-accounts.task.ts
│ │ ├── print-storage-layout.task.ts
│ │ ├── proxy/
│ │ │ └── upgrade-proxy.task.ts
│ │ └── verify-contract.task.ts
│ └── utils/
│ ├── common-options.ts
│ ├── confirm.ts
│ ├── index.ts
│ ├── relayer.ts
│ └── types.ts
├── test/
│ ├── e2e/
│ │ └── e2e.test.ts
│ ├── unit/
│ │ ├── attesters/
│ │ │ ├── hydra-s1/
│ │ │ │ ├── hydra-s1-accountbound-attester.test.ts
│ │ │ │ └── hydra-s1-simple-attester.test.ts
│ │ │ └── pythia-1/
│ │ │ └── pythia-1-simple-attester.test.ts
│ │ ├── core/
│ │ │ ├── attestations-registry/
│ │ │ │ ├── attestations-registry-config-logic.test.ts
│ │ │ │ └── attestations-registry.test.ts
│ │ │ ├── badges.test.ts
│ │ │ ├── front.test.ts
│ │ │ └── utils/
│ │ │ └── sismo-addresses-provider.test.ts
│ │ ├── libs/
│ │ │ └── using-sismo/
│ │ │ └── using-sismo.test.ts
│ │ ├── periphery/
│ │ │ └── utils/
│ │ │ ├── available-roots-registry.test.ts
│ │ │ ├── commitment-mapper-registry.test.ts
│ │ │ └── frontend-lib.test.ts
│ │ └── zkdrop/
│ │ └── zk-badgebound-erc721.test.ts
│ └── utils/
│ ├── attestation-logic.ts
│ ├── evm.ts
│ ├── expectEvent.ts
│ ├── hydra-s1-accountbound.ts
│ ├── hydra-s1.ts
│ ├── index.ts
│ ├── pythia-1.ts
│ ├── setup.ts
│ └── test-helpers.ts
├── tsconfig.json
└── utils/
├── constants.ts
├── index.ts
├── proxy.ts
└── singletonFactory.ts
SYMBOL INDEX (229 symbols across 62 files)
FILE: hardhat.config.ts
constant HARDFORK (line 31) | const HARDFORK = 'london';
constant MNEMONIC_PATH (line 33) | const MNEMONIC_PATH = "m/44'/60'/0'/0";
constant SISMO_SHARED_MNEMONIC (line 35) | const SISMO_SHARED_MNEMONIC =
constant MNEMONIC (line 37) | const MNEMONIC = process.env.MNEMONIC || SISMO_SHARED_MNEMONIC;
constant INFURA_KEY (line 39) | const INFURA_KEY = process.env.INFURA_KEY || '';
constant ALCHEMY_KEY (line 40) | const ALCHEMY_KEY = process.env.ALCHEMY_KEY || '';
constant FORK (line 42) | const FORK = process.env.FORK === 'true';
constant FORKING_BLOCK (line 43) | const FORKING_BLOCK = process.env.FORKING_BLOCK
constant FORK_NETWORK (line 46) | const FORK_NETWORK = process.env.FORK_NETWORK || '';
constant LOCAL_CHAIN_ID (line 98) | const LOCAL_CHAIN_ID = process.env.LOCAL_CHAIN_ID ? parseInt(process.env...
constant LOCAL_HOSTNAME (line 99) | const LOCAL_HOSTNAME = process.env.LOCAL_HOSTNAME ?? 'localhost';
constant LOCAL_PORT (line 100) | const LOCAL_PORT = process.env.LOCAL_PORT ? parseInt(process.env.LOCAL_P...
FILE: helper-hardhat-config.ts
type Network (line 4) | type Network = EthereumNetwork | PolygonNetwork | GnosisNetwork;
type EthereumNetwork (line 6) | enum EthereumNetwork {
type PolygonNetwork (line 16) | enum PolygonNetwork {
type GnosisNetwork (line 21) | enum GnosisNetwork {
type ParamsPerNetwork (line 25) | type ParamsPerNetwork<T> =
type EthereumParamsPerNetwork (line 30) | interface EthereumParamsPerNetwork<Network> {
type PolygonParamsPerNetwork (line 39) | interface PolygonParamsPerNetwork<T> {
type XDaiParamsPerNetwork (line 44) | interface XDaiParamsPerNetwork<T> {
type ObjectString (line 48) | interface ObjectString {
constant NETWORKS_RPC_URL (line 56) | const NETWORKS_RPC_URL: ParamsPerNetwork<string> = {
FILE: tasks/addresses-provider/set-batch.task.ts
type SetBatchArgs (line 8) | type SetBatchArgs = {
function action (line 14) | async function action(
FILE: tasks/available-roots-registry/register-for-attester.task.ts
type RegisterForAttesterArgs (line 11) | type RegisterForAttesterArgs = {
function action (line 19) | async function action(
FILE: tasks/available-roots-registry/unregister-for-attester.task.ts
type UnregisterForAttesterArgs (line 11) | type UnregisterForAttesterArgs = {
function action (line 19) | async function action(
FILE: tasks/deploy-tasks/batch/deploy-core.task.ts
type DeployedCore (line 14) | interface DeployedCore {
type DeployCoreArgs (line 20) | interface DeployCoreArgs {
function deploymentAction (line 29) | async function deploymentAction(
FILE: tasks/deploy-tasks/deployments-config.ts
constant COMMITMENT_MAPPER_EDDSA_PUB_KEY_PROD (line 3) | const COMMITMENT_MAPPER_EDDSA_PUB_KEY_PROD = [
constant COMMITMENT_MAPPER_EDDSA_PUB_KEY_STAGING (line 8) | const COMMITMENT_MAPPER_EDDSA_PUB_KEY_STAGING = [
constant COMMITMENT_MAPPER_TESTER (line 13) | const COMMITMENT_MAPPER_TESTER = [
constant COMMITMENT_SIGNER_PUB_KEY_SYNAPS_STAGING (line 18) | const COMMITMENT_SIGNER_PUB_KEY_SYNAPS_STAGING = [
constant COMMITMENT_SIGNER_PUB_KEY_SYNAPS_PROD (line 23) | const COMMITMENT_SIGNER_PUB_KEY_SYNAPS_PROD = [
constant SISMO_ADDRESSES_PROVIDER_PROXY_DEPLOYER (line 29) | const SISMO_ADDRESSES_PROVIDER_PROXY_DEPLOYER = '0x77694e7C30B74dd271EAC...
constant SISMO_ADDRESSES_PROVIDER_CONTRACT_ADDRESS (line 31) | const SISMO_ADDRESSES_PROVIDER_CONTRACT_ADDRESS =
constant THREE_DAYS (line 34) | const THREE_DAYS = '295200';
constant ALPHA_MAINNET_OWNER (line 37) | const ALPHA_MAINNET_OWNER = '0xaee4acd5c4Bf516330ca8fe11B07206fC6709294';
constant ALPHA_MAINNET_ROOTS_OWNER_RELAYER (line 38) | const ALPHA_MAINNET_ROOTS_OWNER_RELAYER = '0x2a265b954b96d4940b94eb69e8f...
constant ALPHA_MAINNET_PROXY_ADMIN (line 39) | const ALPHA_MAINNET_PROXY_ADMIN = '0x2110475dfbB8d331b300178A867372991ff...
constant ALPHA_POLYGON_OWNER (line 42) | const ALPHA_POLYGON_OWNER = '0xaee4acd5c4Bf516330ca8fe11B07206fC6709294';
constant ALPHA_POLYGON_ROOTS_OWNER_RELAYER (line 43) | const ALPHA_POLYGON_ROOTS_OWNER_RELAYER = '0xf0a0b692e1c764281c211948d03...
constant ALPHA_POLYGON_PROXY_ADMIN (line 44) | const ALPHA_POLYGON_PROXY_ADMIN = '0x2110475dfbB8d331b300178A867372991ff...
constant ALPHA_GNOSIS_OWNER (line 46) | const ALPHA_GNOSIS_OWNER = '0xaee4acd5c4Bf516330ca8fe11B07206fC6709294';
constant ALPHA_GNOSIS_ROOTS_OWNER_RELAYER (line 47) | const ALPHA_GNOSIS_ROOTS_OWNER_RELAYER = '0xef809a50de35c762fbacf1ae1f6b...
constant ALPHA_GNOSIS_PROXY_ADMIN (line 48) | const ALPHA_GNOSIS_PROXY_ADMIN = '0x2110475dfbB8d331b300178A867372991ff3...
constant SANDBOX_POLYGON_OWNER (line 50) | const SANDBOX_POLYGON_OWNER = '0xaee4acd5c4Bf516330ca8fe11B07206fC6709294';
constant SANDBOX_POLYGON_ROOTS_OWNER_RELAYER (line 51) | const SANDBOX_POLYGON_ROOTS_OWNER_RELAYER = '0x7e2305312099748bbd6a31bff...
constant SANDBOX_POLYGON_PROXY_ADMIN (line 52) | const SANDBOX_POLYGON_PROXY_ADMIN = '0x2110475dfbB8d331b300178A867372991...
constant ALPHA_GOERLI_TESTNET_OWNER (line 55) | const ALPHA_GOERLI_TESTNET_OWNER = '0xaee4acd5c4Bf516330ca8fe11B07206fC6...
constant ALPHA_GOERLI_TESTNET_ROOTS_OWNER_RELAYER (line 56) | const ALPHA_GOERLI_TESTNET_ROOTS_OWNER_RELAYER = '0xa687922c4bf2eb22297f...
constant ALPHA_GOERLI_TESTNET_PROXY_ADMIN (line 57) | const ALPHA_GOERLI_TESTNET_PROXY_ADMIN = '0x2110475dfbB8d331b300178A8673...
constant ALPHA_MUMBAI_TESTNET_OWNER (line 59) | const ALPHA_MUMBAI_TESTNET_OWNER = '0xaee4acd5c4Bf516330ca8fe11B07206fC6...
constant ALPHA_MUMBAI_TESTNET_ROOTS_OWNER_RELAYER (line 60) | const ALPHA_MUMBAI_TESTNET_ROOTS_OWNER_RELAYER = '0xca0583a6682607282963...
constant ALPHA_MUMBAI_TESTNET_PROXY_ADMIN (line 61) | const ALPHA_MUMBAI_TESTNET_PROXY_ADMIN = '0x2110475dfbB8d331b300178A8673...
constant ALPHA_GOERLI_STAGING_OWNER (line 64) | const ALPHA_GOERLI_STAGING_OWNER = '0x4e070E9b85a659F0B7B47cde33152ad6c2...
constant ALPHA_GOERLI_STAGING_ROOTS_OWNER_RELAYER (line 65) | const ALPHA_GOERLI_STAGING_ROOTS_OWNER_RELAYER = '0x7f2e6e158643bcaf85f3...
constant ALPHA_GOERLI_STAGING_PROXY_ADMIN (line 66) | const ALPHA_GOERLI_STAGING_PROXY_ADMIN = '0x246E71bC2a257f4BE9C7fAD4664E...
constant ALPHA_MUMBAI_STAGING_OWNER (line 68) | const ALPHA_MUMBAI_STAGING_OWNER = '0x4e070E9b85a659F0B7B47cde33152ad6c2...
constant ALPHA_MUMBAI_STAGING_ROOTS_OWNER_RELAYER (line 69) | const ALPHA_MUMBAI_STAGING_ROOTS_OWNER_RELAYER = '0x63f08f8f13126b9eadc7...
constant ALPHA_MUMBAI_STAGING_PROXY_ADMIN (line 70) | const ALPHA_MUMBAI_STAGING_PROXY_ADMIN = '0x246E71bC2a257f4BE9C7fAD4664E...
FILE: tasks/deploy-tasks/full/0-deploy-core-and-hydra-s1-simple-and-accountbound-and-pythia1.task.ts
type Deployed0 (line 43) | interface Deployed0 {
function deploymentAction (line 56) | async function deploymentAction(
FILE: tasks/deploy-tasks/full/1-deploy-pythia-1-simple.task.ts
type Deployed1 (line 14) | interface Deployed1 {
function deploymentAction (line 19) | async function deploymentAction(
FILE: tasks/deploy-tasks/full/2-upgrade-proxies.task.ts
type Deployed2 (line 14) | interface Deployed2 {
function deploymentAction (line 22) | async function deploymentAction(
FILE: tasks/deploy-tasks/full/3-new-hydra-s1-verifier-and-upgrade-hydra-s1-simple-proxy.task.ts
type Deployed3 (line 8) | interface Deployed3 {
function deploymentAction (line 13) | async function deploymentAction(
FILE: tasks/deploy-tasks/full/4-upgrade-attestations-registry-proxy-and-badges-proxy.task.ts
type Deployed4 (line 9) | interface Deployed4 {
function deploymentAction (line 14) | async function deploymentAction(
FILE: tasks/deploy-tasks/full/4-upgrade-attestations-registry-proxy-and-badges-proxy.test-fork.ts
type IssuerRange (line 42) | type IssuerRange = {
type Attestations (line 47) | type Attestations = {
FILE: tasks/deploy-tasks/full/5-upgrade-proxies-with-reinitializer.task.ts
type Deployed5 (line 15) | interface Deployed5 {
function deploymentAction (line 21) | async function deploymentAction(
FILE: tasks/deploy-tasks/full/6-deploy-sismo-addresses-provider.task.ts
type Deployed6 (line 8) | interface Deployed6 {
function deploymentAction (line 12) | async function deploymentAction(
FILE: tasks/deploy-tasks/full/7-upgrade-hydra-s1-accountbound-and-pythia-1-proxies.task.ts
type Deployed7 (line 9) | interface Deployed7 {
function deploymentAction (line 14) | async function deploymentAction(
FILE: tasks/deploy-tasks/full/9-upgrade-addresses-provider-on-testnets.task.ts
type Deployed9 (line 19) | interface Deployed9 {
function deploymentAction (line 23) | async function deploymentAction(
FILE: tasks/deploy-tasks/full/local/deploy-full-local.task.ts
function deploymentAction (line 30) | async function deploymentAction(
FILE: tasks/deploy-tasks/full/staging/deploy-sismo-addresses-provider-staging.task.ts
constant CONTRACT_NAME (line 14) | const CONTRACT_NAME = 'AddressesProvider';
function deploymentAction (line 16) | async function deploymentAction(
FILE: tasks/deploy-tasks/tests/deploy-mock-attestations-registry.task.ts
type DeployMockAttestationsRegistryArgs (line 15) | interface DeployMockAttestationsRegistryArgs {
type DeployedMockAttestationsRegistry (line 20) | interface DeployedMockAttestationsRegistry {
constant CONTRACT_NAME (line 24) | const CONTRACT_NAME = 'MockAttestationsRegistry';
function deploymentAction (line 26) | async function deploymentAction(
FILE: tasks/deploy-tasks/tests/deploy-mock-attester-and-core.task.ts
type DeployMockAttesterAndCoreArgs (line 11) | type DeployMockAttesterAndCoreArgs = Omit<
type DeployedMockAttesterAndCore (line 16) | interface DeployedMockAttesterAndCore extends DeployedMockAttester, Depl...
function deploymentAction (line 18) | async function deploymentAction(
FILE: tasks/deploy-tasks/tests/deploy-mock-attester.task.ts
type DeployMockAttesterArgs (line 15) | interface DeployMockAttesterArgs {
type DeployedMockAttester (line 23) | interface DeployedMockAttester {
constant CONTRACT_NAME (line 27) | const CONTRACT_NAME = 'MockAttester';
function deploymentAction (line 29) | async function deploymentAction(
FILE: tasks/deploy-tasks/tests/deploy-mock-contract-using-sismo-lib.task.ts
type DeployMockContractUsingSismoLibArgs (line 14) | interface DeployMockContractUsingSismoLibArgs {
type DeployedMockContractUsingSismoLib (line 18) | interface DeployedMockContractUsingSismoLib {
constant CONTRACT_NAME (line 22) | const CONTRACT_NAME = 'MockContractUsingSismoLib';
function deploymentAction (line 24) | async function deploymentAction(
FILE: tasks/deploy-tasks/tests/deploy-zk-badgebound-erc721.task.ts
type DeployZKBadgeboundERC721Args (line 14) | interface DeployZKBadgeboundERC721Args {
type DeployedZkBadgeboundERC721 (line 24) | interface DeployedZkBadgeboundERC721 {
constant CONTRACT_NAME (line 28) | const CONTRACT_NAME = 'ZKBadgeboundERC721';
function deploymentAction (line 30) | async function deploymentAction(
FILE: tasks/deploy-tasks/unit/attesters/hydra-s1/deploy-hydra-s1-accountbound-attester.task.ts
type DeployHydraS1AccountboundAttesterArgs (line 20) | interface DeployHydraS1AccountboundAttesterArgs {
type DeployedHydraS1AccountboundAttester (line 37) | interface DeployedHydraS1AccountboundAttester {
constant CONTRACT_NAME (line 42) | const CONTRACT_NAME = 'HydraS1AccountboundAttester';
function deploymentAction (line 44) | async function deploymentAction(
FILE: tasks/deploy-tasks/unit/attesters/hydra-s1/deploy-hydra-s1-simple-attester.task.ts
type DeployHydraS1SimpleAttesterArgs (line 21) | interface DeployHydraS1SimpleAttesterArgs {
type DeployedHydraS1SimpleAttester (line 39) | interface DeployedHydraS1SimpleAttester {
constant CONTRACT_NAME (line 44) | const CONTRACT_NAME = 'HydraS1SimpleAttester';
function deploymentAction (line 46) | async function deploymentAction(
FILE: tasks/deploy-tasks/unit/attesters/hydra-s1/deploy-hydra-s1-verifier.task.ts
type DeployHydraS1Verifier (line 14) | interface DeployHydraS1Verifier {
type DeployedHydraS1Verifier (line 18) | interface DeployedHydraS1Verifier {
constant CONTRACT_NAME (line 22) | const CONTRACT_NAME = 'HydraS1Verifier';
function deploymentAction (line 24) | async function deploymentAction(
FILE: tasks/deploy-tasks/unit/attesters/pythia-1/deploy-pythia-1-simple-attester.task.ts
type DeployPythia1SimpleAttesterArgs (line 21) | interface DeployPythia1SimpleAttesterArgs {
type DeployedPythia1SimpleAttester (line 38) | interface DeployedPythia1SimpleAttester {
constant CONTRACT_NAME (line 43) | const CONTRACT_NAME = 'Pythia1SimpleAttester';
function deploymentAction (line 45) | async function deploymentAction(
FILE: tasks/deploy-tasks/unit/attesters/pythia-1/deploy-pythia-1-verifier.task.ts
type DeployPythia1Verifier (line 14) | interface DeployPythia1Verifier {
type DeployedPythia1Verifier (line 18) | interface DeployedPythia1Verifier {
constant CONTRACT_NAME (line 22) | const CONTRACT_NAME = 'Pythia1Verifier';
function deploymentAction (line 24) | async function deploymentAction(
FILE: tasks/deploy-tasks/unit/core/deploy-attestations-registry.task.ts
type DeployAttestationsRegistryArgs (line 14) | interface DeployAttestationsRegistryArgs {
type DeployedAttestationsRegistry (line 23) | interface DeployedAttestationsRegistry {
constant CONTRACT_NAME (line 27) | const CONTRACT_NAME = 'AttestationsRegistry';
function deploymentAction (line 29) | async function deploymentAction(
FILE: tasks/deploy-tasks/unit/core/deploy-badges.task.ts
type DeployBadgesArgs (line 14) | interface DeployBadgesArgs {
type DeployedBadges (line 22) | interface DeployedBadges {
constant CONTRACT_NAME (line 26) | const CONTRACT_NAME = 'Badges';
function deploymentAction (line 28) | async function deploymentAction(
FILE: tasks/deploy-tasks/unit/core/deploy-front.task.ts
type DeployFrontArgs (line 15) | interface DeployFrontArgs {
type DeployedFront (line 22) | interface DeployedFront {
constant CONTRACT_NAME (line 26) | const CONTRACT_NAME = 'Front';
function deploymentAction (line 28) | async function deploymentAction(
FILE: tasks/deploy-tasks/unit/core/deploy-sismo-addresses-provider.task.ts
type DeploySismoAddressesProvider (line 23) | interface DeploySismoAddressesProvider {
type DeployedSismoAddressesProvider (line 35) | interface DeployedSismoAddressesProvider {
constant CONTRACT_NAME (line 39) | const CONTRACT_NAME = 'AddressesProvider';
function deploymentAction (line 41) | async function deploymentAction(
FILE: tasks/deploy-tasks/unit/periphery/deploy-available-roots-registry.task.ts
type DeployAvailableRootsRegistry (line 15) | interface DeployAvailableRootsRegistry {
type DeployedAvailableRootsRegistry (line 21) | interface DeployedAvailableRootsRegistry {
constant CONTRACT_NAME (line 25) | const CONTRACT_NAME = 'AvailableRootsRegistry';
function deploymentAction (line 27) | async function deploymentAction(
FILE: tasks/deploy-tasks/unit/periphery/deploy-commitment-mapper-registry.task.ts
type DeployCommitmentMapperArgs (line 15) | interface DeployCommitmentMapperArgs {
type DeployedCommitmentMapper (line 24) | interface DeployedCommitmentMapper {
constant CONTRACT_NAME (line 28) | const CONTRACT_NAME = 'CommitmentMapperRegistry';
function deploymentAction (line 30) | async function deploymentAction(
FILE: tasks/deploy-tasks/unit/periphery/deploy-frontend-lib.task.ts
type DeployFrontendLib (line 17) | interface DeployFrontendLib {
type DeployedFrontendLib (line 22) | interface DeployedFrontendLib {
constant CONTRACT_NAME (line 26) | const CONTRACT_NAME = 'FrontendLib';
function deploymentAction (line 28) | async function deploymentAction(
FILE: tasks/deploy-tasks/utils/deployments-config-types.ts
type DeployOptions (line 3) | interface DeployOptions extends CommonTaskOptions {
type DeploymentsConfigTypes (line 20) | type DeploymentsConfigTypes = {
FILE: tasks/deploy-tasks/zkdrop/deploy-mergooor-pass.task.ts
type DeployedMergooorPass (line 8) | interface DeployedMergooorPass {
function deploymentAction (line 12) | async function deploymentAction(
FILE: tasks/deploy-tasks/zkdrop/deploy-ziki-pass-staging.task.ts
type DeployedZikiPass (line 8) | interface DeployedZikiPass {
function deploymentAction (line 12) | async function deploymentAction(
FILE: tasks/deploy-tasks/zkdrop/deploy-ziki-pass-testnet.task.ts
type DeployedZikiPass (line 8) | interface DeployedZikiPass {
function deploymentAction (line 12) | async function deploymentAction(
FILE: tasks/helpers/authorizations/access-control-grant-role.task.ts
type AccessControlGrantRoleArgs (line 7) | type AccessControlGrantRoleArgs = {
function grantRole (line 14) | async function grantRole(
FILE: tasks/helpers/authorizations/access-control-revoke-role.task.ts
type AccessControlRevokeRoleArgs (line 7) | type AccessControlRevokeRoleArgs = {
function revokeRole (line 14) | async function revokeRole(
FILE: tasks/helpers/authorizations/attestations-registry-authorize-range.task.ts
type AuthorizeRangeArgs (line 8) | type AuthorizeRangeArgs = {
function authorizeRange (line 16) | async function authorizeRange(
FILE: tasks/helpers/authorizations/attestations-registry-transfer-ownership.task.ts
type AuthorizeRangeArgs (line 7) | type AuthorizeRangeArgs = {
function authorizeRange (line 11) | async function authorizeRange(
FILE: tasks/helpers/authorizations/change-proxy-admin.task.ts
type ChangeProxyAdminArgs (line 8) | type ChangeProxyAdminArgs = {
function action (line 14) | async function action(
FILE: tasks/helpers/authorizations/ownable-transfer-ownership.task.ts
type OwnableTransferOwnershipArgs (line 7) | type OwnableTransferOwnershipArgs = {
function ownableTransferOwnership (line 13) | async function ownableTransferOwnership(
FILE: tasks/helpers/forge-create2-transaction.task.ts
function printAccounts (line 4) | async function printAccounts({}, hre: HardhatRuntimeEnvironment): Promis...
FILE: tasks/helpers/print-accounts.task.ts
function printAccounts (line 4) | async function printAccounts({}, hre: HardhatRuntimeEnvironment): Promis...
FILE: tasks/helpers/print-storage-layout.task.ts
function printStorageLayout (line 4) | async function printStorageLayout({}, hre: HardhatRuntimeEnvironment): P...
FILE: tasks/helpers/proxy/upgrade-proxy.task.ts
type UpgradeProxyArgs (line 9) | type UpgradeProxyArgs = {
function upgradeProxy (line 17) | async function upgradeProxy(
FILE: tasks/helpers/verify-contract.task.ts
function verifyContract (line 10) | async function verifyContract({ deploymentName }, hre: HardhatRuntimeEnv...
FILE: tasks/utils/confirm.ts
function confirm (line 4) | function confirm(): Promise<void> {
FILE: tasks/utils/types.ts
type CommonTaskOptions (line 1) | interface CommonTaskOptions {
FILE: test/unit/core/attestations-registry/attestations-registry.test.ts
type IssuerRange (line 8) | type IssuerRange = {
type Attestations (line 13) | type Attestations = {
FILE: test/unit/core/front.test.ts
type IssuerRange (line 9) | type IssuerRange = {
type Requests (line 14) | type Requests = {
type Attestations (line 19) | type Attestations = {
type AttestationArray (line 24) | type AttestationArray = [BigNumber, string, string, BigNumber, BigNumber...
function assertAttestationRecordedEventEmitted (line 26) | async function assertAttestationRecordedEventEmitted(
function assertAttestationDataIsValid (line 43) | async function assertAttestationDataIsValid(
FILE: test/utils/evm.ts
function increaseTime (line 5) | async function increaseTime(
function setTime (line 13) | async function setTime(hre: HardhatRuntimeEnvironment, timestamp: number...
function evmSnapshot (line 17) | async function evmSnapshot(hre: HardhatRuntimeEnvironment): Promise<stri...
function evmRevert (line 22) | async function evmRevert(hre: HardhatRuntimeEnvironment, snapshotId: str...
function impersonateAddress (line 26) | async function impersonateAddress(
function getBlockTimestamp (line 48) | async function getBlockTimestamp(): Promise<number> {
FILE: test/utils/hydra-s1-accountbound.ts
type HydraS1AccountboundGroup (line 12) | type HydraS1AccountboundGroup = {
type HydraS1AccountboundGroupProperties (line 18) | type HydraS1AccountboundGroupProperties = {
type AvailableGroupsAccountbound (line 25) | type AvailableGroupsAccountbound = {
type generateHydraS1AccountBoundAttesterGroups (line 30) | type generateHydraS1AccountBoundAttesterGroups = {
FILE: test/utils/hydra-s1.ts
type GroupData (line 51) | type GroupData = { [address: string]: number };
type HydraS1SimpleGroup (line 73) | type HydraS1SimpleGroup = {
type HydraS1SimpleGroupProperties (line 79) | type HydraS1SimpleGroupProperties = {
type RegistryAccountsMerkle (line 85) | type RegistryAccountsMerkle = {
type AttesterGroups (line 90) | type AttesterGroups = {
type generateAttesterGroups (line 95) | type generateAttesterGroups = {
function generateExternalNullifier (line 184) | async function generateExternalNullifier(attesterAddress: string, groupI...
function toBytes (line 192) | function toBytes(snarkProof: any) {
type GenerateAttesterGroup (line 221) | type GenerateAttesterGroup = {
type ProvingDataStruct (line 229) | type ProvingDataStruct = {
type HydraS1Proof (line 294) | type HydraS1Proof = {
type AccountsTreeWithData (line 299) | type AccountsTreeWithData = { tree: KVMerkleTree; group: HydraS1SimpleGr...
type HydraS1ZKPSConstructorArgs (line 301) | type HydraS1ZKPSConstructorArgs = {
type ProofGenerationArgs (line 310) | type ProofGenerationArgs = {
class HydraS1ZKPS (line 325) | class HydraS1ZKPS {
method constructor (line 333) | constructor({
method generateProof (line 349) | public async generateProof(proofGenerationArgs: ProofGenerationArgs) {
method getNullifier (line 398) | public async getNullifier(proofGenerationArgs: ProofGenerationArgs) {
method getVariables (line 427) | public async getVariables(proofGenerationArgs: ProofGenerationArgs) {
FILE: test/utils/pythia-1.ts
type Pythia1Group (line 10) | type Pythia1Group = {
type Pythia1GroupProperties (line 15) | type Pythia1GroupProperties = {
class CommitmentSignerTester (line 40) | class CommitmentSignerTester {
method constructor (line 43) | constructor(seed: BigNumberish = '0x123321') {
method getCommitmentReceipt (line 47) | async getCommitmentReceipt(
method getPublicKey (line 56) | async getPublicKey(): Promise<EddsaPublicKey> {
method _getEddsaAccount (line 60) | private async _getEddsaAccount(): Promise<EddsaAccount> {
FILE: test/utils/setup.ts
function getMockedAccounts (line 6) | async function getMockedAccounts(
type HydraS1MockedAccount (line 38) | type HydraS1MockedAccount = {
FILE: utils/constants.ts
constant EVENT_TRIGGERER_ROLE (line 4) | const EVENT_TRIGGERER_ROLE: BytesLike = ethers.utils.keccak256(
FILE: utils/proxy.ts
constant IMPLEMENTATION_SLOT (line 4) | const IMPLEMENTATION_SLOT: string =
Condensed preview — 150 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (928K chars).
[
{
"path": ".github/workflows/publish.yaml",
"chars": 1131,
"preview": "name: Publish Docker image\n\non:\n push:\n tags:\n - 'v*'\n\njobs:\n push_to_registry:\n name: Push Docker image to"
},
{
"path": ".github/workflows/push.yaml",
"chars": 544,
"preview": "name: On Push checks\non:\n push:\njobs:\n test:\n runs-on: ubuntu-latest\n name: Compile, test and test deploy\n st"
},
{
"path": ".gitignore",
"chars": 103,
"preview": "node_modules\ndeployments\ncache\nartifacts\ntypechain-types\ntypes/**\n.vscode\ndeployments/local\nsave\n.env\n\n"
},
{
"path": ".mocharc.json",
"chars": 62,
"preview": "{\n \"require\": \"ts-node/register/files\",\n \"timeout\": 20000\n}\n"
},
{
"path": ".prettierrc",
"chars": 238,
"preview": "{\n \"printWidth\": 100,\n \"trailingComma\": \"es5\",\n \"semi\": true,\n \"singleQuote\": true,\n \"tabWidth\": 2,\n \"overrides\": "
},
{
"path": "Dockerfile",
"chars": 296,
"preview": "FROM node:16 AS build\n\nWORKDIR /usr/src/build\n# Install dependencies\nCOPY package.json yarn.lock ./\n\nRUN yarn install --"
},
{
"path": "LICENSE",
"chars": 1062,
"preview": "MIT License\n\nCopyright (c) 2022 Sismo\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof t"
},
{
"path": "README.md",
"chars": 3492,
"preview": "<br />\n<div align=\"center\">\n <img src=\"docs/top.png\" alt=\"Logo\" width=\"100\" height=\"100\" style=\"borderRadius: 20px\">\n\n "
},
{
"path": "contracts/attesters/hydra-s1/HydraS1AccountboundAttester.sol",
"chars": 14671,
"preview": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.14;\npragma experimental ABIEncoderV2;\n\nimport {Ownable} from '@ope"
},
{
"path": "contracts/attesters/hydra-s1/HydraS1SimpleAttester.sol",
"chars": 9527,
"preview": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.14;\npragma experimental ABIEncoderV2;\n\nimport {IHydraS1SimpleAttes"
},
{
"path": "contracts/attesters/hydra-s1/base/HydraS1Base.sol",
"chars": 7007,
"preview": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.14;\npragma experimental ABIEncoderV2;\n\nimport {IHydraS1Base} from "
},
{
"path": "contracts/attesters/hydra-s1/base/IHydraS1Base.sol",
"chars": 2448,
"preview": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.14;\npragma experimental ABIEncoderV2;\n\nimport {IAttester} from '.."
},
{
"path": "contracts/attesters/hydra-s1/interfaces/IHydraS1AccountboundAttester.sol",
"chars": 3400,
"preview": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.14;\npragma experimental ABIEncoderV2;\n\nimport {IHydraS1SimpleAttes"
},
{
"path": "contracts/attesters/hydra-s1/interfaces/IHydraS1SimpleAttester.sol",
"chars": 1762,
"preview": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.14;\npragma experimental ABIEncoderV2;\n\nimport {Attestation} from '"
},
{
"path": "contracts/attesters/hydra-s1/libs/HydraS1AccountboundLib.sol",
"chars": 2517,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nimport {Claim, Request} from '../../../core/libs/Structs.sol';"
},
{
"path": "contracts/attesters/hydra-s1/libs/HydraS1Lib.sol",
"chars": 5036,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nimport {Claim, Request} from '../../../core/libs/Structs.sol';"
},
{
"path": "contracts/attesters/pythia-1/Pythia1SimpleAttester.sol",
"chars": 10123,
"preview": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.14;\npragma experimental ABIEncoderV2;\n\nimport {Ownable} from '@ope"
},
{
"path": "contracts/attesters/pythia-1/base/IPythia1Base.sol",
"chars": 1211,
"preview": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.14;\npragma experimental ABIEncoderV2;\n\nimport {Pythia1Verifier, Py"
},
{
"path": "contracts/attesters/pythia-1/base/Pythia1Base.sol",
"chars": 5688,
"preview": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.14;\npragma experimental ABIEncoderV2;\n\nimport {IPythia1Base} from "
},
{
"path": "contracts/attesters/pythia-1/interfaces/IPythia1SimpleAttester.sol",
"chars": 1746,
"preview": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.14;\npragma experimental ABIEncoderV2;\n\nimport {Attestation} from '"
},
{
"path": "contracts/attesters/pythia-1/libs/Pythia1Lib.sol",
"chars": 4666,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nimport {Claim, Request} from '../../../core/libs/Structs.sol';"
},
{
"path": "contracts/core/AttestationsRegistry.sol",
"chars": 10239,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nimport {IAttestationsRegistry} from './interfaces/IAttestation"
},
{
"path": "contracts/core/Attester.sol",
"chars": 8654,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\nimport {IAttester} from './interfaces/IAttester.sol';\nimport {I"
},
{
"path": "contracts/core/Badges.sol",
"chars": 7068,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nimport {ERC1155} from '@openzeppelin/contracts/token/ERC1155/E"
},
{
"path": "contracts/core/Front.sol",
"chars": 5458,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nimport {IFront} from './interfaces/IFront.sol';\nimport {IAttes"
},
{
"path": "contracts/core/interfaces/IAttestationsRegistry.sol",
"chars": 4156,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nimport {Attestation, AttestationData} from '../libs/Structs.so"
},
{
"path": "contracts/core/interfaces/IAttestationsRegistryConfigLogic.sol",
"chars": 6457,
"preview": "// SPDX-License-Identifier: MIT\n// Forked from, removed storage, OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)\n// O"
},
{
"path": "contracts/core/interfaces/IAttester.sol",
"chars": 2527,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nimport {Request, Attestation} from '../libs/Structs.sol';\nimpo"
},
{
"path": "contracts/core/interfaces/IBadges.sol",
"chars": 3881,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\n/**\n * @title Interface for Badges contract\n * @author Sismo\n "
},
{
"path": "contracts/core/interfaces/IFront.sol",
"chars": 2263,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nimport {Request, Attestation} from '../libs/Structs.sol';\n\n/**"
},
{
"path": "contracts/core/libs/Structs.sol",
"chars": 2755,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\n/**\n * @title Attestations Registry State\n * @author Sismo\n *"
},
{
"path": "contracts/core/libs/attestations-registry/AttestationsRegistryConfigLogic.sol",
"chars": 12886,
"preview": "// SPDX-License-Identifier: MIT\n// Forked from, removed storage, OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)\n// O"
},
{
"path": "contracts/core/libs/attestations-registry/AttestationsRegistryState.sol",
"chars": 1842,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nimport {Range} from '../utils/RangeLib.sol';\nimport {Attestati"
},
{
"path": "contracts/core/libs/attestations-registry/InitializableLogic.sol",
"chars": 6534,
"preview": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/Initializable.sol)\n// Forke"
},
{
"path": "contracts/core/libs/attestations-registry/OwnableLogic.sol",
"chars": 2550,
"preview": "// SPDX-License-Identifier: MIT\n// Forked from, removed storage, OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)\n// O"
},
{
"path": "contracts/core/libs/attestations-registry/PausableLogic.sol",
"chars": 2286,
"preview": "// SPDX-License-Identifier: MIT\n// Forked from, removed storage, OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)\n// O"
},
{
"path": "contracts/core/libs/utils/Address.sol",
"chars": 7728,
"preview": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)\n\npragma solidity ^0."
},
{
"path": "contracts/core/libs/utils/Bitmap256Bit.sol",
"chars": 3653,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\n/*\n * The 256-bit bitmap is structured in 64 chuncks of 4 bits"
},
{
"path": "contracts/core/libs/utils/Context.sol",
"chars": 829,
"preview": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.14;\n\n/**\n * @"
},
{
"path": "contracts/core/libs/utils/RangeLib.sol",
"chars": 443,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nstruct Range {\n uint256 min;\n uint256 max;\n}\n\n// Range [0;3]"
},
{
"path": "contracts/core/utils/AddressesProvider.sol",
"chars": 6657,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nimport {Ownable} from '@openzeppelin/contracts/access/Ownable."
},
{
"path": "contracts/core/utils/interfaces/IAddressesProvider.sol",
"chars": 1773,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\ninterface IAddressesProvider {\n /**\n * @dev Sets the addres"
},
{
"path": "contracts/libs/SismoLib.sol",
"chars": 427,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\n/**\n * @title SismoLib\n * @author Sismo\n * @notice This is the"
},
{
"path": "contracts/libs/using-sismo/UsingSismo.sol",
"chars": 13661,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nimport {AddressesProvider} from '../../core/utils/AddressesPro"
},
{
"path": "contracts/periphery/utils/AvailableRootsRegistry.sol",
"chars": 4118,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nimport {Ownable} from '@openzeppelin/contracts/access/Ownable."
},
{
"path": "contracts/periphery/utils/CommitmentMapperRegistry.sol",
"chars": 3467,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nimport {Ownable} from '@openzeppelin/contracts/access/Ownable."
},
{
"path": "contracts/periphery/utils/FrontendLib.sol",
"chars": 965,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nimport {Ownable} from '@openzeppelin/contracts/access/Ownable."
},
{
"path": "contracts/periphery/utils/TransparentUpgradeableProxy.sol",
"chars": 5115,
"preview": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/transparent/TransparentUpgradeableProxy.sol)\n// "
},
{
"path": "contracts/periphery/utils/interfaces/IAvailableRootsRegistry.sol",
"chars": 2292,
"preview": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.14;\n\n/**\n * @title IAvailableRootsRegistry\n * @author Sismo\n * @no"
},
{
"path": "contracts/periphery/utils/interfaces/ICommitmentMapperRegistry.sol",
"chars": 1497,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\ninterface ICommitmentMapperRegistry {\n event UpdatedCommitmen"
},
{
"path": "contracts/tests/MockHydraS1SimpleAttester.sol",
"chars": 734,
"preview": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.14;\n\nimport {Attestation, Request} from '../core/libs/Structs.sol'"
},
{
"path": "contracts/tests/mocks/MockAttestationsRegistry.sol",
"chars": 1076,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\nimport {IAttestationsRegistry} from '../../core/interfaces/IAtt"
},
{
"path": "contracts/tests/mocks/MockAttester.sol",
"chars": 1330,
"preview": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.14;\n\nimport {Attestation, Request} from '../../core/libs/Structs.s"
},
{
"path": "contracts/tests/mocks/mockContractUsingSismoLib.sol",
"chars": 3961,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nimport {UsingSismo, Request} from '../../libs/SismoLib.sol';\n\n"
},
{
"path": "contracts/zkdrop/ZKBadgeboundERC721.sol",
"chars": 8935,
"preview": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.14;\n\nimport '@openzeppelin/contracts-upgradeable/token/ERC721/ERC72"
},
{
"path": "hardhat.config.ts",
"chars": 4915,
"preview": "import * as dotenv from 'dotenv';\nimport { HardhatUserConfig } from 'hardhat/config';\nimport {\n EthereumNetwork,\n Poly"
},
{
"path": "helper-hardhat-config.ts",
"chars": 2144,
"preview": "import dotenv from 'dotenv';\ndotenv.config({});\n\nexport type Network = EthereumNetwork | PolygonNetwork | GnosisNetwork;"
},
{
"path": "package.json",
"chars": 2299,
"preview": "{\n \"name\": \"sismo-protocol\",\n \"version\": \"1.0.0\",\n \"description\": \"Sismo attestations repo\",\n \"main\": \"index.js\",\n "
},
{
"path": "scripts/wait-for-local-chain.sh",
"chars": 232,
"preview": "#!/bin/sh\nset -e\n\nHOSTNAME=${LOCAL_HOSTNAME:-'localhost'} \nPORT=${LOCAL_PORT:-8545}\nwhile ! nc -z $HOSTNAME $PORT; do "
},
{
"path": "tasks/addresses-provider/set-batch.task.ts",
"chars": 2008,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { AddressesProv"
},
{
"path": "tasks/available-roots-registry/register-for-attester.task.ts",
"chars": 2251,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { getDeployer }"
},
{
"path": "tasks/available-roots-registry/unregister-for-attester.task.ts",
"chars": 2270,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { getDeployer }"
},
{
"path": "tasks/deploy-tasks/batch/deploy-core.task.ts",
"chars": 3466,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { AttestationsR"
},
{
"path": "tasks/deploy-tasks/deployments-config.ts",
"chars": 26018,
"preview": "import { DeploymentsConfigTypes } from './utils/deployments-config-types';\n\nconst COMMITMENT_MAPPER_EDDSA_PUB_KEY_PROD ="
},
{
"path": "tasks/deploy-tasks/full/0-deploy-core-and-hydra-s1-simple-and-accountbound-and-pythia1.task.ts",
"chars": 14352,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport {\n DeployHydra"
},
{
"path": "tasks/deploy-tasks/full/1-deploy-pythia-1-simple.task.ts",
"chars": 3923,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { DeployOptions"
},
{
"path": "tasks/deploy-tasks/full/2-upgrade-proxies.task.ts",
"chars": 5825,
"preview": "import { DeployedBadges } from '../unit/core/deploy-badges.task';\nimport { HydraS1AccountboundAttester } from '../../../"
},
{
"path": "tasks/deploy-tasks/full/2-upgrade-proxies.test-fork.ts",
"chars": 30539,
"preview": "import { getImplementation } from './../../../utils/proxy';\nimport { HydraS1AccountboundAttester } from '../../../types/"
},
{
"path": "tasks/deploy-tasks/full/3-new-hydra-s1-verifier-and-upgrade-hydra-s1-simple-proxy.task.ts",
"chars": 2981,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { DeployOptions"
},
{
"path": "tasks/deploy-tasks/full/3-new-hydra-s1-verifier-and-upgrade-hydra-s1-simple-proxy.test-fork.ts",
"chars": 31937,
"preview": "import { getImplementation } from '../../../utils/proxy';\nimport {\n AttestationStructOutput,\n HydraS1SimpleAttester,\n "
},
{
"path": "tasks/deploy-tasks/full/4-upgrade-attestations-registry-proxy-and-badges-proxy.task.ts",
"chars": 2540,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { DeployOptions"
},
{
"path": "tasks/deploy-tasks/full/4-upgrade-attestations-registry-proxy-and-badges-proxy.test-fork.ts",
"chars": 14163,
"preview": "import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';\nimport { expect } from 'chai';\nimport hre, { ethe"
},
{
"path": "tasks/deploy-tasks/full/5-upgrade-proxies-with-reinitializer/5-upgrade-proxies-with-reinitializer-available-roots-registry.test-fork.ts",
"chars": 16352,
"preview": "import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';\nimport { expect } from 'chai';\nimport hre, { ethe"
},
{
"path": "tasks/deploy-tasks/full/5-upgrade-proxies-with-reinitializer/5-upgrade-proxies-with-reinitializer-commitment-mapper-registry.test-fork.ts",
"chars": 9525,
"preview": "import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';\nimport { CommitmentMapperTester } from '@sismo-co"
},
{
"path": "tasks/deploy-tasks/full/5-upgrade-proxies-with-reinitializer/5-upgrade-proxies-with-reinitializer-pythia1.test-fork.ts",
"chars": 10721,
"preview": "import { expect } from 'chai';\nimport hre from 'hardhat';\nimport {\n AttestationsRegistry,\n AttestationsRegistry__facto"
},
{
"path": "tasks/deploy-tasks/full/5-upgrade-proxies-with-reinitializer.task.ts",
"chars": 3764,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { DeployOptions"
},
{
"path": "tasks/deploy-tasks/full/6-7-8-fork-test/6-7-8.test-fork.ts",
"chars": 15374,
"preview": "import { expect } from 'chai';\nimport hre from 'hardhat';\nimport {\n AddressesProvider,\n AttestationsRegistry,\n Attest"
},
{
"path": "tasks/deploy-tasks/full/6-deploy-sismo-addresses-provider.task.ts",
"chars": 1627,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { DeployOptions"
},
{
"path": "tasks/deploy-tasks/full/7-upgrade-hydra-s1-accountbound-and-pythia-1-proxies.task.ts",
"chars": 3180,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { DeployOptions"
},
{
"path": "tasks/deploy-tasks/full/9-fork-test/9-upgrade-addresses-provider-on-testnets.test-fork.ts",
"chars": 13698,
"preview": "import { AvailableRootsRegistry } from '../../../../types/AvailableRootsRegistry';\nimport { CommitmentMapperRegistry } f"
},
{
"path": "tasks/deploy-tasks/full/9-upgrade-addresses-provider-on-testnets.task.ts",
"chars": 3211,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport {\n afterDeploy"
},
{
"path": "tasks/deploy-tasks/full/local/deploy-full-local.task.ts",
"chars": 5901,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { wrapCommonDep"
},
{
"path": "tasks/deploy-tasks/full/staging/deploy-sismo-addresses-provider-staging.task.ts",
"chars": 2386,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport {\n afterDeploy"
},
{
"path": "tasks/deploy-tasks/tests/deploy-mock-attestations-registry.task.ts",
"chars": 1583,
"preview": "import { BigNumberish } from 'ethers';\nimport { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from "
},
{
"path": "tasks/deploy-tasks/tests/deploy-mock-attester-and-core.task.ts",
"chars": 2458,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport {\n DeployOptio"
},
{
"path": "tasks/deploy-tasks/tests/deploy-mock-attester.task.ts",
"chars": 1954,
"preview": "import { BigNumber, BigNumberish } from 'ethers';\nimport { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironm"
},
{
"path": "tasks/deploy-tasks/tests/deploy-mock-contract-using-sismo-lib.task.ts",
"chars": 1557,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport {\n afterDeploy"
},
{
"path": "tasks/deploy-tasks/tests/deploy-zk-badgebound-erc721.task.ts",
"chars": 2529,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { getImplementa"
},
{
"path": "tasks/deploy-tasks/unit/attesters/hydra-s1/deploy-hydra-s1-accountbound-attester.task.ts",
"chars": 3681,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport {\n getDeployer"
},
{
"path": "tasks/deploy-tasks/unit/attesters/hydra-s1/deploy-hydra-s1-simple-attester.task.ts",
"chars": 3714,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport {\n getDeployer"
},
{
"path": "tasks/deploy-tasks/unit/attesters/hydra-s1/deploy-hydra-s1-verifier.task.ts",
"chars": 1458,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport {\n getDeployer"
},
{
"path": "tasks/deploy-tasks/unit/attesters/pythia-1/deploy-pythia-1-simple-attester.task.ts",
"chars": 3699,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport {\n getDeployer"
},
{
"path": "tasks/deploy-tasks/unit/attesters/pythia-1/deploy-pythia-1-verifier.task.ts",
"chars": 1433,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport {\n getDeployer"
},
{
"path": "tasks/deploy-tasks/unit/core/deploy-attestations-registry.task.ts",
"chars": 2002,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport {\n getDeployer"
},
{
"path": "tasks/deploy-tasks/unit/core/deploy-badges.task.ts",
"chars": 1695,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport {\n getDeployer"
},
{
"path": "tasks/deploy-tasks/unit/core/deploy-front.task.ts",
"chars": 1593,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport {\n getDeployer"
},
{
"path": "tasks/deploy-tasks/unit/core/deploy-sismo-addresses-provider.task.ts",
"chars": 17664,
"preview": "import { singletonFactory } from '../../../../utils/singletonFactory';\nimport { task } from 'hardhat/config';\nimport { H"
},
{
"path": "tasks/deploy-tasks/unit/periphery/deploy-available-roots-registry.task.ts",
"chars": 1870,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport {\n getDeployer"
},
{
"path": "tasks/deploy-tasks/unit/periphery/deploy-commitment-mapper-registry.task.ts",
"chars": 2604,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport {\n getDeployer"
},
{
"path": "tasks/deploy-tasks/unit/periphery/deploy-frontend-lib.task.ts",
"chars": 1845,
"preview": "import { FrontendLib } from '../../../../types/FrontendLib';\nimport { task } from 'hardhat/config';\nimport { HardhatRunt"
},
{
"path": "tasks/deploy-tasks/utils/deployment.ts",
"chars": 6354,
"preview": "import { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { SignerWithAddress } from '@nomiclabs/hardhat-ethers/"
},
{
"path": "tasks/deploy-tasks/utils/deployments-config-types.ts",
"chars": 2291,
"preview": "import { CommonTaskOptions } from '../../utils';\n\nexport interface DeployOptions extends CommonTaskOptions {\n // prefix"
},
{
"path": "tasks/deploy-tasks/utils/index.ts",
"chars": 74,
"preview": "export * from './deployment';\nexport * from './deployments-config-types';\n"
},
{
"path": "tasks/deploy-tasks/zkdrop/deploy-mergooor-pass.task.ts",
"chars": 1354,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { DeployOptions"
},
{
"path": "tasks/deploy-tasks/zkdrop/deploy-ziki-pass-staging.task.ts",
"chars": 1345,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { DeployOptions"
},
{
"path": "tasks/deploy-tasks/zkdrop/deploy-ziki-pass-testnet.task.ts",
"chars": 1335,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { DeployOptions"
},
{
"path": "tasks/helpers/authorizations/access-control-grant-role.task.ts",
"chars": 2500,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { AccessControl"
},
{
"path": "tasks/helpers/authorizations/access-control-revoke-role.task.ts",
"chars": 2538,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { AccessControl"
},
{
"path": "tasks/helpers/authorizations/attestations-registry-authorize-range.task.ts",
"chars": 4077,
"preview": "import { ethers } from 'ethers';\nimport { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardh"
},
{
"path": "tasks/helpers/authorizations/attestations-registry-transfer-ownership.task.ts",
"chars": 1144,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { deploymentsCo"
},
{
"path": "tasks/helpers/authorizations/change-proxy-admin.task.ts",
"chars": 1761,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { TransparentUp"
},
{
"path": "tasks/helpers/authorizations/ownable-transfer-ownership.task.ts",
"chars": 2933,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { Ownable__fact"
},
{
"path": "tasks/helpers/forge-create2-transaction.task.ts",
"chars": 9071,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\n\nasync function printA"
},
{
"path": "tasks/helpers/print-accounts.task.ts",
"chars": 2659,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\n\nasync function printA"
},
{
"path": "tasks/helpers/print-storage-layout.task.ts",
"chars": 323,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\n\nasync function printS"
},
{
"path": "tasks/helpers/proxy/upgrade-proxy.task.ts",
"chars": 2728,
"preview": "import { ethers } from 'ethers';\nimport { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardh"
},
{
"path": "tasks/helpers/verify-contract.task.ts",
"chars": 1932,
"preview": "import { task } from 'hardhat/config';\nimport { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport fs from 'fs';\ni"
},
{
"path": "tasks/utils/common-options.ts",
"chars": 776,
"preview": "import { HardhatRuntimeEnvironment } from 'hardhat/types';\nimport { CommonTaskOptions } from './types';\nimport { DeployO"
},
{
"path": "tasks/utils/confirm.ts",
"chars": 921,
"preview": "import readline from 'readline';\nimport { CommonTaskOptions } from './types';\n\nexport function confirm(): Promise<void> "
},
{
"path": "tasks/utils/index.ts",
"chars": 86,
"preview": "export * from './common-options';\nexport * from './confirm';\nexport * from './types';\n"
},
{
"path": "tasks/utils/relayer.ts",
"chars": 611,
"preview": "import { DefenderRelayProvider, DefenderRelaySigner } from 'defender-relay-client/lib/ethers';\nimport { Signer } from 'e"
},
{
"path": "tasks/utils/types.ts",
"chars": 136,
"preview": "export interface CommonTaskOptions {\n // Enable logging\n log?: boolean;\n // Manually confirm deployment\n manualConfi"
},
{
"path": "test/e2e/e2e.test.ts",
"chars": 17474,
"preview": "import { expect } from 'chai';\nimport hre from 'hardhat';\nimport {\n AttestationsRegistry,\n AvailableRootsRegistry,\n B"
},
{
"path": "test/unit/attesters/hydra-s1/hydra-s1-accountbound-attester.test.ts",
"chars": 41256,
"preview": "import { encodeAccountBoundAttestationExtraData } from '../../../utils/hydra-s1-accountbound';\nimport { SignerWithAddres"
},
{
"path": "test/unit/attesters/hydra-s1/hydra-s1-simple-attester.test.ts",
"chars": 16511,
"preview": "import { expect } from 'chai';\nimport hre from 'hardhat';\nimport {\n AttestationsRegistry,\n AvailableRootsRegistry,\n B"
},
{
"path": "test/unit/attesters/pythia-1/pythia-1-simple-attester.test.ts",
"chars": 6488,
"preview": "import { expect } from 'chai';\nimport hre from 'hardhat';\nimport { AttestationsRegistry, Badges, Pythia1SimpleAttester }"
},
{
"path": "test/unit/core/attestations-registry/attestations-registry-config-logic.test.ts",
"chars": 45150,
"preview": "import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';\nimport { expect } from 'chai';\nimport hre, { ethe"
},
{
"path": "test/unit/core/attestations-registry/attestations-registry.test.ts",
"chars": 24517,
"preview": "import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';\nimport { expect } from 'chai';\nimport { BigNumber"
},
{
"path": "test/unit/core/badges.test.ts",
"chars": 14124,
"preview": "import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';\nimport { expect } from 'chai';\nimport hre, { ethe"
},
{
"path": "test/unit/core/front.test.ts",
"chars": 16240,
"preview": "import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';\nimport { expect } from 'chai';\nimport { BigNumber"
},
{
"path": "test/unit/core/utils/sismo-addresses-provider.test.ts",
"chars": 12379,
"preview": "import { AvailableRootsRegistry } from './../../../../types/AvailableRootsRegistry';\nimport { CommitmentMapperRegistry }"
},
{
"path": "test/unit/libs/using-sismo/using-sismo.test.ts",
"chars": 35619,
"preview": "import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';\nimport { EddsaPublicKey, HydraS1Account, KVMerkle"
},
{
"path": "test/unit/periphery/utils/available-roots-registry.test.ts",
"chars": 15341,
"preview": "import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';\nimport { expect } from 'chai';\nimport hre, { ethe"
},
{
"path": "test/unit/periphery/utils/commitment-mapper-registry.test.ts",
"chars": 9926,
"preview": "import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';\nimport { CommitmentMapperTester } from '@sismo-co"
},
{
"path": "test/unit/periphery/utils/frontend-lib.test.ts",
"chars": 3044,
"preview": "import { expect } from 'chai';\nimport hre from 'hardhat';\n\nimport { MockHydraS1SimpleAttester__factory } from './../../."
},
{
"path": "test/unit/zkdrop/zk-badgebound-erc721.test.ts",
"chars": 35759,
"preview": "import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';\nimport { EddsaPublicKey, HydraS1Account, KVMerkle"
},
{
"path": "test/utils/attestation-logic.ts",
"chars": 185,
"preview": "import { BigNumber } from 'ethers';\n\nexport const computeId = (shardId: number, id: number): BigNumber => {\n return Big"
},
{
"path": "test/utils/evm.ts",
"chars": 1779,
"preview": "import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';\nimport { HardhatRuntimeEnvironment } from 'hardha"
},
{
"path": "test/utils/expectEvent.ts",
"chars": 184,
"preview": "export const getEventArgs = (events: any, name: string) => {\n const event = events && events.find((e: any) => e.event ="
},
{
"path": "test/utils/hydra-s1-accountbound.ts",
"chars": 3793,
"preview": "import { BigNumber, BigNumberish, ethers } from 'ethers';\nimport {\n ACCOUNTS_TREE_HEIGHT,\n buildPoseidon,\n KVMerkleTr"
},
{
"path": "test/utils/hydra-s1.ts",
"chars": 13836,
"preview": "import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';\nimport { CommitmentMapperTester, getOwnershipMsg "
},
{
"path": "test/utils/index.ts",
"chars": 186,
"preview": "export * from './setup';\nexport * from './expectEvent';\nexport * from './evm';\nexport * from './attestation-logic';\nexpo"
},
{
"path": "test/utils/pythia-1.ts",
"chars": 2233,
"preview": "import {\n EddsaAccount,\n EddsaPublicKey,\n EddsaSignature,\n buildPoseidon,\n SNARK_FIELD,\n} from '@sismo-core/crypto'"
},
{
"path": "test/utils/setup.ts",
"chars": 1355,
"preview": "import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';\nimport { BigNumber } from 'ethers';\nimport { Edds"
},
{
"path": "test/utils/test-helpers.ts",
"chars": 7177,
"preview": "import { BigNumber, BigNumberish, Contract, ContractTransaction } from 'ethers';\nimport hre from 'hardhat';\nimport {\n A"
},
{
"path": "tsconfig.json",
"chars": 372,
"preview": "{\n \"compilerOptions\": {\n \"target\": \"es2018\",\n \"module\": \"commonjs\",\n \"strict\": true,\n \"esModuleInterop\": tr"
},
{
"path": "utils/constants.ts",
"chars": 205,
"preview": "import { ethers, BytesLike } from 'ethers';\nimport { toUtf8Bytes } from 'ethers/lib/utils';\n\nexport const EVENT_TRIGGERE"
},
{
"path": "utils/index.ts",
"chars": 54,
"preview": "export * from './constants';\nexport * from './proxy';\n"
},
{
"path": "utils/proxy.ts",
"chars": 491,
"preview": "import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';\nimport { BaseContract, utils } from 'ethers';\n\nex"
},
{
"path": "utils/singletonFactory.ts",
"chars": 2867,
"preview": "export const singletonFactory = {\n // mainnet\n 1: {\n gasPrice: 100000000000,\n gasLimit: 100000,\n signerAddres"
}
]
About this extraction
This page contains the full source code of the sismo-core/sismo-badges GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 150 files (870.5 KB), approximately 218.0k tokens, and a symbol index with 229 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.