Verified contractExactUNLICENSED
NFTMarketplace
Address0x25f77d92b771cfa7ddf5944bbc0c4e688e2f4ee7
- Balance
0.02 ETH
- Transactions
9
- Compiler
solc 0.8.27
- Same code
Only this contract
Details
- Compiler
- solc 0.8.27+commit.40a35a09
- Language
- solidity
- Optimization
- No
- EVM version
- prague
- License
- UNLICENSED
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,699,153
- Creation transaction
- 0x3267e93844…720b947660
7 files
- src/Nightmarket.solmain9.38 KB
- lib/solady/src/tokens/ERC721.sol39.96 KB
- lib/solmate/src/auth/Owned.sol1.48 KB
- src/BabyJubjub.sol1.64 KB
- src/EncryptedERC721.sol24.39 KB
- src/groth16_verifier_addDataWithCheck.sol12.13 KB
- src/groth16_verifier_ecdh_poseidon_transfer_key_derivation.sol11.74 KB
src/Nightmarket.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import {EncryptedERC721} from "./EncryptedERC721.sol";
import {Owned} from "../lib/solmate/src/auth/Owned.sol";
/// @notice Decentralized marketplace for trading Cipher NFTs with encrypted data
/// @dev Implements offer-based trading with ZK-verified transfers that re-encrypt data for buyers
/// @author plsdlr
contract NFTMarketplace is Owned {
event OfferCreated(
uint256 indexed offerId,
address indexed buyer,
uint256 price
);
/// @notice Maps offer IDs to their corresponding offer details
mapping(uint256 => Offer) public offers;
/// @notice Allows the owner to shut down the market while people can still withdraw
bool public marketOpen;
/// @dev Reference to the EncryptedERC721 contract
EncryptedERC721 private erc721Cipher;
/// @notice Counter for total offers created (including cancelled ones)
uint256 public currentOffers;
/// @notice Stack of cancelled offer IDs available for reuse
/// @dev Using a stack to efficiently reuse cancelled offer slots
uint256[] public pointerEmptyOffers;
/// @notice Structure representing a buy offer
/// @dev An offer with price 0 and buyer address(0) is considered cancelled/empty
struct Offer {
/// @dev Address of the buyer making the offer
address buyer;
/// @dev Offer price in wei
uint256 price;
}
/// @notice Initializes the marketplace with the EncryptedERC721 contract address
/// @param _ERC721CipherAddress Address of the EncryptedERC721 contract
constructor(address _ERC721CipherAddress) Owned(msg.sender) {
require(_ERC721CipherAddress != address(0), "Invalid ERC721 address");
erc721Cipher = EncryptedERC721(_ERC721CipherAddress);
marketOpen = true;
}
// ============================================================
// ADMIN FUNCTIONS
// ============================================================
/// @notice Updates the EncryptedERC721 contract address
/// @dev Only callable by contract owner
/// @param newAddress New EncryptedERC721 contract address
function changeERC721Implementation(address newAddress) external onlyOwner {
erc721Cipher = EncryptedERC721(newAddress);
}
/// @notice Function to stop the Fullfilling
/// @dev Only callable by contract owner
function setMarket(bool _setMarket) external onlyOwner {
marketOpen = _setMarket;
}
// ============================================================
// OFFER MANAGEMENT
// ============================================================
/// @notice Creates a new buy offer
/// @dev Reuses cancelled offer slots when available, otherwise creates new slot
/// @dev Sent ETH becomes the offer price locked in the contract
function createOffer() external payable returns (uint256 offerId) {
require(msg.value > 0, "Offer must be > 0");
require(marketOpen == true, "Market Closed");
if (pointerEmptyOffers.length == 0) {
// No empty slots, create new offer at next index
offers[currentOffers] = Offer({
buyer: msg.sender,
price: msg.value
});
offerId = currentOffers;
currentOffers++;
} else {
// Reuse the most recently cancelled offer slot
offers[pointerEmptyOffers[pointerEmptyOffers.length - 1]] = Offer({
buyer: msg.sender,
price: msg.value
});
offerId = pointerEmptyOffers[pointerEmptyOffers.length - 1];
pointerEmptyOffers.pop();
}
emit OfferCreated(offerId, msg.sender, msg.value);
return offerId;
}
/// @notice Cancels an existing offer and refunds the buyer
/// @dev Only callable by the original buyer, follows checks-effects-interactions pattern
/// @param offerId ID of the offer to cancel
function cancelOffer(uint256 offerId) external {
require(offerId < currentOffers, "Invalid offer ID");
require(msg.sender == offers[offerId].buyer, "Only buyer can cancel");
require(offers[offerId].price != 0, "Offer already cancelled");
uint256 refundAmount = offers[offerId].price;
// State changes BEFORE external call (CEI pattern)
offers[offerId] = Offer({buyer: address(0), price: 0});
pointerEmptyOffers.push(offerId);
// External call last to prevent reentrancy
(bool success, ) = payable(msg.sender).call{value: refundAmount}("");
require(success, "Refund failed");
}
/// @notice Fulfills an offer by selling an NFT to the buyer
/// @dev Validates offer, pays seller, clears offer, then executes ZK-verified transfer
/// @param offerId ID of the offer to fulfill
/// @param from Seller address (must be msg.sender and current token owner)
/// @param to Buyer address (must match offer.buyer)
/// @param id Token ID being sold
/// @param _pA ZK proof parameter A for re-encryption
/// @param _pB ZK proof parameter B for re-encryption
/// @param _pC ZK proof parameter C for re-encryption
/// @param _pubSignals Public signals for ZK proof including buyer's public key
function fulfillOffer(
uint256 offerId,
address from,
address to,
uint256 id,
uint[2] calldata _pA,
uint[2][2] calldata _pB,
uint[2] calldata _pC,
uint[13] calldata _pubSignals
) external {
require(offerId < currentOffers, "Invalid offer ID");
require(msg.sender != offers[offerId].buyer, "Cannot sell to yourself");
require(offers[offerId].price != 0, "Offer cancelled or empty");
require(offers[offerId].buyer != address(0), "Invalid buyer");
require(from == msg.sender, "Only token owner can fulfill");
require(marketOpen == true, "Market Closed");
require(to == offers[offerId].buyer, "Recipient must be offer buyer");
// Store offer data BEFORE clearing (CEI pattern)
Offer memory offer = offers[offerId];
// Clear the offer and mark slot as reusable
offers[offerId] = Offer({buyer: address(0), price: 0});
pointerEmptyOffers.push(offerId);
// Pay the seller
(bool success, ) = payable(msg.sender).call{value: offer.price}("");
require(success, "Transfer failed");
// Execute ZK-verified transfer with re-encryption for buyer
erc721Cipher.verifiedTransferFrom(
from,
to,
id,
_pA,
_pB,
_pC,
_pubSignals
);
}
// ============================================================
// VIEW FUNCTIONS
// ============================================================
/// @notice Retrieves active offers within a specified range
/// @dev Filters out cancelled offers (buyer == address(0)), returns resized arrays
/// @param start Starting offer ID (inclusive)
/// @param end Ending offer ID (exclusive)
/// @return offerIds Array of active offer IDs in the range
/// @return activeOffers Array of corresponding offer details
function getOffers(
uint256 start,
uint256 end
)
external
view
returns (uint256[] memory offerIds, Offer[] memory activeOffers)
{
require(start < currentOffers, "Start exceeds current offers");
require(end <= currentOffers, "End exceeds current offers");
require(start < end, "Invalid range");
offerIds = new uint256[](end - start);
activeOffers = new Offer[](end - start);
uint arraySize = 0;
for (uint256 i = start; i < end; i++) {
if (offers[i].buyer != address(0)) {
offerIds[arraySize] = i;
activeOffers[arraySize] = offers[i];
arraySize = arraySize + 1;
}
}
// Resize arrays to actual count of active offers
assembly {
mstore(offerIds, arraySize)
mstore(activeOffers, arraySize)
}
}
/// @notice Retrieves all active offers made by a specific buyer
/// @dev Scans all offers and filters by buyer address, returns resized arrays
/// @param buyer Address of the buyer to query offers for
/// @return offerIds Array of offer IDs created by the buyer
/// @return userOffers Array of corresponding offer details
function getOffersByAddress(
address buyer
)
external
view
returns (uint256[] memory offerIds, Offer[] memory userOffers)
{
// Pre-allocate maximum possible size
offerIds = new uint256[](currentOffers);
userOffers = new Offer[](currentOffers);
uint256 arraySize = 0;
for (uint256 i = 0; i < currentOffers; i++) {
if (offers[i].buyer == buyer) {
offerIds[arraySize] = i;
userOffers[arraySize] = offers[i];
arraySize++;
}
}
// Resize arrays to actual count of buyer's offers
assembly {
mstore(offerIds, arraySize)
mstore(userOffers, arraySize)
}
}
}
lib/solady/src/tokens/ERC721.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple ERC721 implementation with storage hitchhiking.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC721.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/token/ERC721/ERC721.sol)
///
/// @dev Note:
/// - The ERC721 standard allows for self-approvals.
/// For performance, this implementation WILL NOT revert for such actions.
/// Please add any checks with overrides if desired.
/// - For performance, methods are made payable where permitted by the ERC721 standard.
/// - The `safeTransfer` functions use the identity precompile (0x4)
/// to copy memory internally.
///
/// If you are overriding:
/// - NEVER violate the ERC721 invariant:
/// the balance of an owner MUST always be equal to their number of ownership slots.
/// The transfer functions do not have an underflow guard for user token balances.
/// - Make sure all variables written to storage are properly cleaned
/// (e.g. the bool value for `isApprovedForAll` MUST be either 1 or 0 under the hood).
/// - Check that the overridden function is actually used in the function you want to
/// change the behavior of. Much of the code has been manually inlined for performance.
abstract contract ERC721 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev An account can hold up to 4294967295 tokens.
uint256 internal constant _MAX_ACCOUNT_BALANCE = 0xffffffff;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Only the token owner or an approved account can manage the token.
error NotOwnerNorApproved();
/// @dev The token does not exist.
error TokenDoesNotExist();
/// @dev The token already exists.
error TokenAlreadyExists();
/// @dev Cannot query the balance for the zero address.
error BalanceQueryForZeroAddress();
/// @dev Cannot mint or transfer to the zero address.
error TransferToZeroAddress();
/// @dev The token must be owned by `from`.
error TransferFromIncorrectOwner();
/// @dev The recipient's balance has overflowed.
error AccountBalanceOverflow();
/// @dev Cannot safely transfer to a contract that does not implement
/// the ERC721Receiver interface.
error TransferToNonERC721ReceiverImplementer();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Emitted when token `id` is transferred from `from` to `to`.
event Transfer(address indexed from, address indexed to, uint256 indexed id);
/// @dev Emitted when `owner` enables `account` to manage the `id` token.
event Approval(address indexed owner, address indexed account, uint256 indexed id);
/// @dev Emitted when `owner` enables or disables `operator` to manage all of their tokens.
event ApprovalForAll(address indexed owner, address indexed operator, bool isApproved);
/// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`.
uint256 private constant _TRANSFER_EVENT_SIGNATURE =
0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
/// @dev `keccak256(bytes("Approval(address,address,uint256)"))`.
uint256 private constant _APPROVAL_EVENT_SIGNATURE =
0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;
/// @dev `keccak256(bytes("ApprovalForAll(address,address,bool)"))`.
uint256 private constant _APPROVAL_FOR_ALL_EVENT_SIGNATURE =
0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ownership data slot of `id` is given by:
/// ```
/// mstore(0x00, id)
/// mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
/// let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
/// ```
/// Bits Layout:
/// - [0..159] `addr`
/// - [160..255] `extraData`
///
/// The approved address slot is given by: `add(1, ownershipSlot)`.
///
/// See: https://notes.ethereum.org/%40vbuterin/verkle_tree_eip
///
/// The balance slot of `owner` is given by:
/// ```
/// mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
/// mstore(0x00, owner)
/// let balanceSlot := keccak256(0x0c, 0x1c)
/// ```
/// Bits Layout:
/// - [0..31] `balance`
/// - [32..255] `aux`
///
/// The `operator` approval slot of `owner` is given by:
/// ```
/// mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, operator))
/// mstore(0x00, owner)
/// let operatorApprovalSlot := keccak256(0x0c, 0x30)
/// ```
uint256 private constant _ERC721_MASTER_SLOT_SEED = 0x7d8825530a5a2e7a << 192;
/// @dev Pre-shifted and pre-masked constant.
uint256 private constant _ERC721_MASTER_SLOT_SEED_MASKED = 0x0a5a2e7a00000000;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC721 METADATA */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the token collection name.
function name() public view virtual returns (string memory);
/// @dev Returns the token collection symbol.
function symbol() public view virtual returns (string memory);
/// @dev Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) public view virtual returns (string memory);
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC721 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the owner of token `id`.
///
/// Requirements:
/// - Token `id` must exist.
function ownerOf(uint256 id) public view virtual returns (address result) {
result = _ownerOf(id);
/// @solidity memory-safe-assembly
assembly {
if iszero(result) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Returns the number of tokens owned by `owner`.
///
/// Requirements:
/// - `owner` must not be the zero address.
function balanceOf(address owner) public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
// Revert if the `owner` is the zero address.
if iszero(owner) {
mstore(0x00, 0x8f4eb604) // `BalanceQueryForZeroAddress()`.
revert(0x1c, 0x04)
}
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
mstore(0x00, owner)
result := and(sload(keccak256(0x0c, 0x1c)), _MAX_ACCOUNT_BALANCE)
}
}
/// @dev Returns the account approved to manage token `id`.
///
/// Requirements:
/// - Token `id` must exist.
function getApproved(uint256 id) public view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
if iszero(shl(96, sload(ownershipSlot))) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
result := sload(add(1, ownershipSlot))
}
}
/// @dev Sets `account` as the approved account to manage token `id`.
///
/// Requirements:
/// - Token `id` must exist.
/// - The caller must be the owner of the token,
/// or an approved operator for the token owner.
///
/// Emits an {Approval} event.
function approve(address account, uint256 id) public payable virtual {
_approve(msg.sender, account, id);
}
/// @dev Returns whether `operator` is approved to manage the tokens of `owner`.
function isApprovedForAll(address owner, address operator)
public
view
virtual
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
mstore(0x1c, operator)
mstore(0x08, _ERC721_MASTER_SLOT_SEED_MASKED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x30))
}
}
/// @dev Sets whether `operator` is approved to manage the tokens of the caller.
///
/// Emits an {ApprovalForAll} event.
function setApprovalForAll(address operator, bool isApproved) public virtual {
/// @solidity memory-safe-assembly
assembly {
// Convert to 0 or 1.
isApproved := iszero(iszero(isApproved))
// Update the `isApproved` for (`msg.sender`, `operator`).
mstore(0x1c, operator)
mstore(0x08, _ERC721_MASTER_SLOT_SEED_MASKED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x30), isApproved)
// Emit the {ApprovalForAll} event.
mstore(0x00, isApproved)
// forgefmt: disable-next-item
log3(0x00, 0x20, _APPROVAL_FOR_ALL_EVENT_SIGNATURE, caller(), shr(96, shl(96, operator)))
}
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - The caller must be the owner of the token, or be approved to manage the token.
///
/// Emits a {Transfer} event.
function transferFrom(address from, address to, uint256 id) public payable virtual {
_beforeTokenTransfer(from, to, id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
let bitmaskAddress := shr(96, not(0))
from := and(bitmaskAddress, from)
to := and(bitmaskAddress, to)
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, caller()))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let ownershipPacked := sload(ownershipSlot)
let owner := and(bitmaskAddress, ownershipPacked)
// Revert if the token does not exist, or if `from` is not the owner.
if iszero(mul(owner, eq(owner, from))) {
// `TokenDoesNotExist()`, `TransferFromIncorrectOwner()`.
mstore(shl(2, iszero(owner)), 0xceea21b6a1148100)
revert(0x1c, 0x04)
}
// Load, check, and update the token approval.
{
mstore(0x00, from)
let approvedAddress := sload(add(1, ownershipSlot))
// Revert if the caller is not the owner, nor approved.
if iszero(or(eq(caller(), from), eq(caller(), approvedAddress))) {
if iszero(sload(keccak256(0x0c, 0x30))) {
mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
revert(0x1c, 0x04)
}
}
// Delete the approved address if any.
if approvedAddress { sstore(add(1, ownershipSlot), 0) }
}
// Update with the new owner.
sstore(ownershipSlot, xor(ownershipPacked, xor(from, to)))
// Decrement the balance of `from`.
{
let fromBalanceSlot := keccak256(0x0c, 0x1c)
sstore(fromBalanceSlot, sub(sload(fromBalanceSlot), 1))
}
// Increment the balance of `to`.
{
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x1c)
let toBalanceSlotPacked := add(sload(toBalanceSlot), 1)
// Revert if `to` is the zero address, or if the account balance overflows.
if iszero(mul(to, and(toBalanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
// `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
mstore(shl(2, iszero(to)), 0xea553b3401336cea)
revert(0x1c, 0x04)
}
sstore(toBalanceSlot, toBalanceSlotPacked)
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, from, to, id)
}
_afterTokenTransfer(from, to, id);
}
/// @dev Equivalent to `safeTransferFrom(from, to, id, "")`.
function safeTransferFrom(address from, address to, uint256 id) public payable virtual {
transferFrom(from, to, id);
if (_hasCode(to)) _checkOnERC721Received(from, to, id, "");
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - The caller must be the owner of the token, or be approved to manage the token.
/// - If `to` refers to a smart contract, it must implement
/// {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
///
/// Emits a {Transfer} event.
function safeTransferFrom(address from, address to, uint256 id, bytes calldata data)
public
payable
virtual
{
transferFrom(from, to, id);
if (_hasCode(to)) _checkOnERC721Received(from, to, id, data);
}
/// @dev Returns true if this contract implements the interface defined by `interfaceId`.
/// See: https://eips.ethereum.org/EIPS/eip-165
/// This function call must use less than 30000 gas.
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
let s := shr(224, interfaceId)
// ERC165: 0x01ffc9a7, ERC721: 0x80ac58cd, ERC721Metadata: 0x5b5e139f.
result := or(or(eq(s, 0x01ffc9a7), eq(s, 0x80ac58cd)), eq(s, 0x5b5e139f))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL QUERY FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns if token `id` exists.
function _exists(uint256 id) internal view virtual returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
result := iszero(iszero(shl(96, sload(add(id, add(id, keccak256(0x00, 0x20)))))))
}
}
/// @dev Returns the owner of token `id`.
/// Returns the zero address instead of reverting if the token does not exist.
function _ownerOf(uint256 id) internal view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
result := shr(96, shl(96, sload(add(id, add(id, keccak256(0x00, 0x20))))))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL DATA HITCHHIKING FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// For performance, no events are emitted for the hitchhiking setters.
// Please emit your own events if required.
/// @dev Returns the auxiliary data for `owner`.
/// Minting, transferring, burning the tokens of `owner` will not change the auxiliary data.
/// Auxiliary data can be set for any address, even if it does not have any tokens.
function _getAux(address owner) internal view virtual returns (uint224 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
mstore(0x00, owner)
result := shr(32, sload(keccak256(0x0c, 0x1c)))
}
}
/// @dev Set the auxiliary data for `owner` to `value`.
/// Minting, transferring, burning the tokens of `owner` will not change the auxiliary data.
/// Auxiliary data can be set for any address, even if it does not have any tokens.
function _setAux(address owner, uint224 value) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
mstore(0x00, owner)
let balanceSlot := keccak256(0x0c, 0x1c)
let packed := sload(balanceSlot)
sstore(balanceSlot, xor(packed, shl(32, xor(value, shr(32, packed)))))
}
}
/// @dev Returns the extra data for token `id`.
/// Minting, transferring, burning a token will not change the extra data.
/// The extra data can be set on a non-existent token.
function _getExtraData(uint256 id) internal view virtual returns (uint96 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
result := shr(160, sload(add(id, add(id, keccak256(0x00, 0x20)))))
}
}
/// @dev Sets the extra data for token `id` to `value`.
/// Minting, transferring, burning a token will not change the extra data.
/// The extra data can be set on a non-existent token.
function _setExtraData(uint256 id, uint96 value) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let packed := sload(ownershipSlot)
sstore(ownershipSlot, xor(packed, shl(160, xor(value, shr(160, packed)))))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL MINT FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Mints token `id` to `to`.
///
/// Requirements:
///
/// - Token `id` must not exist.
/// - `to` cannot be the zero address.
///
/// Emits a {Transfer} event.
function _mint(address to, uint256 id) internal virtual {
_beforeTokenTransfer(address(0), to, id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
to := shr(96, shl(96, to))
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let ownershipPacked := sload(ownershipSlot)
// Revert if the token already exists.
if shl(96, ownershipPacked) {
mstore(0x00, 0xc991cbb1) // `TokenAlreadyExists()`.
revert(0x1c, 0x04)
}
// Update with the owner.
sstore(ownershipSlot, or(ownershipPacked, to))
// Increment the balance of the owner.
{
mstore(0x00, to)
let balanceSlot := keccak256(0x0c, 0x1c)
let balanceSlotPacked := add(sload(balanceSlot), 1)
// Revert if `to` is the zero address, or if the account balance overflows.
if iszero(mul(to, and(balanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
// `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
mstore(shl(2, iszero(to)), 0xea553b3401336cea)
revert(0x1c, 0x04)
}
sstore(balanceSlot, balanceSlotPacked)
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, 0, to, id)
}
_afterTokenTransfer(address(0), to, id);
}
/// @dev Mints token `id` to `to`, and updates the extra data for token `id` to `value`.
/// Does NOT check if token `id` already exists (assumes `id` is auto-incrementing).
///
/// Requirements:
///
/// - `to` cannot be the zero address.
///
/// Emits a {Transfer} event.
function _mintAndSetExtraDataUnchecked(address to, uint256 id, uint96 value) internal virtual {
_beforeTokenTransfer(address(0), to, id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
to := shr(96, shl(96, to))
// Update with the owner and extra data.
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
sstore(add(id, add(id, keccak256(0x00, 0x20))), or(shl(160, value), to))
// Increment the balance of the owner.
{
mstore(0x00, to)
let balanceSlot := keccak256(0x0c, 0x1c)
let balanceSlotPacked := add(sload(balanceSlot), 1)
// Revert if `to` is the zero address, or if the account balance overflows.
if iszero(mul(to, and(balanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
// `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
mstore(shl(2, iszero(to)), 0xea553b3401336cea)
revert(0x1c, 0x04)
}
sstore(balanceSlot, balanceSlotPacked)
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, 0, to, id)
}
_afterTokenTransfer(address(0), to, id);
}
/// @dev Equivalent to `_safeMint(to, id, "")`.
function _safeMint(address to, uint256 id) internal virtual {
_safeMint(to, id, "");
}
/// @dev Mints token `id` to `to`.
///
/// Requirements:
///
/// - Token `id` must not exist.
/// - `to` cannot be the zero address.
/// - If `to` refers to a smart contract, it must implement
/// {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
///
/// Emits a {Transfer} event.
function _safeMint(address to, uint256 id, bytes memory data) internal virtual {
_mint(to, id);
if (_hasCode(to)) _checkOnERC721Received(address(0), to, id, data);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL BURN FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `_burn(address(0), id)`.
function _burn(uint256 id) internal virtual {
_burn(address(0), id);
}
/// @dev Destroys token `id`, using `by`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - If `by` is not the zero address,
/// it must be the owner of the token, or be approved to manage the token.
///
/// Emits a {Transfer} event.
function _burn(address by, uint256 id) internal virtual {
address owner = ownerOf(id);
_beforeTokenTransfer(owner, address(0), id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
by := shr(96, shl(96, by))
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, by))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let ownershipPacked := sload(ownershipSlot)
// Reload the owner in case it is changed in `_beforeTokenTransfer`.
owner := shr(96, shl(96, ownershipPacked))
// Revert if the token does not exist.
if iszero(owner) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
// Load and check the token approval.
{
mstore(0x00, owner)
let approvedAddress := sload(add(1, ownershipSlot))
// If `by` is not the zero address, do the authorization check.
// Revert if the `by` is not the owner, nor approved.
if iszero(or(iszero(by), or(eq(by, owner), eq(by, approvedAddress)))) {
if iszero(sload(keccak256(0x0c, 0x30))) {
mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
revert(0x1c, 0x04)
}
}
// Delete the approved address if any.
if approvedAddress { sstore(add(1, ownershipSlot), 0) }
}
// Clear the owner.
sstore(ownershipSlot, xor(ownershipPacked, owner))
// Decrement the balance of `owner`.
{
let balanceSlot := keccak256(0x0c, 0x1c)
sstore(balanceSlot, sub(sload(balanceSlot), 1))
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, owner, 0, id)
}
_afterTokenTransfer(owner, address(0), id);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL APPROVAL FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns whether `account` is the owner of token `id`, or is approved to manage it.
///
/// Requirements:
/// - Token `id` must exist.
function _isApprovedOrOwner(address account, uint256 id)
internal
view
virtual
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
result := 1
// Clear the upper 96 bits.
account := shr(96, shl(96, account))
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, account))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let owner := shr(96, shl(96, sload(ownershipSlot)))
// Revert if the token does not exist.
if iszero(owner) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
// Check if `account` is the `owner`.
if iszero(eq(account, owner)) {
mstore(0x00, owner)
// Check if `account` is approved to manage the token.
if iszero(sload(keccak256(0x0c, 0x30))) {
result := eq(account, sload(add(1, ownershipSlot)))
}
}
}
}
/// @dev Returns the account approved to manage token `id`.
/// Returns the zero address instead of reverting if the token does not exist.
function _getApproved(uint256 id) internal view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
result := sload(add(1, add(id, add(id, keccak256(0x00, 0x20)))))
}
}
/// @dev Equivalent to `_approve(address(0), account, id)`.
function _approve(address account, uint256 id) internal virtual {
_approve(address(0), account, id);
}
/// @dev Sets `account` as the approved account to manage token `id`, using `by`.
///
/// Requirements:
/// - Token `id` must exist.
/// - If `by` is not the zero address, `by` must be the owner
/// or an approved operator for the token owner.
///
/// Emits a {Approval} event.
function _approve(address by, address account, uint256 id) internal virtual {
assembly {
// Clear the upper 96 bits.
let bitmaskAddress := shr(96, not(0))
account := and(bitmaskAddress, account)
by := and(bitmaskAddress, by)
// Load the owner of the token.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, by))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let owner := and(bitmaskAddress, sload(ownershipSlot))
// Revert if the token does not exist.
if iszero(owner) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
// If `by` is not the zero address, do the authorization check.
// Revert if `by` is not the owner, nor approved.
if iszero(or(iszero(by), eq(by, owner))) {
mstore(0x00, owner)
if iszero(sload(keccak256(0x0c, 0x30))) {
mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
revert(0x1c, 0x04)
}
}
// Sets `account` as the approved account to manage `id`.
sstore(add(1, ownershipSlot), account)
// Emit the {Approval} event.
log4(codesize(), 0x00, _APPROVAL_EVENT_SIGNATURE, owner, account, id)
}
}
/// @dev Approve or remove the `operator` as an operator for `by`,
/// without authorization checks.
///
/// Emits an {ApprovalForAll} event.
function _setApprovalForAll(address by, address operator, bool isApproved) internal virtual {
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
by := shr(96, shl(96, by))
operator := shr(96, shl(96, operator))
// Convert to 0 or 1.
isApproved := iszero(iszero(isApproved))
// Update the `isApproved` for (`by`, `operator`).
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, operator))
mstore(0x00, by)
sstore(keccak256(0x0c, 0x30), isApproved)
// Emit the {ApprovalForAll} event.
mstore(0x00, isApproved)
log3(0x00, 0x20, _APPROVAL_FOR_ALL_EVENT_SIGNATURE, by, operator)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL TRANSFER FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `_transfer(address(0), from, to, id)`.
function _transfer(address from, address to, uint256 id) internal virtual {
_transfer(address(0), from, to, id);
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - If `by` is not the zero address,
/// it must be the owner of the token, or be approved to manage the token.
///
/// Emits a {Transfer} event.
function _transfer(address by, address from, address to, uint256 id) internal virtual {
_beforeTokenTransfer(from, to, id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
let bitmaskAddress := shr(96, not(0))
from := and(bitmaskAddress, from)
to := and(bitmaskAddress, to)
by := and(bitmaskAddress, by)
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, by))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let ownershipPacked := sload(ownershipSlot)
let owner := and(bitmaskAddress, ownershipPacked)
// Revert if the token does not exist, or if `from` is not the owner.
if iszero(mul(owner, eq(owner, from))) {
// `TokenDoesNotExist()`, `TransferFromIncorrectOwner()`.
mstore(shl(2, iszero(owner)), 0xceea21b6a1148100)
revert(0x1c, 0x04)
}
// Load, check, and update the token approval.
{
mstore(0x00, from)
let approvedAddress := sload(add(1, ownershipSlot))
// If `by` is not the zero address, do the authorization check.
// Revert if the `by` is not the owner, nor approved.
if iszero(or(iszero(by), or(eq(by, from), eq(by, approvedAddress)))) {
if iszero(sload(keccak256(0x0c, 0x30))) {
mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
revert(0x1c, 0x04)
}
}
// Delete the approved address if any.
if approvedAddress { sstore(add(1, ownershipSlot), 0) }
}
// Update with the new owner.
sstore(ownershipSlot, xor(ownershipPacked, xor(from, to)))
// Decrement the balance of `from`.
{
let fromBalanceSlot := keccak256(0x0c, 0x1c)
sstore(fromBalanceSlot, sub(sload(fromBalanceSlot), 1))
}
// Increment the balance of `to`.
{
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x1c)
let toBalanceSlotPacked := add(sload(toBalanceSlot), 1)
// Revert if `to` is the zero address, or if the account balance overflows.
if iszero(mul(to, and(toBalanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
// `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
mstore(shl(2, iszero(to)), 0xea553b3401336cea)
revert(0x1c, 0x04)
}
sstore(toBalanceSlot, toBalanceSlotPacked)
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, from, to, id)
}
_afterTokenTransfer(from, to, id);
}
/// @dev Equivalent to `_safeTransfer(from, to, id, "")`.
function _safeTransfer(address from, address to, uint256 id) internal virtual {
_safeTransfer(from, to, id, "");
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - The caller must be the owner of the token, or be approved to manage the token.
/// - If `to` refers to a smart contract, it must implement
/// {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
///
/// Emits a {Transfer} event.
function _safeTransfer(address from, address to, uint256 id, bytes memory data)
internal
virtual
{
_transfer(address(0), from, to, id);
if (_hasCode(to)) _checkOnERC721Received(from, to, id, data);
}
/// @dev Equivalent to `_safeTransfer(by, from, to, id, "")`.
function _safeTransfer(address by, address from, address to, uint256 id) internal virtual {
_safeTransfer(by, from, to, id, "");
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - If `by` is not the zero address,
/// it must be the owner of the token, or be approved to manage the token.
/// - If `to` refers to a smart contract, it must implement
/// {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
///
/// Emits a {Transfer} event.
function _safeTransfer(address by, address from, address to, uint256 id, bytes memory data)
internal
virtual
{
_transfer(by, from, to, id);
if (_hasCode(to)) _checkOnERC721Received(from, to, id, data);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HOOKS FOR OVERRIDING */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Hook that is called before any token transfers, including minting and burning.
function _beforeTokenTransfer(address from, address to, uint256 id) internal virtual {}
/// @dev Hook that is called after any token transfers, including minting and burning.
function _afterTokenTransfer(address from, address to, uint256 id) internal virtual {}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns if `a` has bytecode of non-zero length.
function _hasCode(address a) private view returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := extcodesize(a) // Can handle dirty upper bits.
}
}
/// @dev Perform a call to invoke {IERC721Receiver-onERC721Received} on `to`.
/// Reverts if the target does not support the function correctly.
function _checkOnERC721Received(address from, address to, uint256 id, bytes memory data)
private
{
/// @solidity memory-safe-assembly
assembly {
// Prepare the calldata.
let m := mload(0x40)
let onERC721ReceivedSelector := 0x150b7a02
mstore(m, onERC721ReceivedSelector)
mstore(add(m, 0x20), caller()) // The `operator`, which is always `msg.sender`.
mstore(add(m, 0x40), shr(96, shl(96, from)))
mstore(add(m, 0x60), id)
mstore(add(m, 0x80), 0x80)
let n := mload(data)
mstore(add(m, 0xa0), n)
if n { pop(staticcall(gas(), 4, add(data, 0x20), n, add(m, 0xc0), n)) }
// Revert if the call reverts.
if iszero(call(gas(), to, 0, add(m, 0x1c), add(n, 0xa4), m, 0x20)) {
if returndatasize() {
// Bubble up the revert if the call reverts.
returndatacopy(m, 0x00, returndatasize())
revert(m, returndatasize())
}
}
// Load the returndata and compare it.
if iszero(eq(mload(m), shl(224, onERC721ReceivedSelector))) {
mstore(0x00, 0xd1a57ed6) // `TransferToNonERC721ReceiverImplementer()`.
revert(0x1c, 0x04)
}
}
}
}
lib/solmate/src/auth/Owned.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Simple single owner authorization mixin.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol)
abstract contract Owned {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OwnershipTransferred(address indexed user, address indexed newOwner);
/*//////////////////////////////////////////////////////////////
OWNERSHIP STORAGE
//////////////////////////////////////////////////////////////*/
address public owner;
modifier onlyOwner() virtual {
require(msg.sender == owner, "UNAUTHORIZED");
_;
}
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(address _owner) {
owner = _owner;
emit OwnershipTransferred(address(0), _owner);
}
/*//////////////////////////////////////////////////////////////
OWNERSHIP LOGIC
//////////////////////////////////////////////////////////////*/
function transferOwnership(address newOwner) public virtual onlyOwner {
owner = newOwner;
emit OwnershipTransferred(msg.sender, newOwner);
}
}
src/BabyJubjub.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
/// @title BabyJubjub
/// @notice Validates points on the Baby Jubjub twisted Edwards curve
/// @dev Cosmetic on-chain guard. Real security comes from the ZK proof verifier.
library BabyJubjub {
/// @dev BN254 scalar field prime
uint256 constant FIELD_PRIME =
21888242871839275222246405745257275088548364400416034343698204186575808495617;
/// @dev Curve parameter a for the twisted Edwards equation: a*x² + y² = 1 + d*x²*y²
uint256 constant A = 168700;
/// @dev Curve parameter d
uint256 constant D = 168696;
/// @notice Returns true if (x, y) is a valid, non-identity point on Baby Jubjub
/// @dev Checks:
/// 1. x and y are in the BN254 scalar field (< FIELD_PRIME)
/// 2. (x, y) satisfies a*x² + y² ≡ 1 + d*x²*y² (mod FIELD_PRIME)
/// 3. (x, y) is not the neutral element (0, 1)
/// @param x X-coordinate
/// @param y Y-coordinate
function isValidPublicKey(uint256 x, uint256 y) internal pure returns (bool) {
// Field range check
if (x >= FIELD_PRIME || y >= FIELD_PRIME) return false;
// Reject the neutral element (identity point)
if (x == 0 && y == 1) return false;
// Curve equation: a*x² + y² ≡ 1 + d*x²*y² (mod p)
uint256 x2 = mulmod(x, x, FIELD_PRIME);
uint256 y2 = mulmod(y, y, FIELD_PRIME);
uint256 lhs = addmod(mulmod(A, x2, FIELD_PRIME), y2, FIELD_PRIME);
uint256 rhs = addmod(1, mulmod(D, mulmod(x2, y2, FIELD_PRIME), FIELD_PRIME), FIELD_PRIME);
return lhs == rhs;
}
}
src/EncryptedERC721.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import {Groth16Verifier as EcdhPoseidonVerifier} from "./groth16_verifier_ecdh_poseidon_transfer_key_derivation.sol";
import {Groth16Verifier as AddDataVerifier} from "./groth16_verifier_addDataWithCheck.sol";
import {ERC721} from "../lib/solady/src/tokens/ERC721.sol";
import {Owned} from "../lib/solmate/src/auth/Owned.sol";
import {BabyJubjub} from "./BabyJubjub.sol";
///*****************************************
///* *
///* *
///* *
///* THE OBJECT OF KNOWLEDGE *
///* BY REVELATION *
///* IS NOTHING THAN OBEDIENCE *
///* *
///* *
///* *
///*****************************************
/// CIPHER v.01
/// @notice Interface for metadata rendering contract
/// @dev Used to generate on-chain metadata for Cipher NFTs
interface IMetaData {
/// @notice Returns collection-level metadata
function collectionMetadata(
uint editionSize
) external view returns (string memory);
/// @notice Returns token-level metadata with encrypted fields
function renderGlowieMetadata(
uint256 n,
uint256 field1,
uint256 field2,
uint256 field3,
uint256 field4
) external view returns (string memory);
}
/// @notice ERC721 NFT with zero-knowledge encrypted on-chain data
/// @dev Implements encrypted transfers using ZK proofs and ECDH key exchange
/// @author plsdlr
contract EncryptedERC721 is ERC721, Owned {
/// @notice Emitted when a verified transfer with re-encryption occurs
/// @dev Contains public keys of sender and recipient
/// @param from Sender's public key as [x, y] coordinates
/// @param to Recipient's public key as [x, y] coordinates
/// @param id Token ID being transferred
event VerifiedTransfer(
uint256[2] indexed from,
uint256[2] indexed to,
uint256 indexed id
);
/// @notice Emitted when metadata contract address is updated
event MetadataUpdated(
address indexed oldMetadata,
address indexed newMetadata
);
/// @notice Emitted when artist address is updated
event ArtistAddressUpdated(
address indexed oldArtist,
address indexed newArtist
);
/// @notice Emitted when verifier contracts are updated
event VerifiersUpdated(
address indexed ecdhVerifier,
address indexed addDataVerifier,
uint256 newVersion
);
/// @dev ZK verifier for ECDH-based encrypted transfers
EcdhPoseidonVerifier private ecdhVerifier;
/// @dev ZK verifier for adding/updating encrypted data
AddDataVerifier private addDataVerifier;
/// @notice Maps user addresses to their public encryption keys
/// @dev Keys are stored as [x, y] coordinates on the Baby Jubjub curve
mapping(address => uint256[2]) public userPublicKeys;
/// @notice Maps token IDs to their encrypted data
mapping(uint => note) public tokenIdToNote;
/// @notice Maps token IDs to the previous owner's address
/// @dev Used to track transfer history
mapping(uint => address) public mapLastOwner;
/// @notice Number of plaintext field elements per token (Baby Jubjub scalar field values)
/// @dev C = ceil(N/3)*3 + 1 = 4 ciphertext fields are stored per token
uint256 public constant N = 3;
/// @notice Mint price in wei (0.1 ETH)
uint256 public constant price = 0.1 ether;
/// @notice Number of nfts
uint256 public constant maxNumber = 150;
/// @notice Artist wallet address receiving mint proceeds
address public artist;
/// @notice Address of the metadata rendering contract
address public metadata;
/// @notice Counter for minted tokens
uint256 public tokenIds;
/// @notice Version counter for verifier updates
uint256 public verifierVersion;
/// @notice Trusted minter contract — handles pricing and allowlist
address public minter;
/// @notice Structure holding encrypted data for each token
/// @dev Four fields of encrypted data stored as uint256 values
struct note {
/// @dev First encrypted field
uint256 field1;
/// @dev Second encrypted field
uint256 field2;
/// @dev Third encrypted field
uint256 field3;
/// @dev Fourth encrypted field
uint256 field4;
}
/// @notice Initializes the contract with verifier and metadata addresses
/// @param _ecdhVerifierAddress Address of the ECDH transfer proof verifier
/// @param _addDataVerifierAddress Address of the add/update data proof verifier
/// @param _metadataAddress Address of the metadata rendering contract
constructor(
address _ecdhVerifierAddress,
address _addDataVerifierAddress,
address _metadataAddress
) Owned(msg.sender) {
ecdhVerifier = EcdhPoseidonVerifier(_ecdhVerifierAddress);
addDataVerifier = AddDataVerifier(_addDataVerifierAddress);
metadata = _metadataAddress;
artist = 0x98B1d98a708F75A1a963BBeDFb96E69008679A7F;
verifierVersion = 1;
}
// ============================================================
// ERC721 OVERRIDES
// ============================================================
/// @notice Returns the token collection name
/// @return Collection name "CIPHER"
function name() public view virtual override returns (string memory) {
return "CIPHER";
}
/// @notice Returns the token collection symbol
/// @return Collection symbol "CIP"
function symbol() public view virtual override returns (string memory) {
return "CIP";
}
/// @notice Returns the metadata URI for a token
/// @dev Calls the metadata contract to generate dynamic metadata including encrypted fields
/// @param id Token ID
/// @return Base64 encoded data URI containing token metadata
function tokenURI(
uint256 id
) public view virtual override returns (string memory) {
return
IMetaData(metadata).renderGlowieMetadata(
id,
tokenIdToNote[id].field1,
tokenIdToNote[id].field2,
tokenIdToNote[id].field3,
tokenIdToNote[id].field4
);
}
// ============================================================
// TIMESTAMP & FLAG STORAGE
// ============================================================
/// @notice Packs timestamp and encryption flag into token's extra data
/// @dev Uses ERC721's extraData (96 bits): 95 bits for timestamp, 1 bit for flag
/// @dev flag == true: Encrypted with owner's own keypair
/// @dev flag == false: Encrypted via ECDH with previous sender
/// @param tokenId Token ID to update
/// @param timestamp Unix timestamp of encryption
/// @param flag Encryption method indicator
function setTimestampAndFlag(
uint256 tokenId,
uint256 timestamp,
bool flag
) internal {
// Ensure timestamp fits within 95 bits
require(timestamp < (1 << 95), "Timestamp too large");
uint96 packedValue = uint96(timestamp);
// Set the highest bit if flag is true
if (flag) {
packedValue |= uint96(1 << 95);
}
_setExtraData(tokenId, packedValue);
}
// ============================================================
// PUBLIC KEY MANAGEMENT
// ============================================================
/// @notice Registers a user's public encryption key
/// @dev Public key must be a valid point on the Baby Jubjub curve
/// @param x X-coordinate of the public key
/// @param y Y-coordinate of the public key
function registerPublicKey(uint256 x, uint256 y) public {
require(BabyJubjub.isValidPublicKey(x, y), "Invalid Baby Jubjub point");
userPublicKeys[msg.sender] = [x, y];
}
// ============================================================
// OWNER FUNCTIONS
// ============================================================
/// @notice Updates the metadata contract address
/// @dev Only callable by contract owner
/// @param _newMetadata Address of the new metadata contract
function setMetadata(address _newMetadata) external onlyOwner {
require(_newMetadata != address(0), "Invalid metadata address");
address oldMetadata = metadata;
metadata = _newMetadata;
emit MetadataUpdated(oldMetadata, _newMetadata);
}
/// @notice Updates the artist wallet address
/// @dev Only callable by contract owner
/// @param _newArtist Address of the new artist wallet
function updateArtistAddress(address _newArtist) external onlyOwner {
require(_newArtist != address(0), "Invalid artist address");
address oldArtist = artist;
artist = _newArtist;
emit ArtistAddressUpdated(oldArtist, _newArtist);
}
/// @notice Sets the trusted minter contract address
/// @dev Only callable by owner. Minter can call mintFrom without payment checks.
/// @param _minter Address of the CipherMinter contract
function setMinter(address _minter) external onlyOwner {
require(_minter != address(0), "Invalid minter address");
minter = _minter;
}
/// @notice Updates the ZK proof verifier contracts
/// @dev Only callable by contract owner, increments verifierVersion
/// @param _ecdhVerifier Address of the new ECDH verifier contract
/// @param _addDataVerifier Address of the new add/update data verifier contract
function updateVerifiers(
address _ecdhVerifier,
address _addDataVerifier
) external onlyOwner {
require(_ecdhVerifier != address(0), "Invalid ECDH verifier address");
require(
_addDataVerifier != address(0),
"Invalid add data verifier address"
);
ecdhVerifier = EcdhPoseidonVerifier(_ecdhVerifier);
addDataVerifier = AddDataVerifier(_addDataVerifier);
verifierVersion++;
emit VerifiersUpdated(_ecdhVerifier, _addDataVerifier, verifierVersion);
}
// ============================================================
// MINTING & RE-ENCRYPTION
// ============================================================
/// @notice Mints a new NFT — callable only by the trusted minter contract
/// @dev Minter handles all payment and allowlist logic. No ETH accepted here.
/// @param _pA ZK proof parameter A
/// @param _pB ZK proof parameter B
/// @param _pC ZK proof parameter C
/// @param _pubSignals Public signals (same layout as mint)
/// @param to Address to receive the minted token
function mintFrom(
uint[2] calldata _pA,
uint[2][2] calldata _pB,
uint[2] calldata _pC,
uint[14] calldata _pubSignals,
address to
) external {
require(msg.sender == minter, "Only minter");
require(_pubSignals[13] == 0, "Invalid mode: must be mint mode");
tokenIds = tokenIds + 1;
require(tokenIds <= maxNumber, "Mint over");
bool works = addDataVerifier.verifyProof(_pA, _pB, _pC, _pubSignals);
require(works, "Invalid Proof");
setNote(
_pubSignals[3],
_pubSignals[4],
_pubSignals[5],
_pubSignals[6],
tokenIds
);
_mint(to, tokenIds);
setTimestampAndFlag(tokenIds, _pubSignals[2], true);
}
/// @notice Mints a new NFT with encrypted data
/// @dev Requires payment of mint price and valid ZK proof of encryption
/// @param _pA ZK proof parameter A
/// @param _pB ZK proof parameter B
/// @param _pC ZK proof parameter C
/// @param _pubSignals Public signals:
/// @param to Address to receive the minted token
function mint(
uint[2] calldata _pA,
uint[2][2] calldata _pB,
uint[2] calldata _pC,
uint[14] calldata _pubSignals,
address to
) external payable {
require(msg.value == price, "Value doesn't match price");
// first mode, multiple changes allowed since this is mint
require(_pubSignals[13] == 0, "Invalid mode: must be mint mode");
// we dont check for previos dataslots because this is the first time writing into the slots
// the user just sends the same data twice
tokenIds = tokenIds + 1;
require(tokenIds <= maxNumber, "Mint over");
(bool sent, ) = artist.call{value: msg.value}("");
require(sent, "Failed to send Ether");
// Verify the ZK proof for encrypted data
bool works = addDataVerifier.verifyProof(_pA, _pB, _pC, _pubSignals);
require(works == true, "Invalid Proof");
// Store the encrypted data on-chain
setNote(
_pubSignals[3],
_pubSignals[4],
_pubSignals[5],
_pubSignals[6],
tokenIds
);
_mint(to, tokenIds);
setTimestampAndFlag(tokenIds, _pubSignals[2], true); // newNonce (used as timestamp)
}
/// @notice Re-encrypts the data of an owned token with a new cipher
/// @dev Only callable by token owner, updates encrypted fields with new values
/// @param _pA ZK proof parameter A
/// @param _pB ZK proof parameter B
/// @param _pC ZK proof parameter C
/// @param _pubSignals Public signals:
/// @param id Token ID to re-encrypt
function reCipher(
uint[2] calldata _pA,
uint[2][2] calldata _pB,
uint[2] calldata _pC,
uint[14] calldata _pubSignals,
uint256 id
) external {
require(
msg.sender == ERC721.ownerOf(id),
"MSG SENDER NEEDS TO BE OWNER"
);
// second mode, only one changes allowed
require(_pubSignals[13] == 1, "NEEDS TO BE RECIPHER MODE");
require(getFlag(id) == false, "CAN ONLY RECIPHER ONCE AFTER TRANSFER");
require(
tokenIdToNote[id].field1 == _pubSignals[7],
"OLD ENCRYPTED DATA DOESN'T MATCH"
);
require(
tokenIdToNote[id].field2 == _pubSignals[8],
"OLD ENCRYPTED DATA DOESN'T MATCH"
);
require(
tokenIdToNote[id].field3 == _pubSignals[9],
"OLD ENCRYPTED DATA DOESN'T MATCH"
);
require(
tokenIdToNote[id].field4 == _pubSignals[10],
"OLD ENCRYPTED DATA DOESN'T MATCH"
);
// Verify the ZK proof for new encrypted data
bool works = addDataVerifier.verifyProof(_pA, _pB, _pC, _pubSignals);
require(works == true, "Invalid Proof");
setNote(
_pubSignals[3],
_pubSignals[4],
_pubSignals[5],
_pubSignals[6],
id
);
setTimestampAndFlag(id, _pubSignals[2], true); // newNonce (used as timestamp)
}
// ============================================================
// VERIFIED TRANSFERS
// ============================================================
/// @notice Disabled - prevents direct transfers without re-encryption
/// @dev Always reverts, forcing use of verifiedTransferFrom
function transferFrom(
address from,
address to,
uint256 id
) public payable virtual override {
revert("Use verifiedTransferFrom instead");
}
/// @notice Disabled - prevents safe transfers without re-encryption
/// @dev Always reverts, forcing use of verifiedTransferFrom
function safeTransferFrom(
address from,
address to,
uint256 id
) public payable virtual override {
revert("Use verifiedTransferFrom instead");
}
/// @notice Disabled - prevents safe transfers without re-encryption
/// @dev Always reverts, forcing use of verifiedTransferFrom
function safeTransferFrom(
address from,
address to,
uint256 id,
bytes calldata data
) public payable virtual override {
revert("Use verifiedTransferFrom instead");
}
/// @notice Transfers token with ZK-verified re-encryption to recipient
/// @dev Verifies proof, re-encrypts data for recipient, then transfers
/// @param from Current owner address
/// @param to Recipient address
/// @param id Token ID to transfer
/// @param _pA ZK proof parameter A
/// @param _pB ZK proof parameter B
/// @param _pC ZK proof parameter C
/// @param _pubSignals Public signals: [recipientPubKeyX, recipientPubKeyY, timestamp, newField1-4, oldField1-4, senderPubKeyX, senderPubKeyY]
function verifiedTransferFrom(
address from,
address to,
uint256 id,
uint[2] calldata _pA,
uint[2][2] calldata _pB,
uint[2] calldata _pC,
uint[13] calldata _pubSignals
) public virtual {
verifyEncryption(_pA, _pB, _pC, _pubSignals, id, to);
ERC721.transferFrom(from, to, id);
mapLastOwner[id] = from;
emit VerifiedTransfer(
[_pubSignals[11], _pubSignals[12]],
[_pubSignals[0], _pubSignals[1]],
id
);
}
/// @notice Verifies the encryption proof for a transfer
/// @dev Validates old encrypted data matches, recipient keys match, and ZK proof is valid
/// @param _pA ZK proof parameter A
/// @param _pB ZK proof parameter B
/// @param _pC ZK proof parameter C
/// @param _pubSignals Public signals array containing keys and encrypted data
/// @param tokenId Token ID being transferred
/// @param recifer Recipient address
function verifyEncryption(
uint[2] calldata _pA,
uint[2][2] calldata _pB,
uint[2] calldata _pC,
uint[13] calldata _pubSignals,
uint tokenId,
address recifer
) internal {
// Verify old encrypted data matches current token data
require(
tokenIdToNote[tokenId].field1 == _pubSignals[7],
"OLD ENCRYPTED DATA DOESN'T MATCH"
);
require(
tokenIdToNote[tokenId].field2 == _pubSignals[8],
"OLD ENCRYPTED DATA DOESN'T MATCH"
);
require(
tokenIdToNote[tokenId].field3 == _pubSignals[9],
"OLD ENCRYPTED DATA DOESN'T MATCH"
);
require(
tokenIdToNote[tokenId].field4 == _pubSignals[10],
"OLD ENCRYPTED DATA DOESN'T MATCH"
);
// Verify recipient's public key matches
require(
userPublicKeys[recifer][0] == _pubSignals[0],
"RECIVER KEYS DONT MATCH"
);
require(
userPublicKeys[recifer][1] == _pubSignals[1],
"RECIVER KEYS DONT MATCH"
);
// Verify the ZK proof for ECDH re-encryption
bool validProof = ecdhVerifier.verifyProof(_pA, _pB, _pC, _pubSignals);
require(validProof == true, "Invalid Proof");
// Store newly encrypted data for recipient
setNote(
_pubSignals[3],
_pubSignals[4],
_pubSignals[5],
_pubSignals[6],
tokenId
);
// Set flag to false (ECDH encryption)
setTimestampAndFlag(tokenId, _pubSignals[2], false);
}
// ============================================================
// VIEW FUNCTIONS
// ============================================================
/// @notice Returns the number of plaintext field elements this contract was deployed with
/// @dev C = ceil(N/3)*3 + 1 = 4 ciphertext fields are stored per token
function plaintextLength() external pure returns (uint256) {
return N;
}
/// @notice Returns the number of ciphertext uint256 fields stored per token
/// @dev C = ceil(N/3)*3 + 1; Poseidon encrypts in blocks of 3, plus one authentication tag
function ciphertextLength() external pure returns (uint256) {
return ((N + 2) / 3) * 3 + 1;
}
/// @notice Gets the encryption timestamp for a token
/// @param tokenId Token ID to query
/// @return Timestamp when the token was last encrypted
function getTimestamp(uint256 tokenId) external view returns (uint256) {
require(_exists(tokenId), "Token does not exist");
uint96 packedValue = _getExtraData(tokenId);
return uint256(packedValue & ~uint96(1 << 95));
}
/// @notice Gets the encryption method flag for a token
/// @dev True if encrypted with owner's keypair, false if encrypted via ECDH
/// @param tokenId Token ID to query
/// @return Encryption method flag
function getFlag(uint256 tokenId) public view returns (bool) {
require(_exists(tokenId), "Token does not exist");
uint96 packedValue = _getExtraData(tokenId);
return (packedValue & uint96(1 << 95)) != 0;
}
/// @notice Gets both timestamp and flag for a token
/// @param tokenId Token ID to query
/// @return timestamp Encryption timestamp
/// @return flag Encryption method indicator
function getTimestampAndFlag(
uint256 tokenId
) public view returns (uint256 timestamp, bool flag) {
require(_exists(tokenId), "Token does not exist");
uint96 packedValue = _getExtraData(tokenId);
timestamp = uint256(packedValue & ~uint96(1 << 95));
flag = (packedValue & uint96(1 << 95)) != 0;
}
/// @notice Gets all encrypted data and metadata for a token
/// @param tokenId Token ID to query
/// @return ciphertext Array of C=4 ciphertext uint256 values
/// @return timestamp Encryption timestamp
/// @return flag Encryption method flag (true = self-encrypted, false = ECDH)
function getEncryptedNote(
uint256 tokenId
)
external
view
returns (uint256[] memory ciphertext, uint256 timestamp, bool flag)
{
(uint256 _timestamp, bool _flag) = getTimestampAndFlag(tokenId);
uint256[] memory ct = new uint256[](4);
ct[0] = tokenIdToNote[tokenId].field1;
ct[1] = tokenIdToNote[tokenId].field2;
ct[2] = tokenIdToNote[tokenId].field3;
ct[3] = tokenIdToNote[tokenId].field4;
return (ct, _timestamp, _flag);
}
/// @notice Returns all token IDs owned by an address in a given range
/// @dev More gas efficient than standard enumerable extension
/// @param start Starting token ID (inclusive)
/// @param end Ending token ID (exclusive)
/// @param owner Address to query tokens for
/// @return Array of token IDs owned by the address
function returnTokenIdsOfOwner(
uint256 start,
uint256 end,
address owner
) external view returns (uint[] memory) {
require(start < end, "END > START");
uint[] memory idsOwnedByAddress = new uint256[](end - start);
uint256 counter = 0;
for (start; start < end; start = start + 1) {
if (_exists(start)) {
if (ownerOf(start) == owner) {
idsOwnedByAddress[counter] = start;
counter = counter + 1;
}
}
}
// Resize the array to actual length
assembly {
mstore(idsOwnedByAddress, counter)
}
return idsOwnedByAddress;
}
// ============================================================
// INTERNAL FUNCTIONS
// ============================================================
/// @notice Stores encrypted data for a token
/// @dev Internal function to update the note mapping
/// @param a First encrypted field
/// @param b Second encrypted field
/// @param c Third encrypted field
/// @param d Fourth encrypted field
/// @param tokenId Token ID to update
function setNote(
uint256 a,
uint256 b,
uint256 c,
uint256 d,
uint tokenId
) internal {
tokenIdToNote[tokenId] = note(a, b, c, d);
}
}
src/groth16_verifier_addDataWithCheck.sol
// SPDX-License-Identifier: GPL-3.0
/*
Copyright 2021 0KIMS association.
This file is generated with [snarkJS](https://github.com/iden3/snarkjs).
snarkJS is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
snarkJS is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with snarkJS. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.7.0 <0.9.0;
contract Groth16Verifier {
// Scalar field size
uint256 constant r = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
// Base field size
uint256 constant q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
// Verification Key data
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 = 934177438833205945042152983019319630322133414557010275116010860604954510046;
uint256 constant deltax2 = 17013748465190579156865408369762109526474755135421520010502256380701772329463;
uint256 constant deltay1 = 14263875054205035764369938913465980363867502966548849703158144882707499394480;
uint256 constant deltay2 = 1013163168152918627576884168334313219144913947924133612817988144063704217365;
uint256 constant IC0x = 18772028871091516385711958118987912119322945991356059714556223285604315867031;
uint256 constant IC0y = 17020317280520086913721586940467686243503106110941153638421616901968679742864;
uint256 constant IC1x = 2746335779019208998405719838220656881690832954781557369654184191044765952943;
uint256 constant IC1y = 14738820409337514810131605210763534952191398424672239703195210490890075453992;
uint256 constant IC2x = 815859376011708452772902682819477452442049485583079344778952671182844641895;
uint256 constant IC2y = 9143987871961568282556671929347410892793436988097558474673173954102830147289;
uint256 constant IC3x = 1392439644756168815299426446816487848735091670825473534754110679250411614097;
uint256 constant IC3y = 15492683872989533179844216123357673121968309153256069267574011541835188541414;
uint256 constant IC4x = 4867071779564394849278202003313615253235086292833533979060468484091349330192;
uint256 constant IC4y = 11134598273648224397982942492397383284921446226950281067359649423468085881674;
uint256 constant IC5x = 5933637366293975627746126647009423078874792040841158881168465040838418587731;
uint256 constant IC5y = 1166524075565102795757762120968188581984327889927101720532692905038944686062;
uint256 constant IC6x = 10468760156368133716209139580885364337842281777710826416327213330456060691625;
uint256 constant IC6y = 4732911224515303639399509965754680407580981919802218338626206043421610037319;
uint256 constant IC7x = 3460643810087764902650842142190333517810512698918470506868139295268018801341;
uint256 constant IC7y = 6940692599290910001452335559416518946482020945611145502623829322777758389278;
uint256 constant IC8x = 3398267608128250862777696224962999981541670638151961244790470186465900615099;
uint256 constant IC8y = 20060443902229803633161236302507757759758785151314384222628804757148682432117;
uint256 constant IC9x = 21099008257005068551950730888209598937161486495443334971372028805682101132335;
uint256 constant IC9y = 1317505919726424792748658762697155568866479862567740519157902871070407989154;
uint256 constant IC10x = 18914702956069348776627329678224743480954012628352335595547185692001183111891;
uint256 constant IC10y = 16606721049507253944308608620015289748822858520552522106673232917070040444522;
uint256 constant IC11x = 9457912436306238752831881924332816865965416189729844883358481657185425815395;
uint256 constant IC11y = 11568225498180742307126018262663486502599472349345706874922608745136665860119;
uint256 constant IC12x = 6716682795843533223055599466417859796963541626454517222699754653564512449757;
uint256 constant IC12y = 1261625834284977111211496884343118461721119116864783743262847921928490379100;
uint256 constant IC13x = 15285768539751802900187067713349783157955637051932786636203484115187488482965;
uint256 constant IC13y = 15635180044057432461153092006431910555181523043364087549546672170387215922673;
uint256 constant IC14x = 17231670379060678024971428146077624909937740400723674295509261729342767976721;
uint256 constant IC14y = 8589169722201247591308257769402361838704986955304492112251063445547681588061;
// Memory data
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[14] calldata _pubSignals) public view returns (bool) {
assembly {
function checkField(v) {
if iszero(lt(v, r)) {
mstore(0, 0)
return(0, 0x20)
}
}
// G1 function to multiply a G1 value(x,y) to value in an address
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)
// Compute the linear combination vk_x
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)))
g1_mulAccC(_pVk, IC7x, IC7y, calldataload(add(pubSignals, 192)))
g1_mulAccC(_pVk, IC8x, IC8y, calldataload(add(pubSignals, 224)))
g1_mulAccC(_pVk, IC9x, IC9y, calldataload(add(pubSignals, 256)))
g1_mulAccC(_pVk, IC10x, IC10y, calldataload(add(pubSignals, 288)))
g1_mulAccC(_pVk, IC11x, IC11y, calldataload(add(pubSignals, 320)))
g1_mulAccC(_pVk, IC12x, IC12y, calldataload(add(pubSignals, 352)))
g1_mulAccC(_pVk, IC13x, IC13y, calldataload(add(pubSignals, 384)))
g1_mulAccC(_pVk, IC14x, IC14y, calldataload(add(pubSignals, 416)))
// -A
mstore(_pPairing, calldataload(pA))
mstore(add(_pPairing, 32), mod(sub(q, calldataload(add(pA, 32))), q))
// B
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)))
// alpha1
mstore(add(_pPairing, 192), alphax)
mstore(add(_pPairing, 224), alphay)
// beta2
mstore(add(_pPairing, 256), betax1)
mstore(add(_pPairing, 288), betax2)
mstore(add(_pPairing, 320), betay1)
mstore(add(_pPairing, 352), betay2)
// vk_x
mstore(add(_pPairing, 384), mload(add(pMem, pVk)))
mstore(add(_pPairing, 416), mload(add(pMem, add(pVk, 32))))
// gamma2
mstore(add(_pPairing, 448), gammax1)
mstore(add(_pPairing, 480), gammax2)
mstore(add(_pPairing, 512), gammay1)
mstore(add(_pPairing, 544), gammay2)
// C
mstore(add(_pPairing, 576), calldataload(pC))
mstore(add(_pPairing, 608), calldataload(add(pC, 32)))
// delta2
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))
// Validate that all evaluations ∈ F
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)))
checkField(calldataload(add(_pubSignals, 192)))
checkField(calldataload(add(_pubSignals, 224)))
checkField(calldataload(add(_pubSignals, 256)))
checkField(calldataload(add(_pubSignals, 288)))
checkField(calldataload(add(_pubSignals, 320)))
checkField(calldataload(add(_pubSignals, 352)))
checkField(calldataload(add(_pubSignals, 384)))
checkField(calldataload(add(_pubSignals, 416)))
// Validate all evaluations
let isValid := checkPairing(_pA, _pB, _pC, _pubSignals, pMem)
mstore(0, isValid)
return(0, 0x20)
}
}
}
src/groth16_verifier_ecdh_poseidon_transfer_key_derivation.sol
// SPDX-License-Identifier: GPL-3.0
/*
Copyright 2021 0KIMS association.
This file is generated with [snarkJS](https://github.com/iden3/snarkjs).
snarkJS is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
snarkJS is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with snarkJS. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.7.0 <0.9.0;
contract Groth16Verifier {
// Scalar field size
uint256 constant r = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
// Base field size
uint256 constant q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
// Verification Key data
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 = 8018129047436714651018025003413820698803498704384604782512646916528987578188;
uint256 constant deltax2 = 9182685111284411648958643002701538665084247186017236595680637325940777796725;
uint256 constant deltay1 = 5423290602099074429219005095446264191634238113864293449943539114862371759415;
uint256 constant deltay2 = 7330182126034832756160733083750214245461010741582374558523378174413925908514;
uint256 constant IC0x = 9647454772703240255761896388388104539841338755328065554951814852655957120926;
uint256 constant IC0y = 9150452246018204925933640006401687270145115043554695216817989862457946399557;
uint256 constant IC1x = 10700788009930761591191448267718331700278366169849476804971697085573834461815;
uint256 constant IC1y = 5828490547528162542928614475512265376553439562971031713063758627674335304416;
uint256 constant IC2x = 5843663754481507809803378226826600805920041712975788097755330571597898611097;
uint256 constant IC2y = 10644028830065634366728249416876057524703742910803830305231723412091375380468;
uint256 constant IC3x = 8499997249213116062293093444670986673642720970763801313715164103267614136955;
uint256 constant IC3y = 10147493975628893330778466741407269178330331712265929239236734365707399855601;
uint256 constant IC4x = 18126732614402545878777254827627132030524042236896287145023360056590667567673;
uint256 constant IC4y = 8555773823619258094981005760855993808398079571919070634002538261131632052301;
uint256 constant IC5x = 1503271103394602681628286402598040505450699943276621427596468806369841683055;
uint256 constant IC5y = 6512776034605753627127573401299174560361286953134429752117186860876565243796;
uint256 constant IC6x = 1670725364949163575432045279811765800529158823983507065420302012861783803073;
uint256 constant IC6y = 5290695491947506009821899831479351781618523715550495475601742931382607405368;
uint256 constant IC7x = 19410573191078564458772721496197828968494944357356515158924740542080539525536;
uint256 constant IC7y = 20907872160852059175791178305790667216443764171297093850152130393999473628816;
uint256 constant IC8x = 2186391611240059945502087137265336895311835802949055431868626539578602557610;
uint256 constant IC8y = 5929280283666999340642408255367969762656528509202266517180351570134086096305;
uint256 constant IC9x = 7252272138952502728688237366613041054154550055771148861417399260068781637671;
uint256 constant IC9y = 17965632548794762870253178739900739621734674392688464300147602934977324906212;
uint256 constant IC10x = 16663806811153355038244258903438343409185873974693501432118629550576870846518;
uint256 constant IC10y = 13267430220243402367353585289504723147301171153880338584478257019985617809939;
uint256 constant IC11x = 4551603563590669937320626059543994196842104282054560789320777554638347857504;
uint256 constant IC11y = 12143120559828987567298549625190895404789774721617890509186693517088509919654;
uint256 constant IC12x = 2247053548462554344133090763175314797775931053326814157227743163595372988794;
uint256 constant IC12y = 5842461983964219283017166703523491491243678630667393465737961999721831235211;
uint256 constant IC13x = 4082084327059826242496885455232812969211605468551864036493041948204084775842;
uint256 constant IC13y = 565753452381832418318491605625639048801171235762391766699241726401262515895;
// Memory data
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[13] calldata _pubSignals) public view returns (bool) {
assembly {
function checkField(v) {
if iszero(lt(v, r)) {
mstore(0, 0)
return(0, 0x20)
}
}
// G1 function to multiply a G1 value(x,y) to value in an address
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)
// Compute the linear combination vk_x
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)))
g1_mulAccC(_pVk, IC7x, IC7y, calldataload(add(pubSignals, 192)))
g1_mulAccC(_pVk, IC8x, IC8y, calldataload(add(pubSignals, 224)))
g1_mulAccC(_pVk, IC9x, IC9y, calldataload(add(pubSignals, 256)))
g1_mulAccC(_pVk, IC10x, IC10y, calldataload(add(pubSignals, 288)))
g1_mulAccC(_pVk, IC11x, IC11y, calldataload(add(pubSignals, 320)))
g1_mulAccC(_pVk, IC12x, IC12y, calldataload(add(pubSignals, 352)))
g1_mulAccC(_pVk, IC13x, IC13y, calldataload(add(pubSignals, 384)))
// -A
mstore(_pPairing, calldataload(pA))
mstore(add(_pPairing, 32), mod(sub(q, calldataload(add(pA, 32))), q))
// B
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)))
// alpha1
mstore(add(_pPairing, 192), alphax)
mstore(add(_pPairing, 224), alphay)
// beta2
mstore(add(_pPairing, 256), betax1)
mstore(add(_pPairing, 288), betax2)
mstore(add(_pPairing, 320), betay1)
mstore(add(_pPairing, 352), betay2)
// vk_x
mstore(add(_pPairing, 384), mload(add(pMem, pVk)))
mstore(add(_pPairing, 416), mload(add(pMem, add(pVk, 32))))
// gamma2
mstore(add(_pPairing, 448), gammax1)
mstore(add(_pPairing, 480), gammax2)
mstore(add(_pPairing, 512), gammay1)
mstore(add(_pPairing, 544), gammay2)
// C
mstore(add(_pPairing, 576), calldataload(pC))
mstore(add(_pPairing, 608), calldataload(add(pC, 32)))
// delta2
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))
// Validate that all evaluations ∈ F
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)))
checkField(calldataload(add(_pubSignals, 192)))
checkField(calldataload(add(_pubSignals, 224)))
checkField(calldataload(add(_pubSignals, 256)))
checkField(calldataload(add(_pubSignals, 288)))
checkField(calldataload(add(_pubSignals, 320)))
checkField(calldataload(add(_pubSignals, 352)))
checkField(calldataload(add(_pubSignals, 384)))
// Validate all evaluations
let isValid := checkPairing(_pA, _pB, _pC, _pubSignals, pMem)
mstore(0, isValid)
return(0, 0x20)
}
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": false
},
"evmVersion": "prague",
"remappings": [
"ds-test/=lib/solmate/lib/ds-test/src/",
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/src/",
"solmate/=lib/solmate/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.