Description:
Proxy contract enabling upgradeable smart contract patterns. Delegates calls to an implementation contract.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"src/DeploiNotes3475.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC3475} from "./interfaces/IERC3475.sol";
/* -------- Upgradeable base (OZ v5) -------- */
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
contract DeploiNotes3475 is
Initializable,
UUPSUpgradeable,
AccessControlUpgradeable,
PausableUpgradeable,
ReentrancyGuardUpgradeable,
IERC3475
{
string public constant NAME = "Deploi Private Credit Notes";
string public constant SYMBOL = "PCN";
function name() external pure returns (string memory) { return NAME; }
function symbol() external pure returns (string memory) { return SYMBOL; }
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
uint256 private constant MAX_BATCH = 64;
struct Nonce {
mapping(uint256 => string) _valuesId;
mapping(string => Values) _values;
mapping(address => uint256) _balances;
mapping(address => mapping(address => uint256)) _allowances;
uint256 _activeSupply;
uint256 _burnedSupply;
uint256 _redeemedSupply;
}
struct Class {
mapping(uint256 => string) _valuesId;
mapping(string => Values) _values;
mapping(uint256 => Nonce) _nonces;
mapping(uint256 => Metadata) _nonceMetadatas;
}
mapping(address => mapping(address => bool)) public _operatorApprovals;
mapping(uint256 => Class) internal _classes;
mapping(uint256 => Metadata) public _classMetadata;
mapping(address => bool) private _wl;
event WhitelistSet(address indexed account, bool ok);
event Approval(address indexed owner, address indexed spender, uint256 indexed classId, uint256 nonceId, uint256 amount);
event NonceScheduleSet(uint256 indexed classId, uint256 indexed nonceId, uint256 issuance, uint256 maturity);
event ClassMetadataSet(uint256 indexed metadataId, Metadata metadata);
event NonceMetadataSet(uint256 indexed classId, uint256 indexed metadataId, Metadata metadata);
event ClassValueSet(uint256 indexed classId, uint256 index, string key);
event NonceValueSet(uint256 indexed classId, uint256 indexed nonceId, uint256 index, string key);
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/**
* @notice Initializes the contract with the provided admin address
* @dev Can only be called once due to the initializer modifier. Sets up all base contracts
* and grants all three roles (DEFAULT_ADMIN_ROLE, UPGRADER_ROLE, OPERATOR_ROLE) to the admin.
* The admin is also automatically whitelisted.
* @param admin The address that will receive all admin privileges and be whitelisted
*/
function initialize(address admin) external initializer {
require(admin != address(0), "ZERO_ADDR");
__UUPSUpgradeable_init();
__AccessControl_init();
__Pausable_init();
__ReentrancyGuard_init();
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_grantRole(UPGRADER_ROLE, admin);
_grantRole(OPERATOR_ROLE, admin);
_wl[admin] = true;
}
/* ---------- Admin ---------- */
/**
* @notice Authorizes contract upgrades (required by UUPS pattern)
* @dev Only addresses with UPGRADER_ROLE can upgrade the contract implementation
*/
function _authorizeUpgrade(address) internal override onlyRole(UPGRADER_ROLE) {}
/**
* @notice Pauses all token operations (transfers, approvals, issue, redeem, burn)
* @dev Only callable by DEFAULT_ADMIN_ROLE. Use in emergency situations to halt all activity.
*/
function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); }
/**
* @notice Unpauses all token operations
* @dev Only callable by DEFAULT_ADMIN_ROLE. Restores normal contract functionality.
*/
function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); }
/**
* @notice Adds or removes an address from the whitelist
* @dev Only callable by DEFAULT_ADMIN_ROLE. All participants (investors and operators) must be
* whitelisted before they can hold, transfer, or receive bonds.
* @param a The address to whitelist or remove from whitelist
* @param ok True to whitelist, false to remove from whitelist
*/
function setWhitelist(address a, bool ok) external onlyRole(DEFAULT_ADMIN_ROLE) {
_wl[a] = ok;
emit WhitelistSet(a, ok);
}
/**
* @notice Sets metadata for a bond class (pool)
* @dev Only callable by DEFAULT_ADMIN_ROLE. Metadata includes title, type, and description.
* @param metadataId The metadata identifier for the class
* @param m The metadata struct containing title, type, and description
*/
function setClassMetadata(uint256 metadataId, Metadata calldata m) external onlyRole(DEFAULT_ADMIN_ROLE) {
_classMetadata[metadataId] = m;
emit ClassMetadataSet(metadataId, m);
}
/**
* @notice Sets metadata for a specific nonce (series) within a class
* @dev Only callable by DEFAULT_ADMIN_ROLE. Used to describe individual bond series.
* @param classId The class identifier
* @param metadataId The metadata identifier for the nonce
* @param m The metadata struct containing title, type, and description
*/
function setNonceMetadata(uint256 classId, uint256 metadataId, Metadata calldata m) external onlyRole(DEFAULT_ADMIN_ROLE) {
_classes[classId]._nonceMetadatas[metadataId] = m;
emit NonceMetadataSet(classId, metadataId, m);
}
/**
* @notice Configures the issuance and maturity schedule for a nonce (series)
* @dev Only callable by DEFAULT_ADMIN_ROLE. MUST be called before issuing bonds for this class/nonce pair.
* The contract validates that issuance > 0 and maturity > issuance during the issue() operation.
* Stores values at index 0 (issuance) and index 1 (maturity) for indexed retrieval.
* @param c The class identifier
* @param n The nonce identifier
* @param issuance The Unix timestamp when bonds become active
* @param maturity The Unix timestamp when bonds mature
*/
function setNonceSchedule(uint256 c, uint256 n, uint256 issuance, uint256 maturity) external onlyRole(DEFAULT_ADMIN_ROLE) {
// Set issuance with index
_classes[c]._nonces[n]._valuesId[0] = "issuance";
_classes[c]._nonces[n]._values["issuance"].uintValue = issuance;
// Set maturity with index
_classes[c]._nonces[n]._valuesId[1] = "maturity";
_classes[c]._nonces[n]._values["maturity"].uintValue = maturity;
emit NonceScheduleSet(c, n, issuance, maturity);
}
/**
* @notice Sets a custom value for a class that can be retrieved by index or key
* @dev Only callable by DEFAULT_ADMIN_ROLE. Populates both _valuesId mapping (for indexed access)
* and _values mapping (for key-based access). Can store strings, uints, addresses, or bools.
* @param classId The class identifier
* @param index The index for retrieving this value via classValues()
* @param key The string key for retrieving this value via getClassValueByKey()
* @param value The Values struct containing stringValue, uintValue, addressValue, and boolValue
*/
function setClassValue(
uint256 classId,
uint256 index,
string calldata key,
Values calldata value
) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(bytes(key).length > 0, "EMPTY_KEY");
_classes[classId]._valuesId[index] = key;
_classes[classId]._values[key] = value;
emit ClassValueSet(classId, index, key);
}
/**
* @notice Sets a custom value for a nonce that can be retrieved by index or key
* @dev Only callable by DEFAULT_ADMIN_ROLE. Populates both _valuesId mapping (for indexed access)
* and _values mapping (for key-based access). Can store strings, uints, addresses, or bools.
* Useful for storing nonce-specific data like loan merkle roots or loan counts.
* @param classId The class identifier
* @param nonceId The nonce identifier
* @param index The index for retrieving this value via nonceValues()
* @param key The string key for retrieving this value via getNonceValueByKey()
* @param value The Values struct containing stringValue, uintValue, addressValue, and boolValue
*/
function setNonceValue(
uint256 classId,
uint256 nonceId,
uint256 index,
string calldata key,
Values calldata value
) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(bytes(key).length > 0, "EMPTY_KEY");
_classes[classId]._nonces[nonceId]._valuesId[index] = key;
_classes[classId]._nonces[nonceId]._values[key] = value;
emit NonceValueSet(classId, nonceId, index, key);
}
/**
* @notice Retrieves a class value by its string key
* @dev Returns empty Values struct if key doesn't exist. Alternative to classValues() for key-based access.
* @param classId The class identifier
* @param key The string key of the value to retrieve
* @return Values struct containing stringValue, uintValue, addressValue, and boolValue
*/
function getClassValueByKey(uint256 classId, string calldata key)
external
view
returns (Values memory)
{
require(bytes(key).length > 0, "EMPTY_KEY");
return _classes[classId]._values[key];
}
/**
* @notice Retrieves a nonce value by its string key
* @dev Returns empty Values struct if key doesn't exist. Alternative to nonceValues() for key-based access.
* @param classId The class identifier
* @param nonceId The nonce identifier
* @param key The string key of the value to retrieve
* @return Values struct containing stringValue, uintValue, addressValue, and boolValue
*/
function getNonceValueByKey(uint256 classId, uint256 nonceId, string calldata key)
external
view
returns (Values memory)
{
require(bytes(key).length > 0, "EMPTY_KEY");
return _classes[classId]._nonces[nonceId]._values[key];
}
/* ---------- Approvals ---------- */
/**
* @notice Approves or revokes an operator to manage all bonds on behalf of msg.sender
* @dev The operator must be whitelisted. This is a global approval that applies to all
* classes and nonces. When approved, the operator can call transferFrom() on behalf
* of the owner without needing per-transaction allowances.
* @param op The operator address to approve or revoke
* @param ok True to approve, false to revoke approval
*/
function setApprovalFor(address op, bool ok) external override whenNotPaused {
require(_wl[op], "OPERATOR_NOT_WHITELISTED");
_operatorApprovals[msg.sender][op] = ok;
emit ApprovalFor(msg.sender, op, ok);
}
/**
* @notice Approves a spender to transfer specific bond amounts via allowances
* @dev The spender must be whitelisted. Implements ERC20-style allowance race condition protection:
* you must set allowance to 0 before changing it to a non-zero value. Supports batch approvals
* for multiple class/nonce pairs (up to MAX_BATCH=64 transactions).
* @param spender The address that will be allowed to spend bonds
* @param txs Array of Transaction structs, each containing classId, nonceId, and _amount
*/
function approve(address spender, Transaction[] calldata txs) external override whenNotPaused {
require(_wl[spender], "SPENDER_NOT_WHITELISTED");
uint256 len = txs.length;
require(len > 0 && len <= MAX_BATCH, "BATCH");
for (uint256 i; i < len; ) {
Transaction calldata t = txs[i];
uint256 cur = _classes[t.classId]._nonces[t.nonceId]._allowances[msg.sender][spender];
require(t._amount == 0 || cur == 0, "ALLOW_NONZERO");
_classes[t.classId]._nonces[t.nonceId]._allowances[msg.sender][spender] = t._amount;
emit Approval(msg.sender, spender, t.classId, t.nonceId, t._amount);
unchecked { ++i; }
}
}
/* ---------- Transfers ---------- */
/**
* @notice Transfers bonds from one address to another
* @dev Caller must be either the 'from' address or an approved operator (via setApprovalFor).
* Both 'from' and 'to' must be whitelisted. Supports batch transfers for multiple
* class/nonce pairs (up to MAX_BATCH=64 transactions). Does not consume allowances.
* @param from The address to transfer bonds from
* @param to The address to transfer bonds to
* @param txs Array of Transaction structs, each containing classId, nonceId, and _amount
*/
function transferFrom(address from, address to, Transaction[] calldata txs) external override whenNotPaused {
require(from != address(0) && to != address(0), "ADDR");
require(msg.sender == from || _operatorApprovals[from][msg.sender], "AUTH");
require(_wl[from] && _wl[to], "WL");
uint256 len = txs.length;
require(len > 0 && len <= MAX_BATCH, "BATCH");
for (uint256 i; i < len; ) {
Transaction calldata t = txs[i];
require(t._amount > 0, "AMT");
_debit(from, t.classId, t.nonceId, t._amount);
_credit(to, t.classId, t.nonceId, t._amount);
unchecked { ++i; }
}
emit Transfer(msg.sender, from, to, txs);
}
/**
* @notice Transfers bonds using an allowance (similar to ERC20 transferFrom)
* @dev Caller must have sufficient allowance for each transaction (set via approve()).
* Both 'from' and 'to' must be whitelisted. Allowances are decreased by the transferred
* amounts. Supports batch transfers for multiple class/nonce pairs (up to MAX_BATCH=64).
* @param from The address to transfer bonds from
* @param to The address to transfer bonds to
* @param txs Array of Transaction structs, each containing classId, nonceId, and _amount
*/
function transferAllowanceFrom(address from, address to, Transaction[] calldata txs) external override whenNotPaused {
require(from != address(0) && to != address(0), "ADDR");
require(_wl[from] && _wl[to], "WL");
uint256 len = txs.length;
require(len > 0 && len <= MAX_BATCH, "BATCH");
for (uint256 i; i < len; ) {
Transaction calldata t = txs[i];
require(t._amount > 0, "AMT");
Nonce storage n = _classes[t.classId]._nonces[t.nonceId];
uint256 currentAllowance = n._allowances[from][msg.sender];
require(currentAllowance >= t._amount, "ALLOW");
unchecked { n._allowances[from][msg.sender] = currentAllowance - t._amount; }
_debit(from, t.classId, t.nonceId, t._amount);
_credit(to, t.classId, t.nonceId, t._amount);
unchecked { ++i; }
}
emit Transfer(msg.sender, from, to, txs);
}
/* ---------- Lifecycle ---------- */
/**
* @notice Issues (mints) new bonds to a whitelisted address
* @dev Only callable by OPERATOR_ROLE. The nonce must be configured via setNonceSchedule()
* before issuance (validates issuance > 0 && maturity > issuance). Increases both the
* recipient's balance and the active supply. Supports batch issuance (up to MAX_BATCH=64).
* Note: 1 unit = €1 face value. Interest is serviced off-chain.
* @param to The whitelisted address to receive the bonds
* @param txs Array of Transaction structs, each containing classId, nonceId, and _amount
*/
function issue(address to, Transaction[] calldata txs) external override whenNotPaused onlyRole(OPERATOR_ROLE) {
require(to != address(0) && _wl[to], "WL");
uint256 len = txs.length;
require(len > 0 && len <= MAX_BATCH, "BATCH");
for (uint256 i; i < len; ) {
Transaction calldata t = txs[i];
require(t._amount > 0, "AMT");
uint256 issuance = _classes[t.classId]._nonces[t.nonceId]._values["issuance"].uintValue;
uint256 maturity = _classes[t.classId]._nonces[t.nonceId]._values["maturity"].uintValue;
require(issuance > 0 && maturity > issuance, "NONCE_NOT_CONFIGURED");
_credit(to, t.classId, t.nonceId, t._amount);
_classes[t.classId]._nonces[t.nonceId]._activeSupply += t._amount;
unchecked { ++i; }
}
emit Issue(msg.sender, to, txs);
}
/**
* @notice Redeems bonds at maturity, mirroring principal repayment
* @dev Only callable by OPERATOR_ROLE. Decreases the holder's balance and active supply,
* increases redeemed supply. Used to reflect off-chain principal repayment at maturity.
* Supports batch redemption (up to MAX_BATCH=64 transactions).
* @param from The address holding the bonds to redeem
* @param txs Array of Transaction structs, each containing classId, nonceId, and _amount
*/
function redeem(address from, Transaction[] calldata txs) external override whenNotPaused onlyRole(OPERATOR_ROLE) {
require(from != address(0), "ADDR");
uint256 len = txs.length;
require(len > 0 && len <= MAX_BATCH, "BATCH");
for (uint256 i; i < len; ) {
Transaction calldata t = txs[i];
require(t._amount > 0, "AMT");
_debit(from, t.classId, t.nonceId, t._amount);
Nonce storage n = _classes[t.classId]._nonces[t.nonceId];
n._activeSupply -= t._amount;
n._redeemedSupply += t._amount;
unchecked { ++i; }
}
emit Redeem(msg.sender, from, txs);
}
/**
* @notice Burns bonds (e.g., for write-offs or cancellations)
* @dev Only callable by OPERATOR_ROLE. Decreases the holder's balance and active supply,
* increases burned supply. Used when bonds need to be permanently removed from circulation
* (e.g., loan defaults, early termination). Supports batch burning (up to MAX_BATCH=64).
* @param from The address holding the bonds to burn
* @param txs Array of Transaction structs, each containing classId, nonceId, and _amount
*/
function burn(address from, Transaction[] calldata txs) external override whenNotPaused onlyRole(OPERATOR_ROLE) {
require(from != address(0), "ADDR");
uint256 len = txs.length;
require(len > 0 && len <= MAX_BATCH, "BATCH");
for (uint256 i; i < len; ) {
Transaction calldata t = txs[i];
require(t._amount > 0, "AMT");
_debit(from, t.classId, t.nonceId, t._amount);
Nonce storage n = _classes[t.classId]._nonces[t.nonceId];
n._activeSupply -= t._amount;
n._burnedSupply += t._amount;
unchecked { ++i; }
}
emit Burn(msg.sender, from, txs);
}
/* ---------- Views ---------- */
/**
* @notice Returns the total supply for a specific class/nonce pair
* @dev Total supply = active supply + redeemed supply + burned supply.
* This represents all bonds ever issued for this nonce, regardless of their current state.
* @param c The class identifier
* @param n The nonce identifier
* @return The total supply (sum of active, redeemed, and burned)
*/
function totalSupply(uint256 c, uint256 n) external view override returns (uint256) {
Nonce storage nonce = _classes[c]._nonces[n];
return nonce._activeSupply + nonce._redeemedSupply + nonce._burnedSupply;
}
/**
* @notice Returns the redeemed supply for a specific class/nonce pair
* @dev Redeemed bonds have reached maturity and principal was repaid off-chain
* @param c The class identifier
* @param n The nonce identifier
* @return The amount of bonds that have been redeemed
*/
function redeemedSupply(uint256 c, uint256 n) external view override returns (uint256) {
return _classes[c]._nonces[n]._redeemedSupply;
}
/**
* @notice Returns the burned supply for a specific class/nonce pair
* @dev Burned bonds were permanently removed (e.g., defaults, cancellations)
* @param c The class identifier
* @param n The nonce identifier
* @return The amount of bonds that have been burned
*/
function burnedSupply(uint256 c, uint256 n) external view override returns (uint256) {
return _classes[c]._nonces[n]._burnedSupply;
}
/**
* @notice Returns the active supply for a specific class/nonce pair
* @dev Active bonds are currently in circulation and held by investors
* @param c The class identifier
* @param n The nonce identifier
* @return The amount of bonds currently active (not redeemed or burned)
*/
function activeSupply(uint256 c, uint256 n) external view override returns (uint256) {
return _classes[c]._nonces[n]._activeSupply;
}
/**
* @notice Returns the bond balance of an address for a specific class/nonce pair
* @param a The address to query
* @param c The class identifier
* @param n The nonce identifier
* @return The amount of bonds held by the address
*/
function balanceOf(address a, uint256 c, uint256 n) external view override returns (uint256) {
return _classes[c]._nonces[n]._balances[a];
}
/**
* @notice Returns the allowance granted by an owner to a spender for a specific class/nonce pair
* @dev Used with transferAllowanceFrom() for ERC20-style delegated transfers
* @param owner The address that owns the bonds
* @param spender The address that is allowed to spend
* @param c The class identifier
* @param n The nonce identifier
* @return The amount the spender is allowed to transfer on behalf of the owner
*/
function allowance(address owner, address spender, uint256 c, uint256 n) external view override returns (uint256) {
return _classes[c]._nonces[n]._allowances[owner][spender];
}
/**
* @notice Checks if an operator is approved to manage all bonds for an owner
* @dev Set via setApprovalFor(). This is a global approval for all classes and nonces.
* @param owner The address that owns the bonds
* @param op The operator address to check
* @return True if the operator is approved, false otherwise
*/
function isApprovedFor(address owner, address op) external view override returns (bool) {
return _operatorApprovals[owner][op];
}
/**
* @notice Returns metadata for a class
* @param id The metadata identifier
* @return Metadata struct containing title, type, and description
*/
function classMetadata(uint256 id) external view override returns (Metadata memory) {
return _classMetadata[id];
}
/**
* @notice Returns metadata for a nonce within a class
* @param c The class identifier
* @param id The metadata identifier
* @return Metadata struct containing title, type, and description
*/
function nonceMetadata(uint256 c, uint256 id) external view override returns (Metadata memory) {
return _classes[c]._nonceMetadatas[id];
}
/**
* @notice Returns a class value by its index
* @dev Reverts if no value exists at the specified index. Use getClassValueByKey() for key-based access.
* @param c The class identifier
* @param id The index to retrieve
* @return Values struct containing stringValue, uintValue, addressValue, and boolValue
*/
function classValues(uint256 c, uint256 id) external view override returns (Values memory) {
string memory key = _classes[c]._valuesId[id];
require(bytes(key).length != 0, "VAL");
return _classes[c]._values[key];
}
/**
* @notice Returns a nonce value by its index
* @dev Reverts if no value exists at the specified index. Use getNonceValueByKey() for key-based access.
* Index 0 = "issuance", index 1 = "maturity" (set via setNonceSchedule).
* @param c The class identifier
* @param n The nonce identifier
* @param id The index to retrieve
* @return Values struct containing stringValue, uintValue, addressValue, and boolValue
*/
function nonceValues(uint256 c, uint256 n, uint256 id) external view override returns (Values memory) {
string memory key = _classes[c]._nonces[n]._valuesId[id];
require(bytes(key).length != 0, "VAL");
return _classes[c]._nonces[n]._values[key];
}
/**
* @notice Calculates time progress toward maturity for a nonce
* @dev Returns (0, 0) if nonce is not configured or has invalid schedule.
* Before issuance: returns (0, total_term).
* During term: returns (elapsed, remaining).
* After maturity: returns (total_term, 0).
* @param c The class identifier
* @param n The nonce identifier
* @return done Seconds elapsed since issuance (0 if not started, total if matured)
* @return remain Seconds remaining until maturity (0 if matured, total if not started)
*/
function getProgress(uint256 c, uint256 n) external view override returns (uint256 done, uint256 remain) {
uint256 issuance = _classes[c]._nonces[n]._values["issuance"].uintValue;
uint256 maturity = _classes[c]._nonces[n]._values["maturity"].uintValue;
if (issuance == 0 || maturity <= issuance) return (0, 0);
if (block.timestamp >= maturity) return (maturity - issuance, 0);
if (block.timestamp < issuance) return (0, maturity - issuance);
uint256 elapsed = block.timestamp - issuance;
uint256 total = maturity - issuance;
return (elapsed, total - elapsed);
}
/* ---------- Internals ---------- */
/**
* @notice Internal function to decrease an address's bond balance
* @dev Reverts if the address has insufficient balance. Used by transfer, redeem, and burn operations.
* @param from The address to debit bonds from
* @param c The class identifier
* @param n The nonce identifier
* @param amt The amount to debit
*/
function _debit(address from, uint256 c, uint256 n, uint256 amt) internal {
Nonce storage nonce = _classes[c]._nonces[n];
uint256 fromBalance = nonce._balances[from];
require(fromBalance >= amt, "BAL");
unchecked { nonce._balances[from] = fromBalance - amt; }
}
/**
* @notice Internal function to increase an address's bond balance
* @dev Used by transfer and issue operations. Does not check for overflow (safe with uint256).
* @param to The address to credit bonds to
* @param c The class identifier
* @param n The nonce identifier
* @param amt The amount to credit
*/
function _credit(address to, uint256 c, uint256 n, uint256 amt) internal {
_classes[c]._nonces[n]._balances[to] += amt;
}
/**
* @notice Indicates whether the contract supports a given interface
* @dev Implements ERC165 via AccessControl. Returns true for IERC3475 and inherited interfaces.
* @param iid The interface identifier to check
* @return True if the interface is supported, false otherwise
*/
function supportsInterface(bytes4 iid) public view override(AccessControlUpgradeable) returns (bool) {
return iid == type(IERC3475).interfaceId || super.supportsInterface(iid);
}
// Reserve 50 slots for future upgrades
uint256[50] private __gap;
}
"
},
"src/interfaces/IERC3475.sol": {
"content": "// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.0;
interface IERC3475 {
// STRUCTURE
/**
* @dev Values structure of the Metadata
*/
struct Values {
string stringValue;
uint uintValue;
address addressValue;
bool boolValue;
}
/**
* @dev structure allows to define particular bond metadata (ie the values in the class as well as nonce inputs).
* @notice 'title' defining the title information,
* @notice '_type' explaining the data type of the title information added (eg int, bool, address),
* @notice 'description' explains little description about the information stored in the bond",
*/
struct Metadata {
string title;
string _type;
string description;
}
/**
* @dev structure that defines the parameters for specific issuance of bonds and amount which are to be transferred/issued/given allowance, etc.
* @notice this structure is used to streamline the input parameters for functions of this standard with that of other Token standards like ERC20.
* @classId is the class id of the bond.
* @nonceId is the nonce id of the given bond class. This param is for distinctions of the issuing conditions of the bond.
* @amount is the amount of the bond that will be transferred.
*/
struct Transaction {
uint256 classId;
uint256 nonceId;
uint256 _amount;
}
// WRITABLES
/**
* @dev allows the transfer of a bond from one address to another (either single or in batches).
* @param _from is the address of the holder whose balance is about to decrease.
* @param _to is the address of the recipient whose balance is about to increase.
* @param _transactions is the object defining {class,nonce and amount of the bonds to be transferred}.
*/
function transferFrom(address _from, address _to, Transaction[] calldata _transactions) external;
/**
* @dev allows the transfer of allowance from one address to another (either single or in batches).
* @param _from is the address of the holder whose balance about to decrease.
* @param _to is the address of the recipient whose balance is about to increased.
* @param _transactions is the object defining {class,nonce and amount of the bonds to be allowed to transferred}.
*/
function transferAllowanceFrom(address _from, address _to, Transaction[] calldata _transactions) external;
/**
* @dev allows issuing of any number of bond types to an address(either single/batched issuance).
* The calling of this function needs to be restricted to bond issuer contract.
* @param _to is the address to which the bond will be issued.
* @param _transactions is the object defining {class,nonce and amount of the bonds to be issued for given whitelisted bond}.
*/
function issue(address _to, Transaction[] calldata _transactions) external;
/**
* @dev allows redemption of any number of bond types from an address.
* The calling of this function needs to be restricted to bond issuer contract.
* @param _from is the address _from which the bond will be redeemed.
* @param _transactions is the object defining {class,nonce and amount of the bonds to be redeemed for given whitelisted bond}.
*/
function redeem(address _from, Transaction[] calldata _transactions) external;
/**
* @dev allows the transfer of any number of bond types from an address to another.
* The calling of this function needs to be restricted to bond issuer contract.
* @param _from is the address of the holder whose balance about to decrease.
* @param _transactions is the object defining {class,nonce and amount of the bonds to be redeemed for given whitelisted bond}.
*/
function burn(address _from, Transaction[] calldata _transactions) external;
/**
* @dev Allows _spender to withdraw from your account multiple times, up to the amount.
* @notice If this function is called again, it overwrites the current allowance with amount.
* @param _spender is the address the caller approve for his bonds.
* @param _transactions is the object defining {class,nonce and amount of the bonds to be approved for given whitelisted bond}.
*/
function approve(address _spender, Transaction[] calldata _transactions) external;
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
* @dev MUST emit the ApprovalForAll event on success.
* @param _operator Address to add to the set of authorized operators
* @param _approved "True" if the operator is approved, "False" to revoke approval.
*/
function setApprovalFor(address _operator, bool _approved) external;
// READABLES
/**
* @dev Returns the total supply of the bond in question.
*/
function totalSupply(uint256 classId, uint256 nonceId) external view returns (uint256);
/**
* @dev Returns the redeemed supply of the bond in question.
*/
function redeemedSupply(uint256 classId, uint256 nonceId) external view returns (uint256);
/**
* @dev Returns the active supply of the bond in question.
*/
function activeSupply(uint256 classId, uint256 nonceId) external view returns (uint256);
/**
* @dev Returns the burned supply of the bond in question.
*/
function burnedSupply(uint256 classId, uint256 nonceId) external view returns (uint256);
/**
* @dev Returns the balance of the giving bond classId and bond nonce.
*/
function balanceOf(address _account, uint256 classId, uint256 nonceId) external view returns (uint256);
/**
* @dev Returns the JSON metadata of the classes.
* The metadata SHOULD follow a set of structure explained later in eip-3475.md
* @param metadataId is the index corresponding to the class parameter that you want to return from mapping.
*/
function classMetadata(uint256 metadataId) external view returns ( Metadata memory);
/**
* @dev Returns the JSON metadata of the Values of the nonces in the corresponding class.
* @param classId is the specific classId of which you want to find the metadata of the corresponding nonce.
* @param metadataId is the index corresponding to the class parameter that you want to return from mapping.
* @notice The metadata SHOULD follow a set of structure explained later in metadata section.
*/
function nonceMetadata(uint256 classId, uint256 metadataId) external view returns ( Metadata memory);
/**
* @dev Returns the values of the given classId.
* @param classId is the specific classId of which we want to return the parameter.
* @param metadataId is the index corresponding to the class parameter that you want to return from mapping.
* the metadata SHOULD follow a set of structures explained in eip-3475.md
*/
function classValues(uint256 classId, uint256 metadataId) external view returns ( Values memory);
/**
* @dev Returns the values of given nonceId.
* @param metadataId index number of structure as explained in the metadata section in EIP-3475.
* @param classId is the class of bonds for which you determine the nonce.
* @param nonceId is the nonce for which you return the value struct info.
* Returns the values object corresponding to the given value.
*/
function nonceValues(uint256 classId, uint256 nonceId, uint256 metadataId) external view returns ( Values memory);
/**
* @dev Returns the information about the progress needed to redeem the bond identified by classId and nonceId.
* @notice Every bond contract can have its own logic concerning the progress definition.
* @param classId The class of bonds.
* @param nonceId is the nonce of bonds for finding the progress.
* Returns progressAchieved is the current progress achieved.
* Returns progressRemaining is the remaining progress.
*/
function getProgress(uint256 classId, uint256 nonceId) external view returns (uint256 progressAchieved, uint256 progressRemaining);
/**
* @notice Returns the amount that spender is still allowed to withdraw from _owner (for given classId and nonceId issuance)
* @param _owner is the address whose owner allocates some amount to the _spender address.
* @param classId is the classId of the bond.
* @param nonceId is the nonce corresponding to the class for which you are approving the spending of total amount of bonds.
*/
function allowance(address _owner, address _spender, uint256 classId, uint256 nonceId) external view returns (uint256);
/**
* @notice Queries the approval status of an operator for bonds (for all classes and nonce issuances of owner).
* @param _owner is the current holder of the bonds for all classes/nonces.
* @param _operator is the address with access to the bonds of _owner for transferring.
* Returns "true" if the operator is approved, "false" if not.
*/
function isApprovedFor(address _owner, address _operator) external view returns (bool);
// EVENTS
/**
* @notice MUST trigger when tokens are transferred, including zero value transfers.
* e.g:
emit Transfer(0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef, 0x492Af743654549b12b1B807a9E0e8F397E44236E,0x3d03B6C79B75eE7aB35298878D05fe36DC1fEf, [IERC3475.Transaction(1,14,500)])
means that operator 0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef wants to transfer 500 bonds of class 1 , Nonce 14 of owner 0x492Af743654549b12b1B807a9E0e8F397E44236E to address 0x3d03B6C79B75eE7aB35298878D05fe36DC1fEf.
*/
event Transfer(address indexed _operator, address indexed _from, address indexed _to, Transaction[] _transactions);
/**
* @notice MUST trigger when tokens are issued
* @notice Issue MUST trigger when Bonds are issued. This SHOULD not include zero value Issuing.
* @dev This SHOULD not include zero value issuing.
* @dev Issue MUST be triggered when the operator (i.e Bank address) contract issues bonds to the given entity.
eg: emit Issue(_operator, 0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef,[IERC3475.Transaction(1,14,500)]);
issue by address(operator) 500 Bonds(nonce14,class 0) to address 0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef.
*/
event Issue(address indexed _operator, address indexed _to, Transaction[] _transactions);
/**
* @notice MUST trigger when tokens are redeemed.
* @notice Redeem MUST trigger when Bonds are redeemed. This SHOULD not include zero value redemption.
* eg: emit Redeem(0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef,0x492Af743654549b12b1B807a9E0e8F397E44236E,[IERC3475.Transaction(1,14,500)]);
* this emit event when 5000 bonds of class 1, nonce 14 owned by address 0x492Af743654549b12b1B807a9E0e8F397E44236E are being redeemed by 0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef.
*/
event Redeem(address indexed _operator, address indexed _from, Transaction[] _transactions);
/**
* @notice MUST trigger when tokens are burned
* @dev `Burn` MUST trigger when the bonds are being redeemed via staking (or being invalidated) by the bank contract.
* @dev `Burn` MUST trigger when Bonds are burned. This SHOULD not include zero value burning
* @notice emit Burn(0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef,0x492Af743654549b12b1B807a9E0e8F397E44236E,[IERC3475.Transaction(1,14,500)]);
* emits event when 5000 bonds of owner 0x492Af743654549b12b1B807a9E0e8F397E44236E of type (class 1, nonce 14) are burned by operator 0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef.
*/
event Burn(address indexed _operator, address indexed _from, Transaction[] _transactions);
/**
* @dev MUST emit when approval for a second party/operator address to manage all bonds from a classId given for an owner address is enabled or disabled (absence of an event assumes disabled).
* @dev its emitted when address(_owner) approves the address(_operator) to transfer his bonds.
* @notice Approval MUST trigger when bond holders are approving an _operator. This SHOULD not include zero value approval.
*/
event ApprovalFor(address indexed _owner, address indexed _operator, bool _approved);
}
"
},
"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reinitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}
"
},
"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.22;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
"
},
"lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(
Submitted on: 2025-10-31 19:14:16
Comments
Log in to comment.
No comments yet.