Verified contractExactMIT
PanoramaS4MusicGateway
Address0x65748ece6147c18d8fd4f5d805cd2ba0dcc24505
- Balance
0 ETH
- Transactions
6
- Compiler
solc 0.8.34
- Same code
Only this contract
Details
- Compiler
- solc 0.8.34+commit.80d5c536
- Language
- solidity
- Optimization
- Yes, 200 runs
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,444,850
- Creation transaction
- 0xe073f07504…d89e4d9f88
7 files
- contracts/PanoramaS4MusicGateway_JS.solmain17.91 KB
- @openzeppelin/[email protected]/access/Ownable.sol3.1 KB
- @openzeppelin/[email protected]/utils/Base64.sol3.86 KB
- @openzeppelin/[email protected]/utils/Context.sol963 B
- @openzeppelin/[email protected]/utils/Strings.sol3.1 KB
- @openzeppelin/[email protected]/utils/math/Math.sol15.12 KB
- @openzeppelin/[email protected]/utils/math/SignedMath.sol1.26 KB
contracts/PanoramaS4MusicGateway_JS.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Ownable} from "@openzeppelin/[email protected]/access/Ownable.sol";
import {Strings} from "@openzeppelin/[email protected]/utils/Strings.sol";
import {Base64} from "@openzeppelin/[email protected]/utils/Base64.sol";
/// @notice ABI types mirror PanoramaS4AudioControlsV2_MoodMelody.sol EXACTLY.
/// @dev Do not reorder existing MusicData fields. These types intentionally do not
/// import the unavailable draft PanoramaTypesV2.sol.
library PanoramaS4Wire {
struct TokenData {
uint8 character;
uint8 mood;
uint8 key;
bool genFX;
bytes fxSettings;
bytes melody;
bytes levels;
bytes32[3] seeds;
uint32 melodyLoopMs;
}
struct CharacterData {
uint8[6] bits;
uint8[6] sampleRoots;
uint8[2] polyOsc;
int16 detuneCents;
}
struct BassSound {
uint8 bit;
uint8 sampleRoot;
uint8[2] oscillators;
int16 detuneCents;
}
struct MusicData {
TokenData token;
CharacterData character;
uint16 bpm;
uint16 chordLoopTicks;
uint16[3] drumBars;
uint8[][] chords;
bytes[3] chordParts;
bytes[3] drumParts;
bytes fxSettings;
bytes bassPart;
uint16 bassLoopTicks;
BassSound bassSound;
}
}
interface IPanoramaS4CoreRead {
function tokenToMusic(uint256 id) external view returns (PanoramaS4Wire.MusicData memory);
function tokenToArrangement(uint256 id) external view returns (bytes memory);
function tokenToMelodySound(uint256 id) external view returns (bytes25);
function tokenData(uint256 id) external view returns (PanoramaS4Wire.TokenData memory);
function tokenToBassSound(uint256 id) external view returns (PanoramaS4Wire.BassSound memory);
}
interface IPanoramaS4StorageRead {
function leadOf(uint256 tokenId) external view returns (uint8);
function moodOf(uint256 tokenId) external view returns (uint8);
}
/// @notice An already-uploaded, preferably sealed Panorama S4 JS renderer.
/// @dev Pass the GATEWAY address as controller so onchain reads honor frozen snapshots.
interface IPanoramaS4ScriptRenderer {
function tokenToJS(address controller, uint256 tokenId) external view returns (string memory);
}
/// @notice EthFS FileStore: readFile(string) yields the stored byte sequence.
/// @dev For `Tone.js.gz` that sequence is gzip-compressed, NOT runnable JavaScript.
/// EthFS returns it in a Solidity string, whose bytes may be binary; do not
/// concatenate this directly into an executable JS source string.
interface IEthFSFileStore {
function readFile(string calldata filename) external view returns (string memory);
}
/// @notice Mainnet read gateway compatible with Yigit's IPanoramaSeason4Music interface.
/// @dev Put THIS address into PanoramaSeason4Storage.musicController().
/// For unfrozen tokens, reads the existing controller and checks canonical
/// lead/mood; for frozen tokens, returns identical ABI from an immutable
/// onchain snapshot. Core token selection must already match Panorama.
/// The gateway does NOT change old controller writes or mutate the music.
contract PanoramaS4MusicGateway is Ownable {
using Strings for uint256;
using PanoramaS4Wire for PanoramaS4Wire.TokenData;
IPanoramaS4CoreRead public immutable core;
IPanoramaS4StorageRead public immutable panorama;
mapping(address => bool) public publishers;
mapping(uint256 => bool) public frozen;
mapping(uint256 => bytes) private _musicSnapshots; // ABI encoded MusicData, very expensive to store; immutable thereafter
mapping(uint256 => bytes) private _arrangementSnapshots;
mapping(uint256 => bytes25) private _melodySnapshots;
// Optional onchain JS endpoints. These are completely independent of MusicData.
// For subsequent releases, use a freshly deployed, sealed renderer.
IPanoramaS4ScriptRenderer public scriptRenderer;
IEthFSFileStore public toneFileStore;
string public toneFilename = "Tone.js.gz";
mapping(uint256 => address) private _rendererAtFreeze;
mapping(uint256 => address) private _toneStoreAtFreeze;
mapping(uint256 => string) private _toneFilenameAtFreeze;
// We intentionally require a confirmed mood index mapping; older saved
// generation profile IDs may not align with Panorama's canonical mood order.
uint8[7] public moodToProfile;
bool public mappingConfigured;
struct TraitCache {
uint8 key;
uint16 bpm;
}
mapping(uint256 => TraitCache) private _frozenTraits;
error InvalidToken();
error InvalidMoodMap();
error WrongCharacter(uint8 actual, uint8 required);
error WrongMood(uint8 actual, uint8 required);
error NotPublisher();
error AlreadyFrozen();
error NoMoodMap();
error ScriptRendererNotConfigured();
error ToneLibraryNotConfigured();
error EmptyToneLibrary();
event PublisherUpdated(address indexed publisher, bool enabled);
event MoodMappingUpdated(uint8[7] mappingValues);
event TokenFrozen(uint256 indexed id, bytes32 musicHash, uint256 musicBytes);
event ScriptRendererSet(address indexed renderer);
event ToneLibrarySet(address indexed fileStore, string filename);
constructor(address owner_, address source_, address panorama_) Ownable(owner_) {
if (source_.code.length == 0 || panorama_.code.length == 0) revert InvalidToken();
core = IPanoramaS4CoreRead(source_);
panorama = IPanoramaS4StorageRead(panorama_);
}
modifier onlyPublisher() {
if (msg.sender != owner() && !publishers[msg.sender]) revert NotPublisher();
_;
}
function setPublisher(address account, bool enabled) external onlyOwner {
if (account == address(0)) revert InvalidToken();
publishers[account] = enabled;
emit PublisherUpdated(account, enabled);
}
/// @notice Set a complete JS renderer. Use a sealed renderer for production.
/// @dev Does not copy the JS into gateway bytecode or storage.
function setScriptRenderer(address renderer_) external onlyOwner {
if (renderer_.code.length == 0) revert ScriptRendererNotConfigured();
scriptRenderer = IPanoramaS4ScriptRenderer(renderer_);
emit ScriptRendererSet(renderer_);
}
/// @notice Configure the EthFS contract and its exact case-sensitive gzip filename.
/// @dev The deployed file name is `Tone.js.gz`. This call does NOT load the file.
/// The supplied FileStore must implement readFile(string) returns (string).
function setToneLibrary(address fileStore_, string calldata filename_) external onlyOwner {
if (fileStore_.code.length == 0 || bytes(filename_).length == 0)
revert ToneLibraryNotConfigured();
toneFileStore = IEthFSFileStore(fileStore_);
toneFilename = filename_;
emit ToneLibrarySet(fileStore_, filename_);
}
/// @notice Returns the renderer pinned when the day was frozen, or the current renderer.
function scriptRendererFor(uint256 tokenId) public view returns (address) {
address pinned = _rendererAtFreeze[tokenId];
return frozen[tokenId] && pinned != address(0) ? pinned : address(scriptRenderer);
}
function _playerJS(uint256 tokenId) internal view returns (string memory) {
// Frozen days read their snapshot and do not need current upstream status.
// Unfrozen days must be configured, revealed and canonically mapped.
if (!frozen[tokenId]) {
PanoramaS4Wire.TokenData memory token = core.tokenData(tokenId);
_check(tokenId, token.character, token.mood);
}
address renderer = scriptRendererFor(tokenId);
if (renderer == address(0)) revert ScriptRendererNotConfigured();
// The gateway address is intentionally passed, NOT the underlying core:
// the JS then fetches tokenToMusic/Arrangement/MelodySound from this gateway.
return IPanoramaS4ScriptRenderer(renderer).tokenToJS(address(this), tokenId);
}
/// @notice One call to fetch the raw, self-contained Panorama S4 player JS.
/// @dev Returns JavaScript source (no script tags, no HTML, no data URI).
function tokenToJSNoTone(uint256 tokenId) external view returns (string memory) {
return _playerJS(tokenId);
}
/// @notice Single eth_call returning runnable JS that loads EthFS `Tone.js.gz`
/// first, then evaluates our embedded player from the sealed renderer.
/// @dev The result is a JS BOOTSTRAP, not the uncompressed library inline.
/// Solidity does not decompress gzip. The browser uses DecompressionStream
/// and injects Tone.js as a classic script (important for Tone's UMD build).
/// The host must `await globalThis.PanoramaS4BundleReady` before using
/// `globalThis.PanoramaS4.create()`. No network fetches after eth_call.
/// This may be a large eth_call (memory, return-data and RPC gas limits).
function tokenToJS(uint256 tokenId) external view returns (string memory) {
string memory playerSource = _playerJS(tokenId);
address store = address(toneFileStore);
string memory filename = toneFilename;
if (frozen[tokenId] && _toneStoreAtFreeze[tokenId] != address(0)) {
store = _toneStoreAtFreeze[tokenId];
filename = _toneFilenameAtFreeze[tokenId];
}
if (store == address(0) || bytes(filename).length == 0)
revert ToneLibraryNotConfigured();
// gzip may contain invalid UTF-8, so turn the original bytes into a
// strictly ASCII JS literal before constructing the script. EthFS may
// also hold base64 text of gzip; the bootstrap handles both variants.
bytes memory rawGzip = bytes(IEthFSFileStore(store).readFile(filename));
if (rawGzip.length == 0) revert EmptyToneLibrary();
string memory gzipBase64 = Base64.encode(rawGzip);
string memory prefix = "(()=>{\nconst packed=\"";
string memory between = "\";\nconst b64Bytes=s=>Uint8Array.from(atob(s),c=>c.charCodeAt(0));\nasync function installTone(){\n let gz=b64Bytes(packed);\n if(!(gz[0]===31&&gz[1]===139)){\n let b64=new TextDecoder().decode(gz).trim();\n if(b64.includes(',')&&b64.startsWith('data:'))b64=b64.slice(b64.indexOf(',')+1);\n gz=b64Bytes(b64.replace(/\\s+/g,''));\n }\n if(gz[0]!==31||gz[1]!==139)throw Error('EthFS Tone.js.gz: not gzip');\n if(typeof DecompressionStream==='undefined')throw Error('Browser does not support DecompressionStream(gzip)');\n const stream=new Blob([gz]).stream().pipeThrough(new DecompressionStream('gzip'));\n const source=await new Response(stream).text();\n if(!source)throw Error('Empty decompressed Tone.js');\n if(typeof document==='undefined')throw Error('Tone.js needs a document to install as a classic script');\n await new Promise((resolve,reject)=>{\n const tag=document.createElement('script');\n const url=URL.createObjectURL(new Blob([source],{type:'text/javascript'}));\n tag.src=url;\n tag.onload=()=>{URL.revokeObjectURL(url);resolve();};\n tag.onerror=()=>{URL.revokeObjectURL(url);reject(Error('Tone.js blob script blocked or failed'));};\n (document.head||document.documentElement).appendChild(tag);\n });\n if(!globalThis.Tone)throw Error('Tone.js did not expose globalThis.Tone');\n}\nasync function boot(){\nawait installTone();\n;\n";
string memory suffix = "\n;\nreturn globalThis.PanoramaS4;\n}\nglobalThis.PanoramaS4BundleReady=boot();\n})();\n";
return string.concat(prefix, gzipBase64, between, playerSource, suffix);
}
/// @notice A permutation mapping Panorama mood ID => actual MoodData contract profile ID.
/// @dev E.g. do NOT assume reverse order without checking deployed profiles.
function setMoodMapping(uint8[7] calldata order) external onlyOwner {
uint8 seen;
for (uint256 i; i < 7; ++i) {
uint8 x = order[i];
if (x >= 7 || (seen & (uint8(1) << x)) != 0) revert InvalidMoodMap();
seen |= uint8(1) << x;
}
moodToProfile = order;
mappingConfigured = true;
emit MoodMappingUpdated(order);
}
function _check(uint256 id, uint8 character, uint8 mood) internal view {
if (id < 211 || id > 270) revert InvalidToken();
if (!mappingConfigured) revert NoMoodMap();
uint8 lead = panorama.leadOf(id);
uint8 selected = panorama.moodOf(id); // reverts until revealed
if (selected >= 7 || lead > 6) revert InvalidToken();
if (mood != moodToProfile[selected]) revert WrongMood(mood, moodToProfile[selected]);
// Panorama #270 represents ALL_LEADS. The artist must deliberately
// select its audio palette; the gateway doesn't claim to synthesize six.
if (lead != 6 && character != lead) revert WrongCharacter(character, lead);
}
function tokenToMusic(uint256 id) external view returns (PanoramaS4Wire.MusicData memory) {
if (frozen[id]) return abi.decode(_musicSnapshots[id], (PanoramaS4Wire.MusicData));
PanoramaS4Wire.MusicData memory m = core.tokenToMusic(id); // reverts if not configured
_check(id, m.token.character, m.token.mood);
return m;
}
function tokenToArrangement(uint256 id) external view returns (bytes memory) {
if (frozen[id]) return _arrangementSnapshots[id];
PanoramaS4Wire.TokenData memory token = core.tokenData(id);
_check(id, token.character, token.mood);
return core.tokenToArrangement(id);
}
function tokenToMelodySound(uint256 id) external view returns (bytes25) {
if (frozen[id]) return _melodySnapshots[id];
PanoramaS4Wire.TokenData memory token = core.tokenData(id);
_check(id, token.character, token.mood);
return core.tokenToMelodySound(id);
}
/// @notice One-shot onchain snapshot. Later mood/character/dependency edits
/// cannot affect these three getter outputs for this token.
/// @dev May consume significant gas; measure on actual token before launching.
function freezeToken(uint256 id) external onlyPublisher {
if (frozen[id]) revert AlreadyFrozen();
PanoramaS4Wire.MusicData memory m = core.tokenToMusic(id);
_check(id, m.token.character, m.token.mood);
bytes memory arr = core.tokenToArrangement(id);
bytes25 melody = core.tokenToMelodySound(id);
bytes memory encoded = abi.encode(m);
_musicSnapshots[id] = encoded;
_arrangementSnapshots[id] = arr;
_melodySnapshots[id] = melody;
// Capture this day's player version if a renderer is configured already.
// An unset renderer cannot be pinned retroactively.
_rendererAtFreeze[id] = address(scriptRenderer);
if (address(toneFileStore) != address(0) && bytes(toneFilename).length != 0) {
_toneStoreAtFreeze[id] = address(toneFileStore);
_toneFilenameAtFreeze[id] = toneFilename;
}
_frozenTraits[id] = TraitCache({key:m.token.key, bpm:m.bpm});
frozen[id] = true;
emit TokenFrozen(id, keccak256(encoded), encoded.length);
}
/// @notice Optional small read for monitoring and audit; no need to recompute MusicData.
function frozenHash(uint256 id) external view returns (bytes32) {
return frozen[id] ? keccak256(_musicSnapshots[id]) : bytes32(0);
}
/// @notice Return only Key and Tempo for Panorama's NFT metadata.
/// @dev Return empty arrays if a token is unconfigured, unrevealed, or its
/// canonical lead/mood is invalid. Frozen tokens read the stored values.
/// Live tempo requires tokenToMusic() and may be expensive for RPCs
/// or metadata renderers with a tight eth_call gas cap.
function musicTraits(uint256 id) external view returns (string[] memory names, string[] memory values) {
TraitCache memory info;
if (frozen[id]) {
info = _frozenTraits[id];
} else {
if (id < 211 || id > 270 || !mappingConfigured) {
return (new string[](0), new string[](0));
}
try core.tokenToMusic(id) returns (PanoramaS4Wire.MusicData memory m) {
try panorama.leadOf(id) returns (uint8 lead) {
if (lead != 6 && m.token.character != lead) {
return (new string[](0), new string[](0));
}
} catch {
return (new string[](0), new string[](0));
}
try panorama.moodOf(id) returns (uint8 mood) {
if (mood >= 7 || m.token.mood != moodToProfile[mood]) {
return (new string[](0), new string[](0));
}
} catch {
return (new string[](0), new string[](0));
}
info = TraitCache({key:m.token.key, bpm:m.bpm});
} catch {
return (new string[](0), new string[](0));
}
}
names = new string[](2);
values = new string[](2);
names[0] = "Key";
values[0] = _key(info.key);
names[1] = "Tempo";
values[1] = string.concat(uint256(info.bpm).toString(), " BPM");
}
function _key(uint8 k) private pure returns (string memory) {
if (k == 0) return "C"; if (k == 1) return "C#";
if (k == 2) return "D"; if (k == 3) return "D#";
if (k == 4) return "E"; if (k == 5) return "F";
if (k == 6) return "F#"; if (k == 7) return "G";
if (k == 8) return "G#"; if (k == 9) return "A";
if (k == 10) return "A#"; if (k == 11) return "B";
return "Unknown";
}
}
@openzeppelin/[email protected]/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
@openzeppelin/[email protected]/utils/Base64.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.2) (utils/Base64.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides a set of functions to operate with Base64 strings.
*/
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/[email protected]/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
@openzeppelin/[email protected]/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @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), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(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) {
uint256 localValue = value;
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] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
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 bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}
@openzeppelin/[email protected]/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @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 towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (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 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
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.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 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.
uint256 twos = denominator & (0 - denominator);
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 (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
@openzeppelin/[email protected]/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @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);
}
}
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": true
},
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.