Verified contractExactMIT
WitnessKey
Address0xdfa921e9c7d85200baf0d8c19ecda6c3fcfa599a
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.20
- Same code
Only this contract
Details
- Compiler
- solc 0.8.20+commit.a1b79de6
- Language
- solidity
- Optimization
- No
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,548,460
- Creation transaction
- 0x5e6298ad81…bc62351b78
9 files
- WitnessKey.solmain24.5 KB
- @openzeppelin/contracts/interfaces/IERC1363.sol4.45 KB
- @openzeppelin/contracts/interfaces/IERC165.sol193 B
- @openzeppelin/contracts/interfaces/IERC20.sol182 B
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol13.31 KB
- @openzeppelin/contracts/utils/ReentrancyGuard.sol4.77 KB
- @openzeppelin/contracts/utils/StorageSlot.sol4.18 KB
- @openzeppelin/contracts/utils/introspection/IERC165.sol871 B
WitnessKey.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
/**
* @title Witness Key (WK)
* @notice cbBTC-backed token for Immutable Editions — ImmutableEditions.com
*
* ─── THE GLASS VAULT — PATENT PENDING ────────────────────────────────────────
*
* Integrity, Witnessed.
*
* It watches — every piece, every hour, nothing moves unseen.
* It holds — 1 sat = 1 key, no one can change it, no one.
* It never locks — the exit works every hour of every day, forever.
*
* ─── Attribution ─────────────────────────────────────────────────────────────
*
* RECIRCULATION MATH
* Dr. Jochen Hoenicke — computer scientist and Trezor hardware wallet
* developer. Created the original linear bonding curve concept as a
* transparency experiment on the Ethereum testnet. The mathematical
* foundation this entire system builds upon.
* https://test.jochen-hoenicke.de/crypto/ponzitoken/
*
* Per-share accumulator pattern refined by aqoleg — https://aqoleg.com/
*
* EVERYTHING ELSE
* The following concepts, systems, and intellectual property are the
* original invention of Michael James Slattery:
*
* Physical concept:
* - Analog Bitcoin — physical art destroyed to redeem digital assets
* - SeedPod™ — embedding a wallet private key inside physical art
* (SeedPod trademark by Lora Green)
* - NFC tap verification of physical assets on chain
* - Read-only NFC tag as a permanent tamper seal
* - Two-wallet system — Ordinal wallet and WK vault sharing one SeedPod
*
* On-chain architecture:
* - Vault registration system linking physical art to blockchain permanently
* - Ordinal oracle — reporting Bitcoin Ordinal movement on Base
* - VaultSwept event — tamper detection across all exit paths
* - Series pieces with optional Ordinal — ordinalNumber = 0 pattern
* - cbBTC as reserve asset — Bitcoin-denominated recirculation on physical art
* - inscribe() — cbBTC in, WK sealed in vault, fee recirculated to holders
*
* Economic model:
* - 1 WK = 1 sat fixed price peg — no AMM, no speculation, no extraction
* - Physical art receives cbBTC recirculation while hanging on a wall
* - Destroying art to redeem digital assets — the redemption mechanism
* - cbBTC recirculation from every trade distributed to all holders and vaults
*
* Brands & intellectual property:
* - Immutable Editions
* - The Glass Vault™ (patent pending)
* - Analog Bitcoin
* - Real World Inscriptions
* - Witness Key (WK)
* - SeedPod™ (trademark: Lora Green)
* - "Integrity, Witnessed."
*
* ─── Network ─────────────────────────────────────────────────────────────────
* Base Sepolia testnet cbBTC : 0xcbB7C0006F23900c38EB856149F799620fcb8A4a
* Base mainnet cbBTC : 0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf
*
* ─── Fixed Price ─────────────────────────────────────────────────────────────
* 1 Satoshi (1 cbBTC unit, 8 decimals) = 1 WK token (0 decimals).
* Because the peg is 1:1, token units and sat units are interchangeable
* throughout the recirculation math — no price conversion needed.
*
* ─── Fees ────────────────────────────────────────────────────────────────────
* Buy : 7% recirculated to all holders as cbBTC
* Sell : 7% recirculated to all holders as cbBTC
* Inscribe : 7% recirculated to all holders as cbBTC
* Recirculate: 0% — recirculation is always free
* Transfer : 0% — always feeless
*
* ─── Minimum amounts ─────────────────────────────────────────────────────────
* Buy/Inscribe minimum: 100 sats
* Sell minimum: 100 sats
* Recirculate minimum: 100 sats
*
* ─── Recirculation math ──────────────────────────────────────────────────────
* Per-share accumulator by aqoleg — https://aqoleg.com/
* Key invariant:
*
* cbbtcInContract = totalSupply
* + totalSupply * recirculationPerToken / MAGNITUDE
* - sum(claimedOf)
*
* Every function maintains this equation. The sell function is the most
* critical — it must use signedSub with only the burned-token baseline,
* and must distribute the fee AFTER updating claimedOf.
*
* claimedOf is int256 — it CAN and WILL go negative. This is correct.
* DO NOT change to uint256. DO NOT change signedSub to signedAdd in sell.
*
* ─── Immutability ────────────────────────────────────────────────────────────
* No owner. No admin. No governance. No upgrades. NO INTERVENTION.
*
* ─── Vault System ────────────────────────────────────────────────────────────
* vaultRegistrar : deployer only — can call inscribe()
* ordinalOracle : deployer only — can call reportOrdinalMoved()
* Both set at deploy time. Permanently immutable. Zero financial control.
* ordinalNumber = 0 is valid — for series pieces without an Ordinal.
*
* VaultSwept : fires when ANY value leaves a registered vault — permanent
* OrdinalMoved : fires when oracle reports Bitcoin Ordinal has moved
*/
contract WitnessKey is ReentrancyGuard {
using SafeERC20 for IERC20;
// ─── Token metadata ───────────────────────────────────────────────────────
string public constant name = "Witness Key";
string public constant symbol = "WK";
uint8 public constant decimals = 0;
// ─── Reserve asset ────────────────────────────────────────────────────────
IERC20 public immutable CBBTC;
// ─── Supply ───────────────────────────────────────────────────────────────
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
// ─── Fees & minimums ──────────────────────────────────────────────────────
uint256 public constant BUY_FEE = 7;
uint256 public constant SELL_FEE = 7;
uint256 public constant INSCRIBE_FEE = 7;
uint256 public constant MIN_SATS = 100;
uint256 public constant MIN_SELL = 100; // prevents sell-fee rounding bypass
uint256 public constant MAX_BUY = 1_000_000; // 0.01 BTC per transaction
// ─── Recirculation accumulator — PITcoin exact ────────────────────────────────
// claimedOf MUST be int256. MUST use signedSub in sell. Never change this.
// The accounting equation requires claimedOf to go negative in normal use.
uint256 public constant MAGNITUDE = 2**64;
uint256 public recirculationPerToken;
mapping(address => int256) public claimedOf;
// ─── Vault registrar ──────────────────────────────────────────────────────
address public immutable vaultRegistrar;
mapping(address => bytes32) public vaultRegistry;
mapping(address => bool) public isVault;
mapping(address => bool) public vaultHasBeenSwept;
mapping(address => uint256) public vaultOrdinal;
mapping(address => bool) public vaultHasOrdinal;
mapping(address => string) public vaultInscriptionId; // Bitcoin Ordinal inscription ID for content rendering
// ─── Ordinal oracle ───────────────────────────────────────────────────────
address public immutable ordinalOracle;
mapping(uint256 => bool) public ordinalHasBeenMoved;
mapping(uint256 => uint256) public ordinalMovedTimestamp;
mapping(uint256 => address) public ordinalVaultAddress;
// ─── Events ───────────────────────────────────────────────────────────────
event Transfer(address indexed from, address indexed to, uint256 value);
event Buy(address indexed buyer, uint256 cbbtcIn, uint256 tokensOut);
event Sell(address indexed seller, uint256 tokensIn, uint256 cbbtcOut);
event Claimed(address indexed user, uint256 cbbtcAmount);
event Recirculated(address indexed user, uint256 tokensOut);
event VaultRegistered(
address indexed vault,
bytes32 indexed assetId,
uint256 ordinalNumber,
bool hasOrdinal,
uint256 oktEmbedded,
uint256 timestamp
);
event VaultSwept(
address indexed vault,
bytes32 indexed assetId,
uint256 amountMoved,
uint256 timestamp
);
event OrdinalMoved(
uint256 indexed ordinalNumber,
address indexed vault,
bytes32 indexed assetId,
uint256 timestamp
);
// ─── Constructor ──────────────────────────────────────────────────────────
//
// The cbBTC address is the only deploy-time parameter. It MUST be an 8-decimal
// token or the 1 sat = 1 WK peg breaks silently. Verify the address before
// deploying:
// Base mainnet : 0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf
// Base Sepolia : 0xcbB7C0006F23900c38EB856149F799620fcb8A4a
//
constructor(address _cbbtc) {
require(_cbbtc != address(0), "cbBTC: zero address");
CBBTC = IERC20(_cbbtc);
vaultRegistrar = msg.sender;
ordinalOracle = msg.sender;
}
// ─── Modifiers ────────────────────────────────────────────────────────────
modifier onlyRegistrar() {
require(msg.sender == vaultRegistrar, "Not vault registrar");
_;
}
modifier onlyOracle() {
require(msg.sender == ordinalOracle, "Not ordinal oracle");
_;
}
// ─── Signed math helpers ──────────────────────────────────────────────────
function _signedAdd(int256 a, uint256 b) internal pure returns (int256) {
return a + int256(b);
}
function _signedSub(int256 a, uint256 b) internal pure returns (int256) {
return a - int256(b);
}
// ─── Distribute fee ───────────────────────────────────────────────────────
function _distributeFee(uint256 fee) internal {
if (totalSupply > 0 && fee > 0) {
recirculationPerToken += (fee * MAGNITUDE) / totalSupply;
}
}
// ─── Vault sweep check ───────────────────────────────────────────────────
function _checkVaultSweep(address vault, uint256 amount) internal {
if (isVault[vault] && !vaultHasBeenSwept[vault]) {
vaultHasBeenSwept[vault] = true;
emit VaultSwept(vault, vaultRegistry[vault], amount, block.timestamp);
}
}
// ─── Buy ──────────────────────────────────────────────────────────────────
// PITcoin exact — fee returned to first buyer, distributed to holders after
function buy(uint256 cbbtcAmount, uint256 minTokens) external nonReentrant {
require(cbbtcAmount >= MIN_SATS, "Minimum 100 sats");
require(cbbtcAmount <= MAX_BUY, "Maximum 1,000,000 sats per buy");
CBBTC.safeTransferFrom(msg.sender, address(this), cbbtcAmount);
uint256 fee = (cbbtcAmount * BUY_FEE) / 100;
uint256 tokens = cbbtcAmount - fee;
require(tokens >= minTokens, "Slippage: too few tokens");
if (totalSupply > 0) {
_distributeFee(fee);
} else {
tokens += fee; // first buyer gets fee back
}
totalSupply += tokens;
balanceOf[msg.sender] += tokens;
emit Transfer(address(0), msg.sender, tokens);
// PITcoin exact — set baseline to current recirculationPerToken * tokens
claimedOf[msg.sender] = _signedAdd(
claimedOf[msg.sender],
(tokens * recirculationPerToken) / MAGNITUDE
);
emit Buy(msg.sender, cbbtcAmount, tokens);
}
// ─── Sell — PITcoin exact ─────────────────────────────────────────────────
//
// The accounting equation that must hold at all times:
// cbbtcInContract = totalSupply + totalSupply*ppt/M - sum(claimedOf)
//
// When selling `tokens` for `taxed` cbBTC:
// - totalSupply decreases by tokens
// - cbbtcInContract decreases by taxed
// - Direct cbBTC payment handles `taxed`
// - claimedOf must decrease only by the burned-token dividend baseline:
// (tokens * recirculationPerToken) / MAGNITUDE
// - Including `taxed` in claimedOf would double-count seller proceeds
// - _distributeFee happens AFTER claimedOf update
//
// DO NOT change signedSub to signedAdd — that breaks dividend distribution
// for any wallet that sells and rebuys. PITcoin uses signedSub. Always.
//
function sell(uint256 tokens, uint256 minCbbtc) external nonReentrant {
require(tokens >= MIN_SELL, "Minimum 100 sats to sell");
require(balanceOf[msg.sender] >= tokens, "Insufficient balance");
require(totalSupply > tokens, "Cannot sell entire supply");
_checkVaultSweep(msg.sender, tokens);
uint256 fee = (tokens * SELL_FEE) / 100;
uint256 taxed = tokens - fee;
require(taxed >= minCbbtc, "Slippage: too little cbBTC");
// 1. Burn tokens
balanceOf[msg.sender] -= tokens;
totalSupply -= tokens;
emit Transfer(msg.sender, address(0), tokens);
// 2. Release ONLY the dividend baseline for burned tokens.
// DO NOT include taxed here — safeTransfer below handles payment.
// Including taxed would allow double-spend: user gets cbBTC via
// safeTransfer AND via withdraw() on the inflated dividend balance.
uint256 payout = (tokens * recirculationPerToken) / MAGNITUDE;
claimedOf[msg.sender] = _signedSub(claimedOf[msg.sender], payout);
// 3. Distribute fee AFTER claimedOf update
_distributeFee(fee);
// 4. Send cbBTC directly to seller
CBBTC.safeTransfer(msg.sender, taxed);
emit Sell(msg.sender, tokens, taxed);
}
// ─── Transfer — zero fee ──────────────────────────────────────────────────
function transfer(address to, uint256 tokens) external returns (bool) {
require(to != address(0), "Zero address");
require(tokens > 0, "Zero tokens");
require(balanceOf[msg.sender] >= tokens, "Insufficient balance");
_checkVaultSweep(msg.sender, tokens);
balanceOf[msg.sender] -= tokens;
balanceOf[to] += tokens;
emit Transfer(msg.sender, to, tokens);
uint256 payoutMove = (tokens * recirculationPerToken) / MAGNITUDE;
claimedOf[msg.sender] = _signedSub(claimedOf[msg.sender], payoutMove);
claimedOf[to] = _signedAdd(claimedOf[to], payoutMove);
return true;
}
// ─── Claim — 100% of earned recirculation, zero fee ───────────────────────
function claim() external nonReentrant {
uint256 divs = recirculationOf(msg.sender);
require(divs > 0, "No recirculation to claim");
_checkVaultSweep(msg.sender, divs);
claimedOf[msg.sender] = _signedAdd(claimedOf[msg.sender], divs);
CBBTC.safeTransfer(msg.sender, divs);
emit Claimed(msg.sender, divs);
}
// ─── Recirculate — zero fee, converts recirculation 1:1 to WK ─────────────────
function recirculate() external nonReentrant {
uint256 divs = recirculationOf(msg.sender);
require(divs >= MIN_SATS, "Minimum 100 sats to recirculate");
// Settle recirculation first
claimedOf[msg.sender] = _signedAdd(claimedOf[msg.sender], divs);
// Mint 1:1 — no fee on recirculate
uint256 tokens = divs;
totalSupply += tokens;
balanceOf[msg.sender] += tokens;
emit Transfer(address(0), msg.sender, tokens);
// Set recirculation baseline for newly minted tokens
claimedOf[msg.sender] = _signedAdd(
claimedOf[msg.sender],
(tokens * recirculationPerToken) / MAGNITUDE
);
emit Recirculated(msg.sender, tokens);
}
// ─── Inscribe ─────────────────────────────────────────────────────────────
function inscribe(
address vault,
bytes32 assetId,
uint256 cbbtcAmount,
uint256 ordinalNumber,
string calldata inscriptionId
) external onlyRegistrar nonReentrant {
require(vault != address(0), "Vault: zero address");
require(assetId != bytes32(0), "Vault: empty asset ID");
require(cbbtcAmount >= MIN_SATS, "Vault: minimum 100 sats");
require(!isVault[vault], "Vault: already registered");
CBBTC.safeTransferFrom(msg.sender, address(this), cbbtcAmount);
uint256 fee = (cbbtcAmount * INSCRIBE_FEE) / 100;
uint256 tokens = cbbtcAmount - fee;
if (totalSupply > 0) {
_distributeFee(fee);
} else {
tokens += fee;
}
// Mint directly into vault
totalSupply += tokens;
balanceOf[vault] += tokens;
emit Transfer(address(0), vault, tokens);
// Set vault recirculation baseline
claimedOf[vault] = _signedAdd(
claimedOf[vault],
(tokens * recirculationPerToken) / MAGNITUDE
);
// Register vault
vaultRegistry[vault] = assetId;
isVault[vault] = true;
vaultHasOrdinal[vault] = (ordinalNumber > 0);
if (ordinalNumber > 0) {
require(ordinalVaultAddress[ordinalNumber] == address(0), "Ordinal: already registered");
require(!ordinalHasBeenMoved[ordinalNumber], "Ordinal: already moved");
vaultOrdinal[vault] = ordinalNumber;
ordinalVaultAddress[ordinalNumber] = vault;
}
// Store inscription ID for content rendering (empty string if no ordinal)
if (bytes(inscriptionId).length > 0) {
vaultInscriptionId[vault] = inscriptionId;
}
emit VaultRegistered(
vault, assetId, ordinalNumber,
ordinalNumber > 0, tokens, block.timestamp
);
}
// ─── Report Ordinal Moved ─────────────────────────────────────────────────
// When a Bitcoin Ordinal moves, the provenance link is broken.
// This also marks the vault as swept — the art's integrity is compromised.
function reportOrdinalMoved(uint256 ordinalNumber) external onlyOracle {
require(ordinalNumber > 0, "Invalid ordinal number");
require(!ordinalHasBeenMoved[ordinalNumber], "Already reported as moved");
address vault = ordinalVaultAddress[ordinalNumber];
bytes32 assetId = vault != address(0) ? vaultRegistry[vault] : bytes32(0);
ordinalHasBeenMoved[ordinalNumber] = true;
ordinalMovedTimestamp[ordinalNumber] = block.timestamp;
// Mark vault as swept — Ordinal movement breaks provenance
if (vault != address(0) && !vaultHasBeenSwept[vault]) {
vaultHasBeenSwept[vault] = true;
emit VaultSwept(vault, assetId, 0, block.timestamp);
}
emit OrdinalMoved(ordinalNumber, vault, assetId, block.timestamp);
}
// ─── recirculationOf — PITcoin exact ─────────────────────────────────────────
function recirculationOf(address user) public view returns (uint256) {
uint256 gross = (balanceOf[user] * recirculationPerToken) / MAGNITUDE;
int256 paid = claimedOf[user];
if (paid < 0) {
return gross + uint256(-paid);
} else {
uint256 upaid = uint256(paid);
if (upaid > gross) return 0;
return gross - upaid;
}
}
// ─── View: core vault info ────────────────────────────────────────────────
function vaultStatus(address vault) external view returns (
bool registered,
bool swept,
uint256 balance,
bytes32 assetId
) {
return (
isVault[vault],
vaultHasBeenSwept[vault],
balanceOf[vault],
vaultRegistry[vault]
);
}
// ─── View: ordinal info ───────────────────────────────────────────────────
function vaultOrdinalStatus(address vault) external view returns (
uint256 ordinalNumber,
bool hasOrdinal,
bool ordinalMoved,
uint256 ordinalMovedAt,
string memory inscriptionId
) {
uint256 ordNum = vaultOrdinal[vault];
bool hasOrd = vaultHasOrdinal[vault];
return (
ordNum,
hasOrd,
hasOrd ? ordinalHasBeenMoved[ordNum] : false,
hasOrd ? ordinalMovedTimestamp[ordNum] : 0,
vaultInscriptionId[vault]
);
}
}
@openzeppelin/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
@openzeppelin/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
@openzeppelin/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 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 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @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 {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @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.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, 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 to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
@openzeppelin/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": false
},
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.