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": {
"CosigoSatellite.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import "@openzeppelin/contracts@4.9.6/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts@4.9.6/token/ERC20/extensions/ERC20Permit.sol";
import "@openzeppelin/contracts@4.9.6/security/Pausable.sol";
import "@openzeppelin/contracts@4.9.6/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts@4.9.6/access/AccessControl.sol";
import "@openzeppelin/contracts@4.9.6/token/ERC20/utils/SafeERC20.sol";
import {ICosigoGuardian} from "./ICosigoGuardian.sol";
import {GuardianAware} from "./GuardianAware.sol";
/* solhint-disable not-rely-on-time */
contract CosigoSatellite is
ERC20,
ERC20Permit,
Pausable,
ReentrancyGuard,
AccessControl,
GuardianAware
{
using SafeERC20 for IERC20;
// ---------- Constants & Roles ----------
uint8 private constant DEC = 18;
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant CUSTODIAN_ROLE = keccak256("CUSTODIAN_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
// Local hard caps (must also pass Guardian caps)
uint16 public constant MAX_MAINTENANCE_FEE_BPS = 500; // 5.00%
uint16 public constant MAX_REDEMPTION_FEE_BPS = 2500; // 25.00%
uint16 public constant MAX_PREMIUM_BPS = 3000; // 30.00%
// Town slug policy (without "cosigo_" prefix)
uint256 private constant MIN_SLUG_LEN = 4;
uint256 private constant MAX_SLUG_LEN = 32;
// Store slug only; ERC20 handles name/symbol
string public _slug; // e.g., "queretaro"
bytes32 public _slugHash;
// ---------- Economics & caps ----------
uint16 public maintenanceFeeBps; // transfer fee (to feeSinkLocal)
uint16 public redemptionFeeBps; // applied on redemption request (burned with mg)
uint16 public premiumBps; // premium on spot for floor checks
address public feeSinkLocal; // local sink for maintenance fee (optional)
// Burn sink + effective supply
address public burnSink;
event BurnSinkSet(address indexed sink);
// Minimum redemption (0 = off)
uint256 public minRedemptionMg1e18;
event MinRedemptionSet(uint256 mg1e18);
// Sensitive setters timelock
uint32 public paramTimelockSeconds = 0;
mapping(bytes32 => uint64) public paramEta;
// ---------- Custody & headroom accounting ----------
struct Deposit { uint256 gramsMilli; bytes32 docHash; address depositor; uint64 ts; }
Deposit[] public deposits;
uint256 public totalGramsMilliDeposited;
// Prevent burn-resurrection of headroom
uint256 public mgFulfilled1e18; // shipped (fulfilled)
uint256 public mgPending1e18; // requested (burned mg), awaiting fulfill/cancel
// ---------- Daily redemption caps ----------
uint256 public dailyCapGlobalMg1e18;
uint256 public dailyCapPerAddrMg1e18;
struct Counter { uint256 amount; uint64 windowStart; }
mapping(address => Counter) public redeemCounter;
Counter public redeemCounterGlobal;
// ---------- Blacklist ----------
mapping(address => bool) public blacklisted;
// ---------- Price/floor ----------
uint256 public spotMicroCentsPerMg; // settable
uint256 public minFloorMicroCentsPerMg; // settable
// ---------- Events ----------
event DepositRegistered(uint256 idx, uint256 gramsMilli, bytes32 docHash, address indexed depositor);
event MintedAgainstHeadroom(address indexed to, uint256 amountMg1e18, uint256 headroomAfter);
event SpotSet(uint256 microCentsPerMg);
event PremiumSet(uint16 bps);
event MinFloorSet(uint256 microCentsPerMg);
event MaintenanceFeeSet(uint16 bps);
event RedemptionFeeSet(uint16 bps);
event FeeSinkLocalSet(address indexed sink);
event RedemptionRequested(bytes32 id, address indexed account, uint256 mg1e18, bytes32 ref);
event RedemptionFulfilled(bytes32 id, string trackingHash);
event RedemptionCancelled(bytes32 id, string reason);
event RedemptionCapsSet(uint256 perAddrMg1e18, uint256 globalMg1e18);
event GuardianFeeSkim(address indexed from, address indexed sink, uint256 fee, uint16 bps);
event Blacklisted(address indexed acct, bool on, uint8 code);
event ParamTimelockSet(uint32 seconds_);
event GuardianProposed(address indexed next, uint32 delay);
event GuardianAccepted(address indexed next);
event GuardianProposalCancelled();
// ---------- Modifiers ----------
modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "not admin"); _; }
modifier onlyCustodian() { require(hasRole(CUSTODIAN_ROLE, msg.sender), "not custodian"); _; }
modifier onlyMinter() { require(hasRole(MINTER_ROLE, msg.sender), "not minter"); _; }
modifier notBlacklisted(address a) { require(!blacklisted[a], "blacklisted"); _; }
// ---------- Constructor ----------
constructor(string memory town_, address guardian_)
ERC20(string.concat("cosigo_", town_), string.concat("cosigo_", town_))
ERC20Permit(string.concat("cosigo_", town_))
GuardianAware(guardian_)
{
// Validate slug
bytes memory s = bytes(town_);
require(s.length >= MIN_SLUG_LEN && s.length <= MAX_SLUG_LEN, "slug len");
for (uint i = 0; i < s.length; ) {
bytes1 c = s[i];
bool ok = (c >= 0x61 && c <= 0x7a) || (c >= 0x30 && c <= 0x39); // a-z0-9
require(ok, "slug char");
unchecked { ++i; }
}
_slug = town_;
_slugHash = keccak256(s);
// Initial local admin/pauser = deployer
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(PAUSER_ROLE, msg.sender);
}
// ERC20 metadata: decimals
function decimals() public pure override returns (uint8){ return DEC; }
function slug() external view returns (string memory){ return _slug; }
function slugHash() external view returns (bytes32){ return _slugHash; }
// ERC165 passthrough for AccessControl
function supportsInterface(bytes4 interfaceId)
public view override(AccessControl) returns (bool)
{
return super.supportsInterface(interfaceId);
}
// ---------- Param timelock helpers ----------
function _pqueue(bytes32 id) internal {
if (paramTimelockSeconds != 0) {
paramEta[id] = uint64(block.timestamp) + paramTimelockSeconds;
}
}
function _pcheck(bytes32 id) internal view {
if (paramTimelockSeconds == 0) return;
require(paramEta[id] != 0 && block.timestamp >= paramEta[id], "param timelock");
}
function _pclear(bytes32 id) internal {
if (paramTimelockSeconds != 0) {
delete paramEta[id];
}
}
function setParamTimelock(uint32 seconds_) external onlyAdmin {
paramTimelockSeconds = seconds_;
emit ParamTimelockSet(seconds_);
}
// ---------- Admin safety ----------
function pause() external onlyRole(PAUSER_ROLE) { _pause(); }
function unpause() external onlyRole(PAUSER_ROLE) { _unpause(); }
function setBlacklist(address acct, bool on, uint8 code) external onlyAdmin {
blacklisted[acct] = on;
emit Blacklisted(acct, on, code);
}
// ---------- Economics (caps enforced: local AND Guardian) ----------
function setMaintenanceFeeBps(uint16 bps) external onlyAdmin {
require(bps <= MAX_MAINTENANCE_FEE_BPS, "local cap");
require(bps <= guardian.maxMaintenanceFeeBps(), "guardian cap");
bytes32 id = keccak256(abi.encode("setMaintenanceFee", bps));
_pqueue(id); _pcheck(id);
maintenanceFeeBps = bps;
_pclear(id);
emit MaintenanceFeeSet(bps);
}
function setRedemptionFeeBps(uint16 bps) external onlyAdmin {
require(bps <= MAX_REDEMPTION_FEE_BPS, "local cap");
require(bps <= guardian.maxRedemptionFeeBps(), "guardian cap");
bytes32 id = keccak256(abi.encode("setRedemptionFee", bps));
_pqueue(id); _pcheck(id);
redemptionFeeBps = bps;
_pclear(id);
emit RedemptionFeeSet(bps);
}
function setPremiumBps(uint16 bps) external onlyAdmin {
require(bps <= MAX_PREMIUM_BPS, "local cap");
require(bps <= guardian.maxPremiumBps(), "guardian cap");
bytes32 id = keccak256(abi.encode("setPremium", bps));
_pqueue(id); _pcheck(id);
premiumBps = bps;
_pclear(id);
emit PremiumSet(bps);
}
function setSpotMicroCentsPerMg(uint256 x) external onlyAdmin {
bytes32 id = keccak256(abi.encode("setSpot", x));
_pqueue(id); _pcheck(id);
spotMicroCentsPerMg = x;
_pclear(id);
emit SpotSet(x);
}
function setMinFloorMicroCentsPerMg(uint256 x) external onlyAdmin {
bytes32 id = keccak256(abi.encode("setFloor", x));
_pqueue(id); _pcheck(id);
minFloorMicroCentsPerMg = x;
_pclear(id);
emit MinFloorSet(x);
}
function setFeeSinkLocal(address sink) external onlyAdmin {
require(sink != address(0), "sink=0");
feeSinkLocal = sink;
emit FeeSinkLocalSet(sink);
}
function setBurnSink(address sink) external onlyAdmin {
require(sink != address(0), "sink=0");
burnSink = sink;
emit BurnSinkSet(sink);
}
function setMinRedemption(uint256 mg1e18) external onlyAdmin {
minRedemptionMg1e18 = mg1e18;
emit MinRedemptionSet(mg1e18);
}
// ---------- Deposits & mint ----------
function registerDeposit(uint256 gramsMilli, bytes32 docHash, address depositor)
external onlyCustodian
{
require(gramsMilli > 0, "grams=0");
require(docHash != bytes32(0), "docHash=0");
deposits.push(Deposit({
gramsMilli: gramsMilli,
docHash: docHash,
depositor: depositor,
ts: uint64(block.timestamp)
}));
totalGramsMilliDeposited += gramsMilli;
emit DepositRegistered(deposits.length - 1, gramsMilli, docHash, depositor);
}
function depositsLength() external view returns (uint256) { return deposits.length; }
function _depositedMg1e18() internal view returns (uint256) {
// gramsMilli == mg units; then * 1e18 for token decimals
return totalGramsMilliDeposited * 1e18;
}
function headroomMg1e18() public view returns (uint256) {
uint256 dep = _depositedMg1e18();
uint256 used = totalSupply() + mgPending1e18 + mgFulfilled1e18;
if (dep <= used) return 0;
return dep - used;
}
function effectiveSupply() public view returns (uint256 s) {
s = totalSupply();
if (feeSinkLocal != address(0)) {
uint256 b = balanceOf(feeSinkLocal);
if (b >= s) return 0;
s -= b;
}
if (burnSink != address(0)) {
uint256 b2 = balanceOf(burnSink);
if (b2 >= s) return 0;
s -= b2;
}
}
function mintAgainstHeadroom(address to, uint256 amountMg1e18)
external onlyMinter
whenNotPaused
{
uint256 room = headroomMg1e18();
require(amountMg1e18 <= room, "exceeds headroom");
_mint(to, amountMg1e18);
emit MintedAgainstHeadroom(to, amountMg1e18, room - amountMg1e18);
}
// ---------- Redemption flow ----------
struct Redemption {
address account;
uint256 mg1e18;
bytes32 ref; // opaque ref
bool fulfilled;
bool cancelled;
}
mapping(bytes32 => Redemption) public redemptions;
function _rollCounter(Counter storage c, uint256 add) internal {
uint64 start = c.windowStart;
if (start == 0 || block.timestamp >= start + 1 days) {
c.windowStart = uint64(block.timestamp);
c.amount = add;
} else {
c.amount += add;
}
}
function setRedemptionCaps(uint256 perAddrMg1e18, uint256 globalMg1e18) external onlyAdmin {
dailyCapPerAddrMg1e18 = perAddrMg1e18;
dailyCapGlobalMg1e18 = globalMg1e18;
emit RedemptionCapsSet(perAddrMg1e18, globalMg1e18);
}
function _enforceCaps(address acct, uint256 mg1e18) internal {
_rollCounter(redeemCounter[acct], mg1e18);
require(dailyCapPerAddrMg1e18 == 0 || redeemCounter[acct].amount <= dailyCapPerAddrMg1e18, "per-addr cap");
_rollCounter(redeemCounterGlobal, mg1e18);
require(dailyCapGlobalMg1e18 == 0 || redeemCounterGlobal.amount <= dailyCapGlobalMg1e18, "global cap");
}
function redeemPhysicalSilver(uint256 mg1e18, bytes32 shippingRef)
public
nonReentrant
whenNotPaused
notBlacklisted(msg.sender)
guardianChecks(msg.sender, address(0), mg1e18)
{
require(mg1e18 > 0, "zero mg");
require(minRedemptionMg1e18 == 0 || mg1e18 >= minRedemptionMg1e18, "min redeem");
_enforceCaps(msg.sender, mg1e18);
// floor latch: (spot * (1 + premium)) >= minFloor
if (minFloorMicroCentsPerMg > 0 && spotMicroCentsPerMg > 0) {
uint256 eff = spotMicroCentsPerMg + (spotMicroCentsPerMg * premiumBps) / 10_000;
require(eff >= minFloorMicroCentsPerMg, "floor not met");
}
// redemption fee (burned with mg for simple accounting)
uint256 fee = (mg1e18 * redemptionFeeBps) / 10_000;
uint256 burnAmount = mg1e18 + fee;
_burn(msg.sender, burnAmount);
// mark pending so headroom doesn't resurrect due to burn
mgPending1e18 += mg1e18;
// deterministic ID
bytes32 id = keccak256(abi.encodePacked(msg.sender, mg1e18, shippingRef, block.number));
redemptions[id] = Redemption({
account: msg.sender,
mg1e18: mg1e18,
ref: shippingRef,
fulfilled: false,
cancelled: false
});
emit RedemptionRequested(id, msg.sender, mg1e18, shippingRef);
}
// convenience overload for front-ends
function redeemPhysicalSilver(uint256 mg1e18, string calldata shippingRefStr) external {
redeemPhysicalSilver(mg1e18, keccak256(bytes(shippingRefStr)));
}
function fulfillRedemption(bytes32 id, string calldata trackingHash)
external onlyCustodian
{
Redemption storage r = redemptions[id];
require(r.account != address(0), "bad id");
require(!r.fulfilled && !r.cancelled, "done");
r.fulfilled = true;
mgPending1e18 -= r.mg1e18;
mgFulfilled1e18 += r.mg1e18;
emit RedemptionFulfilled(id, trackingHash);
}
function cancelRedemption(bytes32 id, string calldata reason)
external onlyCustodian
{
Redemption storage r = redemptions[id];
require(r.account != address(0), "bad id");
require(!r.fulfilled && !r.cancelled, "done");
r.cancelled = true;
// return mg (fee remains burned)
_mint(r.account, r.mg1e18);
mgPending1e18 -= r.mg1e18;
emit RedemptionCancelled(id, reason);
}
// ---------- Transfers with fees & guardian skim ----------
function _transfer(address from, address to, uint256 amount)
internal
override
whenNotPaused
notBlacklisted(from)
notBlacklisted(to)
guardianChecks(from, to, amount)
{
uint256 amt = amount;
// 1) Maintenance fee (local)
if (maintenanceFeeBps > 0 && feeSinkLocal != address(0) && amount > 0 && from != address(0)) {
uint256 f = (amount * maintenanceFeeBps) / 10_000;
if (f > 0) {
super._transfer(from, feeSinkLocal, f);
amt -= f;
}
}
// 2) Guardian skim
uint16 gbps = _guardianFeeBps();
address gsink = _guardianFeeSink();
if (gbps > 0 && gsink != address(0) && amt > 0 && from != address(0)) {
uint256 gf = (amt * gbps) / 10_000;
if (gf > 0) {
super._transfer(from, gsink, gf);
emit GuardianFeeSkim(from, gsink, gf, gbps);
amt -= gf;
}
}
super._transfer(from, to, amt);
}
// for GuardianAware: fee settlement hook
function _transferFee(address from, address sink, uint256 fee) internal override {
if (fee == 0) return;
super._transfer(from, sink, fee);
}
// ---------- Daily ops helpers ----------
function grantLocalRoles(address custodianMS, address minter) external onlyAdmin {
_grantRole(CUSTODIAN_ROLE, custodianMS);
_grantRole(MINTER_ROLE, minter);
}
// ---------- Guardian upgrade (two-step with delay) ----------
address public proposedGuardian;
uint64 public guardianChangeEta; // earliest accept time (unix)
uint32 public guardianChangeDelay = 0;
function proposeGuardian(address next) external onlyAdmin {
proposedGuardian = next;
if (next == address(0)) {
guardianChangeEta = 0;
emit GuardianProposalCancelled();
} else {
guardianChangeEta = uint64(block.timestamp) + guardianChangeDelay;
emit GuardianProposed(next, guardianChangeDelay);
}
}
function acceptGuardian() external onlyAdmin {
address next = proposedGuardian;
require(next != address(0), "no proposal");
require(block.timestamp >= guardianChangeEta, "delay");
guardian = ICosigoGuardian(next);
proposedGuardian = address(0);
guardianChangeEta = 0;
emit GuardianAccepted(address(guardian));
}
function setGuardianChangeDelay(uint32 seconds_) external onlyAdmin {
guardianChangeDelay = seconds_;
}
// Optional view sanity check (off-chain tool can call this)
function assertGuardianBinding() external view returns (bool ok) {
// If guardian maintains a slug registry, verify it points to us
address reg = guardian.satelliteBySlug(_slugHash);
ok = (reg == address(this)) && guardian.isSatelliteApproved(address(this));
}
// ---------- Rescue ----------
function recoverERC20(address token, address to, uint256 amount) external onlyAdmin {
require(token != address(this), "no self");
IERC20(token).safeTransfer(to, amount);
}
}"
},
"GuardianAware.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import {ICosigoGuardian} from "./ICosigoGuardian.sol";
abstract contract GuardianAware {
ICosigoGuardian public guardian;
error GuardianNotApproved();
error EOARequired();
error MarketClosed();
constructor(address guardian_) { guardian = ICosigoGuardian(guardian_); }
modifier guardianChecks(address /*from*/, address /*to*/, uint256 /*amount*/) {
if (!guardian.isSatelliteApproved(address(this))) revert GuardianNotApproved();
if (guardian.eoaOnlyEnabled()) {
if (tx.origin != msg.sender) revert EOARequired();
}
if (!guardian.isMarketOpen()) revert MarketClosed();
_;
}
function _guardianFeeBps() internal view returns (uint16) {
return guardian.guardianFeeBpsOf(address(this));
}
function _guardianFeeSink() internal view returns (address) {
return guardian.feeSinkOf(address(this));
}
// ABSTRACT: implemented by the Satellite (which IS an ERC20)
function _transferFee(address from, address sink, uint256 fee) internal virtual;
// helper for transfer-like flows; returns net amount
function _skimGuardianFee(address from, uint256 amount) internal returns (uint256) {
uint16 bps = _guardianFeeBps();
address sink = _guardianFeeSink();
if (bps == 0 || sink == address(0) || amount == 0) return amount;
uint256 fee = (amount * bps) / 10_000;
if (fee > 0) _transferFee(from, sink, fee);
return amount - fee;
}
}"
},
"ICosigoGuardian.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
interface ICosigoGuardian {
// Per-satellite policy
function isSatelliteApproved(address sat) external view returns (bool);
function feeSinkOf(address sat) external view returns (address);
function guardianFeeBpsOf(address sat) external view returns (uint16);
// Global signals
function isMarketOpen() external view returns (bool);
function eoaOnlyEnabled() external view returns (bool);
// Global caps
function maxGuardianFeeBps() external view returns (uint16);
function maxMaintenanceFeeBps() external view returns (uint16);
function maxRedemptionFeeBps() external view returns (uint16);
function maxPremiumBps() external view returns (uint16);
// Registry helpers
function satelliteBySlug(bytes32 slugHash) external view returns (address);
}"
},
"@openzeppelin/contracts@4.9.6/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
"
},
"@openzeppelin/contracts@4.9.6/access/AccessControl.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.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 AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
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 override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(account),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @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 override returns (bytes32) {
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 override 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 override 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 `account`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
"
},
"@openzeppelin/contracts@4.9.6/security/ReentrancyGuard.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
}
"
},
"@openzeppelin/contracts@4.9.6/security/Pausable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
"
},
"@openzeppelin/contracts@4.9.6/token/ERC20/extensions/ERC20Permit.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/ERC20Permit.sol)
pragma solidity ^0.8.0;
import "./IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/cryptography/EIP712.sol";
import "../../../utils/Counters.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private constant _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`.
* However, to ensure consistency with the upgradeable transpiler, we will continue
* to reserve a slot.
* @custom:oz-renamed-from _PERMIT_TYPEHASH
*/
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @inheritdoc IERC20Permit
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @inheritdoc IERC20Permit
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @inheritdoc IERC20Permit
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
"
},
"@openzeppelin/contracts@4.9.6/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}
"
},
"@openzeppelin/contracts@4.9.6/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev
Submitted on: 2025-10-26 17:52:54
Comments
Log in to comment.
No comments yet.