Description:
Multi-signature wallet contract requiring multiple confirmations for transaction execution.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"settings": {
"optimizer": {
"enabled": true,
"runs": 500
},
"viaIR": true,
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"remappings": []
},
"sources": {
"contracts/StelePerformanceNFT.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/Base64.sol";
import "./libraries/NFTSVG.sol";
// NFT metadata structure for performance records
struct PerformanceNFT {
uint256 challengeId;
address user;
uint32 totalUsers;
uint256 finalScore;
uint8 rank; // 1-5
uint256 returnRate; // in basis points (10000 = 100%)
ChallengeType challengeType;
uint256 challengeStartTime;
uint256 seedMoney; // Initial investment amount
}
// Challenge type definition
enum ChallengeType { OneWeek, OneMonth, ThreeMonths, SixMonths, OneYear }
contract StelePerformanceNFT is ERC721, ERC721Enumerable {
using Strings for uint256;
using NFTSVG for NFTSVG.SVGParams;
// Events
event PerformanceNFTMinted(uint256 indexed tokenId, uint256 indexed challengeId, address indexed user, uint8 rank, uint256 returnRate);
event TransferAttemptBlocked(uint256 indexed tokenId, address from, address to, string reason);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// State variables
address public owner;
address public steleContract;
// NFT storage
uint256 private _nextTokenId = 1;
mapping(uint256 => PerformanceNFT) public performanceNFTs;
mapping(address => mapping(uint256 => uint256)) public userNFTsByIndex;
mapping(address => uint256) public userNFTCount;
mapping(uint256 => mapping(address => bool)) public hasClaimedNFT; // challengeId => user => claimed
modifier onlyOwner() {
require(msg.sender == owner, "NO"); // Not Owner
_;
}
modifier onlySteleContract() {
require(msg.sender == steleContract, "NSC"); // Not Stele Contract
_;
}
constructor(address _steleContract) ERC721("Stele Performance NFT", "SPNFT") {
owner = msg.sender;
steleContract = _steleContract;
}
// Calculate return rate based on final score and initial value (basis points: 10000 = 100%)
function calculateReturnRate(uint256 finalScore, uint256 initialValue) internal pure returns (uint256) {
if (finalScore > initialValue) {
return ((finalScore - initialValue) * 10000) / initialValue;
} else {
return 0;
}
}
// Calculate profit/loss percentage with 3 decimal places (1000000 = 100.000%)
function calculateProfitLossPercentage(uint256 finalScore, uint256 seedMoney) internal pure returns (int256) {
if (seedMoney == 0) return 0;
if (finalScore >= seedMoney) {
// Profit: ((finalScore - seedMoney) / seedMoney) * 1000000
uint256 profit = finalScore - seedMoney;
uint256 profitPercentage = (profit * 1000000) / seedMoney;
return int256(profitPercentage);
} else {
// Loss: -((seedMoney - finalScore) / seedMoney) * 1000000
uint256 loss = seedMoney - finalScore;
uint256 lossPercentage = (loss * 1000000) / seedMoney;
return -int256(lossPercentage);
}
}
// Mint Performance NFT (only callable by Stele contract)
function mintPerformanceNFT(
uint256 challengeId,
address user,
uint32 totalUsers,
uint256 finalScore,
uint8 rank,
uint256 initialValue,
ChallengeType challengeType,
uint256 challengeStartTime
) external onlySteleContract returns (uint256) {
require(!hasClaimedNFT[challengeId][user], "AC"); // Already Claimed
// Calculate return rate (basis points for backward compatibility)
uint256 returnRate = calculateReturnRate(finalScore, initialValue);
// Get next token ID
uint256 tokenId = _nextTokenId;
_nextTokenId++;
// Store NFT metadata (initialValue is seedMoney from challenge)
performanceNFTs[tokenId] = PerformanceNFT({
challengeId: challengeId,
user: user,
totalUsers: totalUsers,
finalScore: finalScore,
rank: rank,
returnRate: returnRate,
challengeType: challengeType,
challengeStartTime: challengeStartTime,
seedMoney: initialValue
});
// Mark as claimed
hasClaimedNFT[challengeId][user] = true;
// Mint NFT using OpenZeppelin's _mint function
_mint(user, tokenId);
// Update custom mappings for user enumeration
userNFTsByIndex[user][userNFTCount[user]] = tokenId;
userNFTCount[user]++;
emit PerformanceNFTMinted(tokenId, challengeId, user, rank, returnRate);
return tokenId;
}
// Get NFT metadata
function getPerformanceNFTData(uint256 tokenId) external view returns (
uint256 challengeId,
address user,
uint32 totalUsers,
uint256 finalScore,
uint8 rank,
uint256 returnRate,
ChallengeType challengeType,
uint256 challengeStartTime,
uint256 seedMoney
) {
require(_ownerOf(tokenId) != address(0), "TNE"); // Token Not Exists
PerformanceNFT memory nft = performanceNFTs[tokenId];
return (
nft.challengeId,
nft.user,
nft.totalUsers,
nft.finalScore,
nft.rank,
nft.returnRate,
nft.challengeType,
nft.challengeStartTime,
nft.seedMoney
);
}
// Check if user can mint NFT for a challenge
function canMintNFT(uint256 challengeId, address user) external view returns (bool) {
return !hasClaimedNFT[challengeId][user];
}
// Get challenge period text
function getChallengePeriodText(ChallengeType challengeType) internal pure returns (string memory) {
if (challengeType == ChallengeType.OneWeek) return "1 week";
if (challengeType == ChallengeType.OneMonth) return "1 month";
if (challengeType == ChallengeType.ThreeMonths) return "3 months";
if (challengeType == ChallengeType.SixMonths) return "6 months";
if (challengeType == ChallengeType.OneYear) return "1 year";
return "unknown period";
}
// Format return rate for display
function formatReturnRate(int256 profitLossPercent) internal pure returns (string memory) {
if (profitLossPercent >= 0) {
uint256 absPercent = uint256(profitLossPercent);
uint256 wholePart = absPercent / 10000;
uint256 decimalPart = (absPercent % 10000) / 100;
string memory decimal = decimalPart < 10
? string(abi.encodePacked("0", Strings.toString(decimalPart)))
: Strings.toString(decimalPart);
return string(abi.encodePacked(
"+",
Strings.toString(wholePart),
".",
decimal,
"%"
));
} else {
uint256 absPercent = uint256(-profitLossPercent);
uint256 wholePart = absPercent / 10000;
uint256 decimalPart = (absPercent % 10000) / 100;
string memory decimal = decimalPart < 10
? string(abi.encodePacked("0", Strings.toString(decimalPart)))
: Strings.toString(decimalPart);
return string(abi.encodePacked(
"-",
Strings.toString(wholePart),
".",
decimal,
"%"
));
}
}
// Token URI with on-chain SVG image
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_ownerOf(tokenId) != address(0), "TNE");
PerformanceNFT memory nft = performanceNFTs[tokenId];
int256 profitLossPercent = calculateProfitLossPercentage(nft.finalScore, nft.seedMoney);
// Generate SVG image
NFTSVG.SVGParams memory svgParams = NFTSVG.SVGParams({
challengeId: nft.challengeId,
user: nft.user,
totalUsers: nft.totalUsers,
finalScore: nft.finalScore,
rank: nft.rank,
returnRate: nft.returnRate,
challengeType: uint256(nft.challengeType),
challengeStartTime: nft.challengeStartTime,
seedMoney: nft.seedMoney,
profitLossPercent: profitLossPercent
});
string memory svg = svgParams.generateSVG();
string memory image = string(abi.encodePacked(
"data:image/svg+xml;base64,",
Base64.encode(bytes(svg))
));
string memory returnRateText = formatReturnRate(profitLossPercent);
string memory periodText = getChallengePeriodText(nft.challengeType);
string memory json = string(abi.encodePacked(
'{"name":"Challenge #',
Strings.toString(nft.challengeId),
' Performance Certificate",',
'"description":"Rank #',
Strings.toString(nft.rank),
' in ',
periodText,
' challenge with ',
returnRateText,
' return rate",',
'"image":"',
image,
'",',
'"attributes":[',
'{"trait_type":"Challenge ID","value":',
Strings.toString(nft.challengeId),
'},',
'{"trait_type":"Rank","value":',
Strings.toString(nft.rank),
'},',
'{"trait_type":"Return Rate","value":"',
returnRateText,
'"},',
'{"trait_type":"Challenge Period","value":"',
periodText,
'"},',
'{"trait_type":"Total Participants","value":',
Strings.toString(nft.totalUsers),
'}]}'
));
return string(abi.encodePacked(
"data:application/json;base64,",
Base64.encode(bytes(json))
));
}
// ============ SOULBOUND NFT FUNCTIONS ============
// Transfer functions are blocked for soulbound functionality
function transferFrom(address from, address to, uint256 tokenId) public override(ERC721, IERC721) {
emit TransferAttemptBlocked(tokenId, from, to, "Soulbound NFT cannot be transferred");
revert("SBT");
}
function safeTransferFrom(address from, address to, uint256 tokenId) public override(ERC721, IERC721) {
emit TransferAttemptBlocked(tokenId, from, to, "Soulbound NFT cannot be transferred");
revert("SBT");
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory /* data */) public override(ERC721, IERC721) {
emit TransferAttemptBlocked(tokenId, from, to, "Soulbound NFT cannot be transferred");
revert("SBT");
}
// Approval functions are blocked since transfers are not allowed
function approve(address /* to */, uint256 /* tokenId */) public pure override(ERC721, IERC721) {
revert("SBT");
}
function setApprovalForAll(address /* operator */, bool /* approved */) public pure override(ERC721, IERC721) {
revert("SBT");
}
function getApproved(uint256 tokenId) public view override(ERC721, IERC721) returns (address) {
require(_ownerOf(tokenId) != address(0), "TNE");
return address(0); // Always return zero address for soulbound tokens
}
function isApprovedForAll(address /* tokenOwner */, address /* operator */) public pure override(ERC721, IERC721) returns (bool) {
return false; // Always return false for soulbound tokens
}
// Check if this is a soulbound token
function isSoulbound() external pure returns (bool) {
return true;
}
// Get soulbound token information
function getSoulboundInfo(uint256 tokenId) external view returns (
bool isSoulboundToken,
address boundTo,
string memory reason
) {
require(_ownerOf(tokenId) != address(0), "TNE");
return (true, ownerOf(tokenId), "Performance NFT bound to achievement owner");
}
// Verify if NFT was minted by this contract with challenge validation
function verifyNFTAuthenticity(uint256 tokenId) external view returns (
bool isAuthentic,
uint256 challengeId,
address originalMinter,
uint8 rank,
uint256 blockTimestamp
) {
if (_ownerOf(tokenId) == address(0)) {
return (false, 0, address(0), 0, 0);
}
PerformanceNFT memory nft = performanceNFTs[tokenId];
return (
true,
nft.challengeId,
nft.user,
nft.rank,
nft.challengeStartTime
);
}
// Get contract name and version for verification
function getContractInfo() external pure returns (string memory contractName, string memory version) {
return ("Stele Performance NFT", "1.0.0");
}
// Override required functions for ERC721Enumerable compatibility
function _beforeTokenTransfer(address from, address to, uint256 tokenId, uint256 batchSize)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId, batchSize);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
// Custom enumeration functions (using ERC721Enumerable for standard functions)
function tokenOfOwnerByIndex(address tokenOwner, uint256 index) public view override returns (uint256) {
require(index < userNFTCount[tokenOwner], "OOB"); // Out of bounds
return userNFTsByIndex[tokenOwner][index];
}
// ERC721 functions are inherited from OpenZeppelin
// Get user's NFT tokens with pagination
function getUserNFTs(address user, uint256 offset, uint256 limit) external view returns (uint256[] memory tokens, uint256 total) {
total = userNFTCount[user];
if (offset >= total) {
return (new uint256[](0), total);
}
uint256 end = offset + limit;
if (end > total) {
end = total;
}
uint256 length = end - offset;
tokens = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
tokens[i] = userNFTsByIndex[user][offset + i];
}
return (tokens, total);
}
// Get all user's NFT tokens (for backward compatibility, gas limit aware)
function getAllUserNFTs(address user) external view returns (uint256[] memory) {
uint256 total = userNFTCount[user];
uint256[] memory tokens = new uint256[](total);
for (uint256 i = 0; i < total; i++) {
tokens[i] = userNFTsByIndex[user][i];
}
return tokens;
}
// totalSupply is provided by ERC721Enumerable
// Check if token exists
function exists(uint256 tokenId) external view returns (bool) {
return _ownerOf(tokenId) != address(0);
}
// Transfer ownership
function transferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0), "NZ"); // Not Zero address
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
// supportsInterface is handled by the override above
}
"
},
"contracts/libraries/NFTSVG.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/Base64.sol";
library NFTSVG {
using Strings for uint256;
using Strings for address;
struct SVGParams {
uint256 challengeId;
address user;
uint32 totalUsers;
uint256 finalScore;
uint8 rank;
uint256 returnRate;
uint256 challengeType;
uint256 challengeStartTime;
uint256 seedMoney;
int256 profitLossPercent;
}
function generateSVG(SVGParams memory params) internal pure returns (string memory) {
return string(abi.encodePacked(
'<svg width="300" height="400" viewBox="0 0 300 400" xmlns="http://www.w3.org/2000/svg">',
generateDefs(),
generateCard(),
generateTitle(),
generateRankBadge(params.rank),
generateStatsGrid(params),
generateSeparator(),
generateInvestmentSummary(params),
generateFooter(),
'</svg>'
));
}
function generateDefs() internal pure returns (string memory) {
return string(abi.encodePacked(
'<defs>',
'<linearGradient id="orangeGradient" x1="0%" y1="0%" x2="100%" y2="100%">',
'<stop offset="0%" style="stop-color:#ff8c42;stop-opacity:1" />',
'<stop offset="100%" style="stop-color:#e55100;stop-opacity:1" />',
'</linearGradient>',
'<linearGradient id="cardBackground" x1="0%" y1="0%" x2="0%" y2="100%">',
'<stop offset="0%" style="stop-color:#2a2a2e;stop-opacity:1" />',
'<stop offset="100%" style="stop-color:#1f1f23;stop-opacity:1" />',
'</linearGradient>',
'<filter id="cardShadow">',
'<feDropShadow dx="0" dy="2" stdDeviation="8" flood-color="#000" flood-opacity="0.06"/>',
'</filter>',
'</defs>'
));
}
function generateCard() internal pure returns (string memory) {
return string(abi.encodePacked(
'<rect width="300" height="400" rx="12" fill="url(#cardBackground)" stroke="#404040" stroke-width="1" filter="url(#cardShadow)"/>',
'<rect x="0" y="0" width="300" height="4" rx="12" fill="url(#orangeGradient)"/>'
));
}
function generateTitle() internal pure returns (string memory) {
return string(abi.encodePacked(
'<text x="24" y="40" font-family="-apple-system, BlinkMacSystemFont, Segoe UI, sans-serif" font-size="20" font-weight="600" fill="#f9fafb">',
'Trading Performance',
'</text>',
'<text x="24" y="60" font-family="-apple-system, BlinkMacSystemFont, Segoe UI, sans-serif" font-size="14" fill="#9ca3af">',
'Stele Protocol',
'</text>'
));
}
function generateRankBadge(uint8 rank) internal pure returns (string memory) {
return string(abi.encodePacked(
'<rect x="24" y="85" width="80" height="32" rx="16" fill="url(#orangeGradient)"/>',
'<text x="64" y="103" font-family="-apple-system, BlinkMacSystemFont, Segoe UI, sans-serif" font-size="14" font-weight="600" fill="#ffffff" text-anchor="middle">',
'Rank ', uint256(rank).toString(),
'</text>'
));
}
function generateStatsGrid(SVGParams memory params) internal pure returns (string memory) {
string memory challengeText = getChallengePeriodText(params.challengeType);
string memory returnText = formatReturnRate(params.profitLossPercent);
return string(abi.encodePacked(
'<g font-family="-apple-system, BlinkMacSystemFont, Segoe UI, sans-serif">',
'<text x="24" y="140" font-size="14" font-weight="500" fill="#9ca3af">Challenge</text>',
'<text x="276" y="140" font-size="14" font-weight="600" fill="#f9fafb" text-anchor="end">#', params.challengeId.toString(), '</text>',
'<text x="24" y="165" font-size="14" font-weight="500" fill="#9ca3af">Duration</text>',
'<text x="276" y="165" font-size="14" font-weight="600" fill="#f9fafb" text-anchor="end">', challengeText, '</text>',
'<text x="24" y="190" font-size="14" font-weight="500" fill="#9ca3af">Ranking</text>',
'<text x="276" y="190" font-size="14" font-weight="600" fill="url(#orangeGradient)" text-anchor="end">', uint256(params.rank).toString(), getRankSuffix(params.rank), ' / ', uint256(params.totalUsers).toString(), '</text>',
'<text x="24" y="215" font-size="14" font-weight="500" fill="#9ca3af">Return Rate</text>',
'<text x="276" y="215" font-size="16" font-weight="700" fill="#10b981" text-anchor="end">', returnText, '</text>',
'</g>'
));
}
function generateSeparator() internal pure returns (string memory) {
return '<line x1="24" y1="245" x2="276" y2="245" stroke="#404040" stroke-width="1"/>';
}
function generateInvestmentSummary(SVGParams memory params) internal pure returns (string memory) {
if (params.finalScore >= params.seedMoney) {
return string(abi.encodePacked(
'<g font-family="-apple-system, BlinkMacSystemFont, Segoe UI, sans-serif">',
'<text x="24" y="270" font-size="14" font-weight="500" fill="#9ca3af">Initial Investment</text>',
'<text x="276" y="270" font-size="14" font-weight="600" fill="#f9fafb" text-anchor="end">$', formatAmount(params.seedMoney), '</text>',
'<text x="24" y="295" font-size="14" font-weight="500" fill="#9ca3af">Current Value</text>',
'<text x="276" y="295" font-size="14" font-weight="600" fill="#f9fafb" text-anchor="end">$', formatAmount(params.finalScore), '</text>',
'<text x="24" y="320" font-size="14" font-weight="500" fill="#9ca3af">Profit/Loss</text>',
'<text x="276" y="320" font-size="14" font-weight="600" fill="#10b981" text-anchor="end">+$', formatAmount(params.finalScore - params.seedMoney), '</text>',
'</g>'
));
} else {
return string(abi.encodePacked(
'<g font-family="-apple-system, BlinkMacSystemFont, Segoe UI, sans-serif">',
'<text x="24" y="270" font-size="14" font-weight="500" fill="#9ca3af">Initial Investment</text>',
'<text x="276" y="270" font-size="14" font-weight="600" fill="#f9fafb" text-anchor="end">$', formatAmount(params.seedMoney), '</text>',
'<text x="24" y="295" font-size="14" font-weight="500" fill="#9ca3af">Current Value</text>',
'<text x="276" y="295" font-size="14" font-weight="600" fill="#f9fafb" text-anchor="end">$', formatAmount(params.finalScore), '</text>',
'<text x="24" y="320" font-size="14" font-weight="500" fill="#9ca3af">Profit/Loss</text>',
'<text x="276" y="320" font-size="14" font-weight="600" fill="#ef4444" text-anchor="end">-$', formatAmount(params.seedMoney - params.finalScore), '</text>',
'</g>'
));
}
}
function generateFooter() internal pure returns (string memory) {
return '<text x="150" y="365" font-family="-apple-system, BlinkMacSystemFont, Segoe UI, sans-serif" font-size="12" font-weight="500" fill="#9ca3af" text-anchor="middle">Powered by Stele Protocol</text>';
}
function getChallengePeriodText(uint256 challengeType) internal pure returns (string memory) {
if (challengeType == 0) return "1 Week";
if (challengeType == 1) return "1 Month";
if (challengeType == 2) return "3 Months";
if (challengeType == 3) return "6 Months";
if (challengeType == 4) return "1 Year";
return "Unknown";
}
function formatReturnRate(int256 profitLossPercent) internal pure returns (string memory) {
if (profitLossPercent >= 0) {
uint256 absPercent = uint256(profitLossPercent);
return string(abi.encodePacked(
"+",
(absPercent / 10000).toString(),
".",
formatDecimals((absPercent % 10000) / 100),
"%"
));
} else {
uint256 absPercent = uint256(-profitLossPercent);
return string(abi.encodePacked(
"-",
(absPercent / 10000).toString(),
".",
formatDecimals((absPercent % 10000) / 100),
"%"
));
}
}
function formatAmount(uint256 amount) internal pure returns (string memory) {
// USDC has 6 decimals, so 1e6 = 1 USD
if (amount >= 1e12) { // >= 1,000,000 USD (1M)
return string(abi.encodePacked((amount / 1e12).toString(), "M"));
} else if (amount >= 1e11) { // >= 100,000 USD (100K)
return string(abi.encodePacked((amount / 1e9).toString(), "K"));
} else if (amount >= 1e6) { // >= 1 USD
return (amount / 1e6).toString();
} else {
// Less than 1 USD, show with decimals
uint256 dollars = amount / 1e6;
uint256 cents = (amount % 1e6) / 1e4; // 2 decimal places
return string(abi.encodePacked(dollars.toString(), ".", formatDecimals(cents)));
}
}
function formatDecimals(uint256 value) internal pure returns (string memory) {
if (value < 10) {
return string(abi.encodePacked("0", value.toString()));
}
return value.toString();
}
function getRankSuffix(uint8 rank) internal pure returns (string memory) {
if (rank == 1) return "st";
if (rank == 2) return "nd";
if (rank == 3) return "rd";
return "th";
}
}"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.6) (utils/Base64.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides a set of functions to operate with Base64 strings.
*
* _Available since v4.5._
*/
library Base64 {
/**
* @dev Base64 Encoding/Decoding Table
*/
string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* @dev Converts a `bytes` to its Bytes64 `string` representation.
*/
function encode(bytes memory data) internal pure returns (string memory) {
/**
* Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
* https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
*/
if (data.length == 0) return "";
// Loads the table into memory
string memory table = _TABLE;
// Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
// and split into 4 numbers of 6 bits.
// The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
// - `data.length + 2` -> Round up
// - `/ 3` -> Number of 3-bytes chunks
// - `4 *` -> 4 characters for each chunk
string memory result = new string(4 * ((data.length + 2) / 3));
/// @solidity memory-safe-assembly
assembly {
// Prepare the lookup table (skip the first "length" byte)
let tablePtr := add(table, 1)
// Prepare result pointer, jump over length
let resultPtr := add(result, 0x20)
let dataPtr := data
let endPtr := add(data, mload(data))
// In some cases, the last iteration will read bytes after the end of the data. We cache the value, and
// set it to zero to make sure no dirty bytes are read in that section.
let afterPtr := add(endPtr, 0x20)
let afterCache := mload(afterPtr)
mstore(afterPtr, 0x00)
// Run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
// Advance 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// To write each character, shift the 3 byte (24 bits) chunk
// 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
// and apply logical AND with 0x3F to bitmask the least significant 6 bits.
// Use this as an index into the lookup table, mload an entire word
// so the desired character is in the least significant byte, and
// mstore8 this least significant byte into the result and continue.
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
}
// Reset the value that was cached
mstore(afterPtr, afterCache)
// When data `bytes` is not exactly 3 bytes long
// it is padded with `=` characters at the end
switch mod(mload(data), 3)
case 1 {
mstore8(sub(resultPtr, 1), 0x3d)
mstore8(sub(resultPtr, 2), 0x3d)
}
case 2 {
mstore8(sub(resultPtr, 1), 0x3d)
}
}
return result;
}
}
"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
"
},
"@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize
) internal virtual override {
super._beforeTokenTransfer(from, to, firstTokenId, batchSize);
if (batchSize > 1) {
// Will only trigger during construction. Batch transferring (minting) is not available afterwards.
revert("ERC721Enumerable: consecutive transfers not supported");
}
uint256 tokenId = firstTokenId;
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: address zero is not a valid owner");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _ownerOf(tokenId);
require(owner != address(0), "ERC721: invalid token ID");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
_requireMinted(tokenId);
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not token owner or approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
_requireMinted(tokenId);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
_safeTransfer(from, to, tokenId, data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
*/
function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
return _owners[tokenId];
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _ownerOf(tokenId) != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId, 1);
// Check that tokenId was not minted by `_beforeTokenTransfer` hook
require(!_exists(tokenId), "ERC721: token already minted");
unchecked {
// Will not overflow unless all 2**256 token ids are minted to the same owner.
// Given that tokens are minted one by one, it is impossible in practice that
// this ever happens. Might change if we allow batch minting.
// The ERC fails to describe this case.
_balances[to] += 1;
}
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId, 1);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
* This is an internal function that does not check if the sender is authorized to operate on the token.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId, 1);
// Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
owner = ERC721.ownerOf(tokenId);
// Clear approvals
delete _tokenApprovals[tokenId];
unchecked {
// Cannot overflow, as that would require more tokens to be burned/transferred
// out than the owner initially received through minting and transferring in.
_balances[owner] -= 1;
}
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId, 1);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId, 1);
// Check that tokenId was not transferred by `_beforeTokenTransfer` hook
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
// Clear approvals from the previous owner
delete _tokenApprovals[tokenId];
unchecked {
// `_balances[from]` cannot overflow for the same reason as described in `_burn`:
// `from`'s balance is the number of token held, which is at least one before the current
// transfer.
// `_balances[to]` could overflow in the conditions described in `_mint`. That would require
// all 2**256 token ids to be minted, which in practice is impossible.
_balances[from] -= 1;
_balances[to] += 1;
}
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits an {ApprovalForAll} event.
*/
function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Reverts if the `tokenId` has not been minted yet.
*/
function _requireMinted(uint256 tokenId) internal view virtual {
require(_exists(tokenId), "ERC721: invalid token ID");
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
/// @solidity memory-safe-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
* used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
* - When `from` is zero, the tokens will be minted for `to`.
* - When `to` is zero, ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
* - `batchSize` is non-zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}
/**
* @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
* used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
* - When `from` is zero, the tokens were minted for `to`.
* - When `to` is zero, ``from``'s tokens were burned.
* - `from` and `to` are never both zero.
* - `batchSize` is non-zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}
/**
* @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
*
* WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant
* being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such
* that `ownerOf(tokenId)` is `a`.
*/
// solhint-disable-next-line func-name-mixedcase
function __unsafe_increaseBalance(address account, uint256 amount) internal {
_balances[account] += amount;
}
}
"
},
"@openzeppelin/contracts/utils/math/SignedMath.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
"
},
"@openzeppelin/contracts/utils/math/Math.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.
Submitted on: 2025-09-24 16:06:59
Comments
Log in to comment.
No comments yet.