Verified contractPartial
NijiP2PEthPool
Address0x9c6bcbfd16e7cb0cf7b9cb7d4b9cdeb29b25d8e9
- Balance
0 ETH
- Transactions
2
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- Via IR
- yes
- License
- Not stated
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,282,467
- Creation transaction
- 0x3925182de7…3c39dfbd48
14 files
- src/NijiP2PEthPool.solmain12.87 KB
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3.07 KB
- lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol2.44 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.77 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol931 B
- lib/openzeppelin-contracts/contracts/utils/Errors.sol864 B
- lib/openzeppelin-contracts/contracts/utils/LowLevelCall.sol5.52 KB
- lib/openzeppelin-contracts/contracts/utils/Pausable.sol2.67 KB
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol4.73 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.15 KB
- src/zk/Groth16Verifier.sol7.93 KB
- src/zk/IPoseidonT3.sol148 B
- src/zk/IPoseidonT4.sol143 B
- src/zk/MerkleTreeWithHistory.sol2.89 KB
src/NijiP2PEthPool.sol
pragma solidity 0.8.28;
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {MerkleTreeWithHistory} from "./zk/MerkleTreeWithHistory.sol";
import {IPoseidonT4} from "./zk/IPoseidonT4.sol";
import {Groth16Verifier} from "./zk/Groth16Verifier.sol";
contract NijiP2PEthPool is ReentrancyGuard, Pausable, Ownable2Step, MerkleTreeWithHistory {
using Address for address payable;
enum Status { NONE, LOCKED, PAID, DISPUTED, SETTLED, REFUNDED }
struct PoolOffer {
uint256 id;
address seller;
uint256 denomId;
uint256 amount;
uint256 rate;
bytes32 commitment;
bool cancelled;
uint256 activeTradeId;
}
struct PoolTrade {
uint256 id;
uint256 offerId;
address seller;
address buyer;
uint256 amount;
uint256 rate;
Status status;
uint64 lockedAt;
uint64 paidAt;
address arbiterPin;
}
INijiP2PArbiter public arbiter;
Groth16Verifier public immutable verifier;
IPoseidonT4 public immutable leafHasher;
uint256[] public denominations;
mapping(bytes32 => uint256) public offerOfCommitment;
mapping(bytes32 => bool) public spentNullifiers;
mapping(bytes32 => bool) public commitmentSpent;
mapping(bytes32 => uint256) public depositDenomOf;
mapping(uint256 => PoolOffer) public offers;
mapping(uint256 => PoolTrade) public trades;
mapping(address => uint256) public ethCredit;
uint256 public offerCounter;
uint256 public tradeCounter;
uint256 public constant TRADE_WINDOW = 20 minutes;
uint256 public constant CONFIRM_WINDOW = 20 minutes;
event Deposited(bytes32 indexed commitment, uint32 indexed leafIndex, uint256 indexed denomId, address seller, uint256 amount);
event Withdrawn(bytes32 indexed nullifierHash, uint256 indexed denomId, address indexed to);
event EthClaimed(address indexed to, uint256 amount);
event OfferCreated(uint256 indexed id, address indexed seller, uint256 amount, uint256 rate, bytes32 commitment);
event OfferCancelled(uint256 indexed id);
event TradeLocked(uint256 indexed id, uint256 indexed offerId, address indexed buyer);
event Paid(uint256 indexed id);
event Settled(uint256 indexed id, address indexed buyer, uint256 amount);
event Refunded(uint256 indexed id, address indexed seller);
event Disputed(uint256 indexed id, address indexed by, string reason);
event Resolved(uint256 indexed id, bool buyerWins, address indexed arbiter, string note);
event ArbiterSet(address indexed arbiter);
modifier onlyArbiter() { require(arbiter.isArbiter(msg.sender), "NOT_ARBITER"); _; }
constructor(address hasher_, address leafHasher_, address verifier_)
MerkleTreeWithHistory(hasher_)
Ownable(msg.sender)
{
require(verifier_ != address(0), "ZERO_VERIFIER");
require(leafHasher_ != address(0), "ZERO_LEAF_HASHER");
verifier = Groth16Verifier(verifier_);
leafHasher = IPoseidonT4(leafHasher_);
denominations.push(0.01 ether);
denominations.push(0.05 ether);
denominations.push(0.1 ether);
denominations.push(0.5 ether);
denominations.push(1 ether);
}
function setArbiter(address a) external onlyOwner {
require(a != address(0), "ZERO_ARBITER");
arbiter = INijiP2PArbiter(a);
emit ArbiterSet(a);
}
function _requireNoteTradeFree(bytes32 commitment) private view {
uint256 oid = offerOfCommitment[commitment];
if (oid != 0 && oid != type(uint256).max) {
require(offers[oid].activeTradeId == 0, "TRADE_ACTIVE");
}
}
function pause() external onlyOwner { _pause(); }
function unpause() external onlyOwner { _unpause(); }
function claim() external nonReentrant whenNotPaused {
uint256 amt = ethCredit[msg.sender];
require(amt != 0, "NOTHING_TO_CLAIM");
ethCredit[msg.sender] = 0;
payable(msg.sender).sendValue(amt);
emit EthClaimed(msg.sender, amt);
}
function deposit(bytes32 commitment, uint256 denomId) external payable nonReentrant whenNotPaused {
_deposit(commitment, denomId);
}
function _deposit(bytes32 commitment, uint256 denomId) private {
require(commitment != bytes32(0), "BAD_COMMITMENT");
require(denomId < denominations.length, "BAD_DENOM");
require(msg.value == denominations[denomId], "BAD_VALUE");
require(offerOfCommitment[commitment] == 0, "COMMITMENT_EXISTS");
uint32 leafIndex = _insert(commitment);
offerOfCommitment[commitment] = type(uint256).max;
depositDenomOf[commitment] = denomId;
emit Deposited(commitment, leafIndex, denomId, msg.sender, msg.value);
}
function withdraw(
uint[2] calldata a,
uint[2][2] calldata b,
uint[2] calldata c,
bytes32 nullifierHash,
address recipient,
uint256 denomId,
bytes32 merkleRoot,
bytes32 commitment
) external nonReentrant whenNotPaused {
require(!spentNullifiers[nullifierHash], "NOTE_SPENT");
require(!commitmentSpent[commitment], "NOTE_SPENT");
require(isKnownRoot(merkleRoot), "UNKNOWN_ROOT");
require(denomId < denominations.length, "BAD_DENOM");
require(depositDenomOf[commitment] == denomId, "DENOM_MISMATCH");
require(recipient != address(0), "BAD_RECIPIENT");
_requireNoteTradeFree(commitment);
uint[6] memory pubSignals = [
uint256(nullifierHash),
uint256(uint160(recipient)),
denomId,
0,
uint256(merkleRoot),
uint256(commitment)
];
require(verifier.verifyProof(a, b, c, pubSignals), "INVALID_PROOF");
spentNullifiers[nullifierHash] = true;
commitmentSpent[commitment] = true;
payable(recipient).sendValue(denominations[denomId]);
emit Withdrawn(nullifierHash, denomId, recipient);
}
function createOffer(uint256 denomId, uint256 rate, bytes32 commitment)
external payable nonReentrant whenNotPaused returns (uint256 id)
{
_deposit(commitment, denomId);
id = ++offerCounter;
PoolOffer storage o = offers[id];
o.id = id;
o.seller = msg.sender;
o.denomId = denomId;
o.amount = denominations[denomId];
o.rate = rate;
o.commitment = commitment;
offerOfCommitment[commitment] = id;
emit OfferCreated(id, msg.sender, o.amount, rate, commitment);
}
function cancelOffer(uint256 offerId) external {
PoolOffer storage o = offers[offerId];
require(o.seller == msg.sender, "NOT_SELLER");
require(!o.cancelled, "ALREADY_CANCELLED");
require(o.activeTradeId == 0, "TRADE_ACTIVE");
o.cancelled = true;
emit OfferCancelled(offerId);
}
function takeOffer(uint256 offerId) external returns (uint256 tid) {
PoolOffer storage o = offers[offerId];
require(!o.cancelled && o.activeTradeId == 0, "OFFER_TAKEN");
require(offerOfCommitment[o.commitment] != 0, "OFFER_UNBACKED");
require(!commitmentSpent[o.commitment], "OFFER_UNBACKED");
require(msg.sender != o.seller, "SELF_TAKE");
tid = ++tradeCounter;
o.activeTradeId = tid;
PoolTrade storage t = trades[tid];
t.id = tid;
t.offerId = offerId;
t.seller = o.seller;
t.buyer = msg.sender;
t.amount = o.amount;
t.rate = o.rate;
t.status = Status.LOCKED;
t.lockedAt = uint64(block.timestamp);
emit TradeLocked(tid, offerId, msg.sender);
}
function markPaid(uint256 tid) external {
PoolTrade storage t = trades[tid];
require(t.buyer == msg.sender && t.status == Status.LOCKED, "BAD_STATE");
require(block.timestamp <= t.lockedAt + TRADE_WINDOW, "PAY_WINDOW_OVER");
t.status = Status.PAID;
t.paidAt = uint64(block.timestamp);
emit Paid(tid);
}
function release(
uint256 tid,
uint[2] calldata a,
uint[2][2] calldata b,
uint[2] calldata c,
bytes32 nullifierHash,
bytes32 merkleRoot
) external nonReentrant whenNotPaused {
PoolTrade storage t = trades[tid];
PoolOffer storage o = offers[t.offerId];
require(t.seller == msg.sender && t.status == Status.PAID, "BAD_STATE");
require(!spentNullifiers[nullifierHash], "NOTE_SPENT");
require(isKnownRoot(merkleRoot), "UNKNOWN_ROOT");
uint[6] memory pubSignals = [
uint256(nullifierHash),
uint256(uint160(t.buyer)),
o.denomId,
0,
uint256(merkleRoot),
uint256(o.commitment)
];
require(verifier.verifyProof(a, b, c, pubSignals), "INVALID_PROOF");
spentNullifiers[nullifierHash] = true;
commitmentSpent[o.commitment] = true;
ethCredit[t.buyer] += t.amount;
t.status = Status.SETTLED;
o.activeTradeId = 0;
o.cancelled = true;
emit Settled(tid, t.buyer, t.amount);
}
function refundExpired(
uint256 tid,
uint[2] calldata a,
uint[2][2] calldata b,
uint[2] calldata c,
bytes32 nullifierHash,
bytes32 merkleRoot
) external nonReentrant whenNotPaused {
PoolTrade storage t = trades[tid];
PoolOffer storage o = offers[t.offerId];
require(t.status == Status.LOCKED, "BAD_STATE");
require(block.timestamp > t.lockedAt + TRADE_WINDOW, "STILL_IN_WINDOW");
require(!spentNullifiers[nullifierHash], "NOTE_SPENT");
require(isKnownRoot(merkleRoot), "UNKNOWN_ROOT");
uint[6] memory pubSignals = [
uint256(nullifierHash),
uint256(uint160(t.seller)),
o.denomId,
0,
uint256(merkleRoot),
uint256(o.commitment)
];
require(verifier.verifyProof(a, b, c, pubSignals), "INVALID_PROOF");
spentNullifiers[nullifierHash] = true;
commitmentSpent[o.commitment] = true;
ethCredit[t.seller] += t.amount;
t.status = Status.REFUNDED;
o.activeTradeId = 0;
o.cancelled = true;
emit Refunded(tid, t.seller);
}
function raiseDispute(uint256 tid, string calldata reason) external {
PoolTrade storage t = trades[tid];
bool isParty = msg.sender == t.seller || msg.sender == t.buyer;
require(isParty, "NOT_PARTY");
require(address(arbiter) != address(0), "NO_ARBITER");
if (msg.sender == t.buyer) {
require(t.status == Status.PAID, "BAD_STATE");
require(block.timestamp > t.paidAt + CONFIRM_WINDOW, "SELLER_WINDOW");
} else {
bool expiredLock = t.status == Status.LOCKED && block.timestamp > t.lockedAt + TRADE_WINDOW;
require(t.status == Status.PAID || expiredLock, "BAD_STATE");
}
t.arbiterPin = address(arbiter);
t.status = Status.DISPUTED;
emit Disputed(tid, msg.sender, reason);
}
function arbiterResolve(uint256 tid, bool buyerWins, string calldata note)
external nonReentrant whenNotPaused
{
PoolTrade storage t = trades[tid];
PoolOffer storage o = offers[t.offerId];
require(t.status == Status.DISPUTED, "BAD_STATE");
require(t.arbiterPin != address(0), "DISPUTE_NOT_PINNED");
require(INijiP2PArbiter(t.arbiterPin).isArbiter(msg.sender), "NOT_ARBITER");
require(!commitmentSpent[o.commitment], "ALREADY_SPENT");
commitmentSpent[o.commitment] = true;
ethCredit[buyerWins ? t.buyer : t.seller] += t.amount;
t.status = buyerWins ? Status.SETTLED : Status.REFUNDED;
o.activeTradeId = 0;
o.cancelled = true;
emit Resolved(tid, buyerWins, msg.sender, note);
}
function denomCount() external view returns (uint256) { return denominations.length; }
}
interface INijiP2PArbiter {
function isArbiter(address) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/access/Ownable.sol
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.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.
*
* The initial owner is set to the address provided by the deployer. 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 Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling 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 {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_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);
}
}
lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v5.5.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
import {LowLevelCall} from "./LowLevelCall.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
if (LowLevelCall.callNoReturn(recipient, amount, "")) {
// call successful, nothing to do
return;
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @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 or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* 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.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @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`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
bool success = LowLevelCall.callNoReturn(target, value, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
bool success = LowLevelCall.staticcallNoReturn(target, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
bool success = LowLevelCall.delegatecallNoReturn(target, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*
* NOTE: This function is DEPRECATED and may be removed in the next major release.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (success && (returndata.length > 0 || target.code.length > 0)) {
return returndata;
} else if (success) {
revert AddressEmptyCode(target);
} else if (returndata.length > 0) {
LowLevelCall.bubbleRevert(returndata);
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else if (returndata.length > 0) {
LowLevelCall.bubbleRevert(returndata);
} else {
revert Errors.FailedCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @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;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts/contracts/utils/Errors.sol
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
lib/openzeppelin-contracts/contracts/utils/LowLevelCall.sol
// OpenZeppelin Contracts (last updated v5.6.0) (utils/LowLevelCall.sol)
pragma solidity ^0.8.20;
/**
* @dev Library of low level call functions that implement different calling strategies to deal with the return data.
*
* WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
* to use the {Address} library instead.
*/
library LowLevelCall {
/// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
function callNoReturn(address target, bytes memory data) internal returns (bool success) {
return callNoReturn(target, 0, data);
}
/// @dev Same as {callNoReturn-address-bytes}, but allows specifying the value to be sent in the call.
function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function callReturn64Bytes(
address target,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
return callReturn64Bytes(target, 0, data);
}
/// @dev Same as {callReturn64Bytes-address-bytes}, but allows specifying the value to be sent in the call.
function callReturn64Bytes(
address target,
uint256 value,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function staticcallReturn64Bytes(
address target,
bytes memory data
) internal view returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function delegatecallReturn64Bytes(
address target,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Returns the size of the return data buffer.
function returnDataSize() internal pure returns (uint256 size) {
assembly ("memory-safe") {
size := returndatasize()
}
}
/// @dev Returns a buffer containing the return data from the last call.
function returnData() internal pure returns (bytes memory result) {
assembly ("memory-safe") {
result := mload(0x40)
mstore(result, returndatasize())
returndatacopy(add(result, 0x20), 0x00, returndatasize())
mstore(0x40, add(result, add(0x20, returndatasize())))
}
}
/// @dev Revert with the return data from the last call.
function bubbleRevert() internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
}
function bubbleRevert(bytes memory returndata) internal pure {
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
}
}
lib/openzeppelin-contracts/contracts/utils/Pausable.sol
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.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 Pausable is Context {
bool private _paused;
/**
* @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);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @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());
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
src/zk/Groth16Verifier.sol
pragma solidity >=0.7.0 <0.9.0;
contract Groth16Verifier {
uint256 constant r = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint256 constant q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
uint256 constant alphax = 20491192805390485299153009773594534940189261866228447918068658471970481763042;
uint256 constant alphay = 9383485363053290200918347156157836566562967994039712273449902621266178545958;
uint256 constant betax1 = 4252822878758300859123897981450591353533073413197771768651442665752259397132;
uint256 constant betax2 = 6375614351688725206403948262868962793625744043794305715222011528459656738731;
uint256 constant betay1 = 21847035105528745403288232691147584728191162732299865338377159692350059136679;
uint256 constant betay2 = 10505242626370262277552901082094356697409835680220590971873171140371331206856;
uint256 constant gammax1 = 11559732032986387107991004021392285783925812861821192530917403151452391805634;
uint256 constant gammax2 = 10857046999023057135944570762232829481370756359578518086990519993285655852781;
uint256 constant gammay1 = 4082367875863433681332203403145435568316851327593401208105741076214120093531;
uint256 constant gammay2 = 8495653923123431417604973247489272438418190587263600148770280649306958101930;
uint256 constant deltax1 = 5691148068378261546272234026164431778443804389255694748733137802030054612114;
uint256 constant deltax2 = 17459401919803238418862287219191867050230614511634783558974802942323981718129;
uint256 constant deltay1 = 12892197819269769179086392138716471892129787725425894635571839245795954174504;
uint256 constant deltay2 = 15647588188318340569439424143076689487443859610960158399781068877341067949471;
uint256 constant IC0x = 17000826867433676632357715367664081161757734483157366322068062867947181040542;
uint256 constant IC0y = 4379230222829347733313428669815797960780934390625784557706602028677553006784;
uint256 constant IC1x = 20907107917818558758617822412744270951972636060525816880856359514931037670359;
uint256 constant IC1y = 10240448741319724955637951167514844231030778897956819308524822318204414429248;
uint256 constant IC2x = 20163007795956736848452421700817009715152912541306771826150848117059431466609;
uint256 constant IC2y = 870373682240034631245838936434440718936165047776256447368088023114245659405;
uint256 constant IC3x = 21860812141579503273045680150636424379951405750792674882168390070922328440551;
uint256 constant IC3y = 19915678136157067311276111150823959906741167154613651037323782643473421018483;
uint256 constant IC4x = 10507152668002082899649128764205740986320908513385482046506539264713070544430;
uint256 constant IC4y = 2154405029163696129232065409927666266011425469449069697627566848244279089876;
uint256 constant IC5x = 6219626797845345362421275301697950815697630147235650810731819624553269859083;
uint256 constant IC5y = 18400312621252294201385029791407565555533084935076493030048572249503986519981;
uint256 constant IC6x = 8078875635303809713574178601566449147074497377623708552338052246752339426234;
uint256 constant IC6y = 1001025495067815895521634622709190688505161896598513170723194052995932359111;
uint16 constant pVk = 0;
uint16 constant pPairing = 128;
uint16 constant pLastMem = 896;
function verifyProof(uint[2] calldata _pA, uint[2][2] calldata _pB, uint[2] calldata _pC, uint[6] calldata _pubSignals) public view returns (bool) {
assembly {
function checkField(v) {
if iszero(lt(v, r)) {
mstore(0, 0)
return(0, 0x20)
}
}
function g1_mulAccC(pR, x, y, s) {
let success
let mIn := mload(0x40)
mstore(mIn, x)
mstore(add(mIn, 32), y)
mstore(add(mIn, 64), s)
success := staticcall(sub(gas(), 2000), 7, mIn, 96, mIn, 64)
if iszero(success) {
mstore(0, 0)
return(0, 0x20)
}
mstore(add(mIn, 64), mload(pR))
mstore(add(mIn, 96), mload(add(pR, 32)))
success := staticcall(sub(gas(), 2000), 6, mIn, 128, pR, 64)
if iszero(success) {
mstore(0, 0)
return(0, 0x20)
}
}
function checkPairing(pA, pB, pC, pubSignals, pMem) -> isOk {
let _pPairing := add(pMem, pPairing)
let _pVk := add(pMem, pVk)
mstore(_pVk, IC0x)
mstore(add(_pVk, 32), IC0y)
g1_mulAccC(_pVk, IC1x, IC1y, calldataload(add(pubSignals, 0)))
g1_mulAccC(_pVk, IC2x, IC2y, calldataload(add(pubSignals, 32)))
g1_mulAccC(_pVk, IC3x, IC3y, calldataload(add(pubSignals, 64)))
g1_mulAccC(_pVk, IC4x, IC4y, calldataload(add(pubSignals, 96)))
g1_mulAccC(_pVk, IC5x, IC5y, calldataload(add(pubSignals, 128)))
g1_mulAccC(_pVk, IC6x, IC6y, calldataload(add(pubSignals, 160)))
mstore(_pPairing, calldataload(pA))
mstore(add(_pPairing, 32), mod(sub(q, calldataload(add(pA, 32))), q))
mstore(add(_pPairing, 64), calldataload(pB))
mstore(add(_pPairing, 96), calldataload(add(pB, 32)))
mstore(add(_pPairing, 128), calldataload(add(pB, 64)))
mstore(add(_pPairing, 160), calldataload(add(pB, 96)))
mstore(add(_pPairing, 192), alphax)
mstore(add(_pPairing, 224), alphay)
mstore(add(_pPairing, 256), betax1)
mstore(add(_pPairing, 288), betax2)
mstore(add(_pPairing, 320), betay1)
mstore(add(_pPairing, 352), betay2)
mstore(add(_pPairing, 384), mload(add(pMem, pVk)))
mstore(add(_pPairing, 416), mload(add(pMem, add(pVk, 32))))
mstore(add(_pPairing, 448), gammax1)
mstore(add(_pPairing, 480), gammax2)
mstore(add(_pPairing, 512), gammay1)
mstore(add(_pPairing, 544), gammay2)
mstore(add(_pPairing, 576), calldataload(pC))
mstore(add(_pPairing, 608), calldataload(add(pC, 32)))
mstore(add(_pPairing, 640), deltax1)
mstore(add(_pPairing, 672), deltax2)
mstore(add(_pPairing, 704), deltay1)
mstore(add(_pPairing, 736), deltay2)
let success := staticcall(sub(gas(), 2000), 8, _pPairing, 768, _pPairing, 0x20)
isOk := and(success, mload(_pPairing))
}
let pMem := mload(0x40)
mstore(0x40, add(pMem, pLastMem))
checkField(calldataload(add(_pubSignals, 0)))
checkField(calldataload(add(_pubSignals, 32)))
checkField(calldataload(add(_pubSignals, 64)))
checkField(calldataload(add(_pubSignals, 96)))
checkField(calldataload(add(_pubSignals, 128)))
checkField(calldataload(add(_pubSignals, 160)))
let isValid := checkPairing(_pA, _pB, _pC, _pubSignals, pMem)
mstore(0, isValid)
return(0, 0x20)
}
}
}
src/zk/IPoseidonT3.sol
pragma solidity 0.8.28;
interface IPoseidonT3 {
function poseidon(bytes32[2] calldata input) external pure returns (bytes32);
}
src/zk/IPoseidonT4.sol
pragma solidity 0.8.28;
interface IPoseidonT4 {
function poseidon(bytes32[4] calldata input) external pure returns (bytes32);
}
src/zk/MerkleTreeWithHistory.sol
pragma solidity 0.8.28;
import {IPoseidonT3} from "./IPoseidonT3.sol";
abstract contract MerkleTreeWithHistory {
uint256 public constant MERKLE_TREE_HEIGHT = 20;
uint256 public constant ROOT_HISTORY_SIZE = 30;
bytes32 public constant ZERO_VALUE = bytes32(uint256(21663839004416932945302849793973061578898396969786164423988850241217061365062));
IPoseidonT3 public hasher;
bytes32[MERKLE_TREE_HEIGHT] public zeros;
bytes32[MERKLE_TREE_HEIGHT] public fillers;
bytes32[ROOT_HISTORY_SIZE] public roots;
uint32 public currentRootIndex = 0;
uint32 public nextIndex = 0;
event NewCommitment(bytes32 indexed commitment, uint32 indexed leafIndex, uint256 timestamp);
event NewRoot(bytes32 indexed root, uint32 indexed rootIndex);
constructor(address hasher_) {
require(hasher_ != address(0), "ZERO_HASHER");
hasher = IPoseidonT3(hasher_);
bytes32 z = ZERO_VALUE;
for (uint256 i = 0; i < MERKLE_TREE_HEIGHT; i++) {
zeros[i] = z;
fillers[i] = z;
z = hasher.poseidon([z, z]);
}
roots[0] = z;
emit NewRoot(roots[0], 0);
}
function _insert(bytes32 leaf) internal returns (uint32 index) {
uint32 _nextIndex = nextIndex;
require(_nextIndex < uint32(1) << MERKLE_TREE_HEIGHT, "TREE_FULL");
bytes32 current = leaf;
uint32 i = _nextIndex;
for (uint256 level = 0; level < MERKLE_TREE_HEIGHT; level++) {
if (i & 1 == 0) {
fillers[level] = current;
current = hasher.poseidon([current, zeros[level]]);
} else {
current = hasher.poseidon([fillers[level], current]);
}
i >>= 1;
}
currentRootIndex = uint32((currentRootIndex + 1) % ROOT_HISTORY_SIZE);
roots[currentRootIndex] = current;
nextIndex = _nextIndex + 1;
index = _nextIndex;
emit NewCommitment(leaf, index, block.timestamp);
emit NewRoot(current, currentRootIndex);
}
function isKnownRoot(bytes32 root) public view returns (bool) {
if (root == bytes32(0)) return false;
uint32 i = currentRootIndex;
for (uint256 count = 0; count < ROOT_HISTORY_SIZE; count++) {
if (roots[i] == root) return true;
if (i == 0) i = uint32(ROOT_HISTORY_SIZE);
i--;
}
return false;
}
function getLastRoot() public view returns (bytes32) {
return roots[currentRootIndex];
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"remappings": [
"@openzeppelin/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.