Verified contractPartialBUSL-1.1
FactoryNative
Address0x4799cdcb8d9635aebfeccd691ce2fc0553bada55
- Balance
0 ETH
- Transactions
3
- Compiler
solc 0.8.38
- Same code
Only this contract
Details
- Compiler
- solc 0.8.38+commit.1835d247
- Language
- solidity
- Optimization
- Yes, 30 runs
- EVM version
- shanghai
- License
- BUSL-1.1
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,483,513
- Creation transaction
- 0x9fd13d6dbc…0e38a6f02f
42 files
- src/FactoryNative.solmain10.54 KB
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3.1 KB
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol6.54 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol10.8 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol4.77 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.18 KB
- lib/prb-math/src/Common.sol25.82 KB
- lib/prb-math/src/UD60x18.sol2.15 KB
- lib/prb-math/src/sd1x18/Casting.sol2.32 KB
- lib/prb-math/src/sd1x18/Constants.sol758 B
- lib/prb-math/src/sd1x18/Errors.sol786 B
- lib/prb-math/src/sd1x18/ValueType.sol855 B
- lib/prb-math/src/sd21x18/Casting.sol2.35 KB
- lib/prb-math/src/sd21x18/Constants.sol823 B
- lib/prb-math/src/sd21x18/Errors.sol802 B
- lib/prb-math/src/sd21x18/ValueType.sol863 B
- lib/prb-math/src/sd59x18/Casting.sol4.94 KB
- lib/prb-math/src/sd59x18/Constants.sol2.78 KB
- lib/prb-math/src/sd59x18/Errors.sol4.46 KB
- lib/prb-math/src/sd59x18/Helpers.sol4.12 KB
- lib/prb-math/src/sd59x18/Math.sol27.63 KB
- lib/prb-math/src/sd59x18/ValueType.sol2.66 KB
- lib/prb-math/src/ud21x18/Casting.sol1.91 KB
- lib/prb-math/src/ud21x18/Constants.sol633 B
- lib/prb-math/src/ud21x18/Errors.sol241 B
- lib/prb-math/src/ud21x18/ValueType.sol868 B
- lib/prb-math/src/ud2x18/Casting.sol1.9 KB
- lib/prb-math/src/ud2x18/Constants.sol596 B
- lib/prb-math/src/ud2x18/Errors.sol237 B
- lib/prb-math/src/ud2x18/ValueType.sol861 B
- lib/prb-math/src/ud60x18/Casting.sol3.95 KB
- lib/prb-math/src/ud60x18/Constants.sol1.93 KB
- lib/prb-math/src/ud60x18/Conversions.sol1.02 KB
- lib/prb-math/src/ud60x18/Errors.sol2.03 KB
- lib/prb-math/src/ud60x18/Helpers.sol3.79 KB
- lib/prb-math/src/ud60x18/Math.sol22.82 KB
- lib/prb-math/src/ud60x18/ValueType.sol2.84 KB
- src/PHSolver.sol9.51 KB
- src/PUNZI.sol77.9 KB
src/FactoryNative.sol
// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Charu Punjani. Licensed under the Business Source License 1.1.
// PUNZI(TM) and PUNZI WARS(TM) are trademarks of Charu Punjani.
// See LICENSE for full terms.
pragma solidity 0.8.38;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {PUNZI} from "./PUNZI.sol";
import {IPHSolver, PHSolver} from "./PHSolver.sol";
/**
* @title PUNZI FactoryNative
* @notice Deploys native-collateral PUNZI tokens with CREATE2 and keeps a registry of them.
* @dev The factory stores only the hash of the PUNZI creation code. `deployPUNZI` receives the
* creation code as calldata and deploys it only if it matches that hash.
* `renounceOwnership()` reverts while any deployed token still has an owner, and
* `renounceAllInstances()` renounces them. With no owner, the factory deploys nothing
* further. The whitepaper is published at the domains returned by `canonicalDomains()`.
*/
contract FactoryNative is Ownable {
// Custom errors
/// @notice Thrown when the solver address is zero.
error PhSolverZero();
/// @notice Thrown when the solver address has no code.
error PhSolverNotContract();
/// @notice Thrown when a solver check call returns an unexpected value.
error PhSolverProbeFailed();
/// @notice Thrown when the solver's runtime code is not PHSolver's.
error PhSolverCodeMismatch();
/// @notice Thrown when the salt has already been used.
error SaltAlreadyUsed();
/// @notice Thrown when the CREATE2 deployment fails.
error Create2DeploymentFailed();
/// @notice Thrown when the supplied creation code does not match `punziCreationCodeHash`.
error CreationCodeMismatch();
/// @notice Thrown by `renounceOwnership()` while any deployed token still has an owner.
error InstancesNotRenounced();
/// @notice Thrown by `transferOwnership()`: factory ownership can only be renounced.
error TransferOwnershipDisabled();
// Events
/// @notice Emitted when a token is deployed.
event PUNZIDeployed(
address indexed instance,
string symbol,
PUNZI.SupplyCurve supplyCurve,
PUNZI.SupportCurve supportCurve
);
/// @notice Emitted by `renounceAllInstances()`.
/// @param instanceCount Number of tokens renounced by this call.
event AllInstancesRenounced(uint256 instanceCount);
// State
/// @notice All deployed native-collateral PUNZI instance addresses.
address[] public instances;
/// @notice Salts already used by `deployPUNZI`; each salt can deploy only once.
mapping(bytes32 => bool) public saltUsed;
/// @notice keccak256 of the PUNZI creation code this factory deploys, set by the constructor.
bytes32 public immutable punziCreationCodeHash;
/// @notice The solver every token from this factory uses, set once by the constructor.
IPHSolver public immutable phSolver;
// Constructor
/**
* @notice Sets the owner, checks the solver and stores it.
* @param _initialOwner The account that will own this factory.
* @param _phSolver The PHSolver deployment on this chain.
*/
constructor(address _initialOwner, IPHSolver _phSolver) Ownable(_initialOwner) {
if (address(_phSolver) == address(0)) revert PhSolverZero();
if (address(_phSolver).code.length == 0) revert PhSolverNotContract();
if (_phSolver.HEAL_DURATION() == 0) revert PhSolverProbeFailed();
if (keccak256(bytes(_phSolver.canonicalDomains())) != keccak256(bytes(canonicalDomains()))) {
revert PhSolverProbeFailed();
}
if (address(_phSolver).codehash != keccak256(type(PHSolver).runtimeCode)) revert PhSolverCodeMismatch();
punziCreationCodeHash = keccak256(type(PUNZI).creationCode);
phSolver = _phSolver;
}
// Deploy functions
/**
* @notice Deploy a native-collateral PUNZI token with CREATE2.
* @param salt The CREATE2 salt; each salt can be used once.
* @param creationCode The PUNZI creation code; must match punziCreationCodeHash.
* @param name Token name.
* @param symbol Token symbol (e.g., "PUNZI-ETH").
* @param supplyCurve Supply curve type.
* @param supportCurve Support curve type.
* @param minPurchase Minimum native amount per buy.
* @param collateralDecimals Decimals of the native currency (must be 18).
* @param curveParams The three curve parameters.
* @param maturityScale Maturity denominator for this token.
* @return instance The deployed token address.
*/
function deployPUNZI(
bytes32 salt,
bytes calldata creationCode,
string memory name,
string memory symbol,
PUNZI.SupplyCurve supplyCurve,
PUNZI.SupportCurve supportCurve,
address payable[2] memory feeRecipients,
uint256 minPurchase,
uint8 collateralDecimals,
uint256[3] memory curveParams,
uint256 maturityScale
) external onlyOwner returns (address instance) {
if (saltUsed[salt]) revert SaltAlreadyUsed();
saltUsed[salt] = true;
if (keccak256(creationCode) != punziCreationCodeHash) revert CreationCodeMismatch();
bytes memory bytecode = abi.encodePacked(
creationCode,
_encodeCtorArgs(name, symbol, supplyCurve, supportCurve, feeRecipients, minPurchase, collateralDecimals, curveParams, maturityScale)
);
instance = _deploy(bytecode, salt);
instances.push(instance);
emit PUNZIDeployed(instance, symbol, supplyCurve, supportCurve);
}
// Ownership management
/**
* @notice Renounce ownership of every deployed token. Irreversible.
* @dev Skips tokens that are already ownerless. If any renounce fails, the whole call
* reverts. Must run before `renounceOwnership()`.
*/
function renounceAllInstances() external onlyOwner {
uint256 len = instances.length;
uint256 renounced;
for (uint256 i = 0; i < len; i++) {
if (Ownable(instances[i]).owner() != address(0)) {
Ownable(instances[i]).renounceOwnership();
renounced++;
}
}
emit AllInstancesRenounced(renounced);
}
/**
* @notice Renounce ownership of this factory. Reverts while any deployed token still has
* an owner, so `renounceAllInstances()` must run first.
*/
function renounceOwnership() public override onlyOwner {
uint256 len = instances.length;
for (uint256 i = 0; i < len; i++) {
if (Ownable(instances[i]).owner() != address(0)) {
revert InstancesNotRenounced();
}
}
super.renounceOwnership();
}
/**
* @notice Disabled: factory ownership can only be renounced, never transferred.
*/
function transferOwnership(address) public pure override {
revert TransferOwnershipDisabled();
}
// View functions
/**
* @notice The CREATE2 address for these arguments, which `deployPUNZI` uses when the salt
* has not been used.
* @param salt The CREATE2 salt.
* @param creationCode The PUNZI creation code; must match punziCreationCodeHash.
* @param name Token name.
* @param symbol Token symbol.
* @param supplyCurve Supply curve type.
* @param supportCurve Support curve type.
* @param minPurchase Minimum native amount per buy.
* @param collateralDecimals Decimals of the native currency (must be 18).
* @param curveParams The three curve parameters.
* @param maturityScale Maturity denominator for this token.
* @return The predicted address.
*/
function computeAddressPUNZI(
bytes32 salt,
bytes calldata creationCode,
string memory name,
string memory symbol,
PUNZI.SupplyCurve supplyCurve,
PUNZI.SupportCurve supportCurve,
address payable[2] memory feeRecipients,
uint256 minPurchase,
uint8 collateralDecimals,
uint256[3] memory curveParams,
uint256 maturityScale
) external view returns (address) {
if (keccak256(creationCode) != punziCreationCodeHash) revert CreationCodeMismatch();
bytes memory bytecode = abi.encodePacked(
creationCode,
_encodeCtorArgs(name, symbol, supplyCurve, supportCurve, feeRecipients, minPurchase, collateralDecimals, curveParams, maturityScale)
);
return _computeAddress(bytecode, salt);
}
/// @notice Total number of deployed native instances.
function instanceCount() external view returns (uint256) {
return instances.length;
}
/// @notice Get all deployed native instance addresses.
function allInstances() external view returns (address[] memory) {
return instances;
}
// Canonical domains
/// @notice The dApp's canonical domains and ENS name, comma-separated.
/// @dev The same value on every PUNZI contract.
function canonicalDomains() public pure returns (string memory) {
return "punzi.xyz,punziwars.com,punzi.eth";
}
// Internal
/// @dev ABI-encodes the PUNZI constructor arguments, including this factory's solver.
function _encodeCtorArgs(
string memory name,
string memory symbol,
PUNZI.SupplyCurve supplyCurve,
PUNZI.SupportCurve supportCurve,
address payable[2] memory feeRecipients,
uint256 minPurchase,
uint8 collateralDecimals,
uint256[3] memory curveParams,
uint256 maturityScale
) private view returns (bytes memory) {
return abi.encode(
name, symbol, supplyCurve, supportCurve, feeRecipients,
minPurchase, collateralDecimals, curveParams, maturityScale, phSolver
);
}
function _deploy(bytes memory bytecode, bytes32 salt) internal returns (address addr) {
assembly {
addr := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
}
if (addr == address(0)) revert Create2DeploymentFailed();
}
function _computeAddress(bytes memory bytecode, bytes32 salt) internal view returns (address) {
bytes32 hash = keccak256(
abi.encodePacked(bytes1(0xff), address(this), salt, keccak256(bytecode))
);
return address(uint160(uint256(hash)));
}
}
lib/openzeppelin-contracts/contracts/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);
}
}
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/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;
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
lib/prb-math/src/Common.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
// Common.sol
//
// Common mathematical functions used in both SD59x18 and UD60x18. Note that these global functions do not
// always operate with SD59x18 and UD60x18 numbers.
/*//////////////////////////////////////////////////////////////////////////
CUSTOM ERRORS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when the resultant value in {mulDiv} overflows uint256.
error PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator);
/// @notice Thrown when the resultant value in {mulDiv18} overflows uint256.
error PRBMath_MulDiv18_Overflow(uint256 x, uint256 y);
/// @notice Thrown when one of the inputs passed to {mulDivSigned} is `type(int256).min`.
error PRBMath_MulDivSigned_InputTooSmall();
/// @notice Thrown when the resultant value in {mulDivSigned} overflows int256.
error PRBMath_MulDivSigned_Overflow(int256 x, int256 y);
/*//////////////////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////////////////*/
/// @dev The maximum value a uint128 number can have.
uint128 constant MAX_UINT128 = type(uint128).max;
/// @dev The maximum value a uint40 number can have.
uint40 constant MAX_UINT40 = type(uint40).max;
/// @dev The maximum value a uint64 number can have.
uint64 constant MAX_UINT64 = type(uint64).max;
/// @dev The unit number, which is the decimal precision of the fixed-point types.
uint256 constant UNIT = 1e18;
/// @dev The unit number inverted mod 2^256.
uint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281;
/// @dev The largest power of two that divides the decimal value of `UNIT`. The logarithm of this value is the least significant
/// bit in the binary representation of `UNIT`.
uint256 constant UNIT_LPOTD = 262144;
/*//////////////////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Calculates the binary exponent of x using the binary fraction method.
/// @dev Has to use 192.64-bit fixed-point numbers. See https://ethereum.stackexchange.com/a/96594/24693.
/// @param x The exponent as an unsigned 192.64-bit fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function exp2(uint256 x) pure returns (uint256 result) {
unchecked {
// Start from 0.5 in the 192.64-bit fixed-point format.
result = 0x800000000000000000000000000000000000000000000000;
// The following logic multiplies the result by $\sqrt{2^{-i}}$ when the bit at position i is 1. Key points:
//
// 1. Intermediate results will not overflow, as the starting point is 2^191 and all magic factors are under 2^65.
// 2. The rationale for organizing the if statements into groups of 8 is gas savings. If the result of performing
// a bitwise AND operation between x and any value in the array [0x80; 0x40; 0x20; 0x10; 0x08; 0x04; 0x02; 0x01] is 1,
// we know that `x & 0xFF` is also 1.
if (x & 0xFF00000000000000 > 0) {
if (x & 0x8000000000000000 > 0) {
result = (result * 0x16A09E667F3BCC909) >> 64;
}
if (x & 0x4000000000000000 > 0) {
result = (result * 0x1306FE0A31B7152DF) >> 64;
}
if (x & 0x2000000000000000 > 0) {
result = (result * 0x1172B83C7D517ADCE) >> 64;
}
if (x & 0x1000000000000000 > 0) {
result = (result * 0x10B5586CF9890F62A) >> 64;
}
if (x & 0x800000000000000 > 0) {
result = (result * 0x1059B0D31585743AE) >> 64;
}
if (x & 0x400000000000000 > 0) {
result = (result * 0x102C9A3E778060EE7) >> 64;
}
if (x & 0x200000000000000 > 0) {
result = (result * 0x10163DA9FB33356D8) >> 64;
}
if (x & 0x100000000000000 > 0) {
result = (result * 0x100B1AFA5ABCBED61) >> 64;
}
}
if (x & 0xFF000000000000 > 0) {
if (x & 0x80000000000000 > 0) {
result = (result * 0x10058C86DA1C09EA2) >> 64;
}
if (x & 0x40000000000000 > 0) {
result = (result * 0x1002C605E2E8CEC50) >> 64;
}
if (x & 0x20000000000000 > 0) {
result = (result * 0x100162F3904051FA1) >> 64;
}
if (x & 0x10000000000000 > 0) {
result = (result * 0x1000B175EFFDC76BA) >> 64;
}
if (x & 0x8000000000000 > 0) {
result = (result * 0x100058BA01FB9F96D) >> 64;
}
if (x & 0x4000000000000 > 0) {
result = (result * 0x10002C5CC37DA9492) >> 64;
}
if (x & 0x2000000000000 > 0) {
result = (result * 0x1000162E525EE0547) >> 64;
}
if (x & 0x1000000000000 > 0) {
result = (result * 0x10000B17255775C04) >> 64;
}
}
if (x & 0xFF0000000000 > 0) {
if (x & 0x800000000000 > 0) {
result = (result * 0x1000058B91B5BC9AE) >> 64;
}
if (x & 0x400000000000 > 0) {
result = (result * 0x100002C5C89D5EC6D) >> 64;
}
if (x & 0x200000000000 > 0) {
result = (result * 0x10000162E43F4F831) >> 64;
}
if (x & 0x100000000000 > 0) {
result = (result * 0x100000B1721BCFC9A) >> 64;
}
if (x & 0x80000000000 > 0) {
result = (result * 0x10000058B90CF1E6E) >> 64;
}
if (x & 0x40000000000 > 0) {
result = (result * 0x1000002C5C863B73F) >> 64;
}
if (x & 0x20000000000 > 0) {
result = (result * 0x100000162E430E5A2) >> 64;
}
if (x & 0x10000000000 > 0) {
result = (result * 0x1000000B172183551) >> 64;
}
}
if (x & 0xFF00000000 > 0) {
if (x & 0x8000000000 > 0) {
result = (result * 0x100000058B90C0B49) >> 64;
}
if (x & 0x4000000000 > 0) {
result = (result * 0x10000002C5C8601CC) >> 64;
}
if (x & 0x2000000000 > 0) {
result = (result * 0x1000000162E42FFF0) >> 64;
}
if (x & 0x1000000000 > 0) {
result = (result * 0x10000000B17217FBB) >> 64;
}
if (x & 0x800000000 > 0) {
result = (result * 0x1000000058B90BFCE) >> 64;
}
if (x & 0x400000000 > 0) {
result = (result * 0x100000002C5C85FE3) >> 64;
}
if (x & 0x200000000 > 0) {
result = (result * 0x10000000162E42FF1) >> 64;
}
if (x & 0x100000000 > 0) {
result = (result * 0x100000000B17217F8) >> 64;
}
}
if (x & 0xFF000000 > 0) {
if (x & 0x80000000 > 0) {
result = (result * 0x10000000058B90BFC) >> 64;
}
if (x & 0x40000000 > 0) {
result = (result * 0x1000000002C5C85FE) >> 64;
}
if (x & 0x20000000 > 0) {
result = (result * 0x100000000162E42FF) >> 64;
}
if (x & 0x10000000 > 0) {
result = (result * 0x1000000000B17217F) >> 64;
}
if (x & 0x8000000 > 0) {
result = (result * 0x100000000058B90C0) >> 64;
}
if (x & 0x4000000 > 0) {
result = (result * 0x10000000002C5C860) >> 64;
}
if (x & 0x2000000 > 0) {
result = (result * 0x1000000000162E430) >> 64;
}
if (x & 0x1000000 > 0) {
result = (result * 0x10000000000B17218) >> 64;
}
}
if (x & 0xFF0000 > 0) {
if (x & 0x800000 > 0) {
result = (result * 0x1000000000058B90C) >> 64;
}
if (x & 0x400000 > 0) {
result = (result * 0x100000000002C5C86) >> 64;
}
if (x & 0x200000 > 0) {
result = (result * 0x10000000000162E43) >> 64;
}
if (x & 0x100000 > 0) {
result = (result * 0x100000000000B1721) >> 64;
}
if (x & 0x80000 > 0) {
result = (result * 0x10000000000058B91) >> 64;
}
if (x & 0x40000 > 0) {
result = (result * 0x1000000000002C5C8) >> 64;
}
if (x & 0x20000 > 0) {
result = (result * 0x100000000000162E4) >> 64;
}
if (x & 0x10000 > 0) {
result = (result * 0x1000000000000B172) >> 64;
}
}
if (x & 0xFF00 > 0) {
if (x & 0x8000 > 0) {
result = (result * 0x100000000000058B9) >> 64;
}
if (x & 0x4000 > 0) {
result = (result * 0x10000000000002C5D) >> 64;
}
if (x & 0x2000 > 0) {
result = (result * 0x1000000000000162E) >> 64;
}
if (x & 0x1000 > 0) {
result = (result * 0x10000000000000B17) >> 64;
}
if (x & 0x800 > 0) {
result = (result * 0x1000000000000058C) >> 64;
}
if (x & 0x400 > 0) {
result = (result * 0x100000000000002C6) >> 64;
}
if (x & 0x200 > 0) {
result = (result * 0x10000000000000163) >> 64;
}
if (x & 0x100 > 0) {
result = (result * 0x100000000000000B1) >> 64;
}
}
if (x & 0xFF > 0) {
if (x & 0x80 > 0) {
result = (result * 0x10000000000000059) >> 64;
}
if (x & 0x40 > 0) {
result = (result * 0x1000000000000002C) >> 64;
}
if (x & 0x20 > 0) {
result = (result * 0x10000000000000016) >> 64;
}
if (x & 0x10 > 0) {
result = (result * 0x1000000000000000B) >> 64;
}
if (x & 0x8 > 0) {
result = (result * 0x10000000000000006) >> 64;
}
if (x & 0x4 > 0) {
result = (result * 0x10000000000000003) >> 64;
}
if (x & 0x2 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
if (x & 0x1 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
}
// In the code snippet below, two operations are executed simultaneously:
//
// 1. The result is multiplied by $(2^n + 1)$, where $2^n$ represents the integer part, and the additional 1
// accounts for the initial guess of 0.5. This is achieved by subtracting from 191 instead of 192.
// 2. The result is then converted to an unsigned 60.18-decimal fixed-point format.
//
// The underlying logic is based on the relationship $2^{191-ip} = 2^{ip} / 2^{191}$, where $ip$ denotes the
// integer part, $2^n$.
result *= UNIT;
result >>= (191 - (x >> 64));
}
}
/// @notice Finds the zero-based index of the first 1 in the binary representation of x.
///
/// @dev See the note on "msb" in this Wikipedia article: https://en.wikipedia.org/wiki/Find_first_set
///
/// The implementation satisfies these properties:
///
/// $$
/// \begin{cases}
/// x = 0 \implies \text{msb}(x) = 0 \\
/// x > 0 \implies x \gg \text{msb}(x) = 1
/// \end{cases}
/// $$
///
/// Each step below is equivalent to this high-level code:
///
/// ```solidity
/// if (x >= 2 ** 128) {
/// x >>= 128;
/// result += 128;
/// }
/// ```
///
/// Where 128 is replaced with each respective power of two factor. The Yul instructions used below are:
///
/// - "gt" is "greater than"
/// - "or" is the OR bitwise operator
/// - "shl" is "shift left"
/// - "shr" is "shift right"
///
/// See the full high-level implementation here:
/// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948
///
/// @param x The uint256 number for which to find the index of the most significant bit.
/// @return result The index of the most significant bit as a uint256.
/// @custom:smtchecker abstract-function-nondet
function msb(uint256 x) pure returns (uint256 result) {
// 2^128
assembly ("memory-safe") {
let factor := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^64
assembly ("memory-safe") {
let factor := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^32
assembly ("memory-safe") {
let factor := shl(5, gt(x, 0xFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^16
assembly ("memory-safe") {
let factor := shl(4, gt(x, 0xFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^8
assembly ("memory-safe") {
let factor := shl(3, gt(x, 0xFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^4
assembly ("memory-safe") {
let factor := shl(2, gt(x, 0xF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^2
assembly ("memory-safe") {
let factor := shl(1, gt(x, 0x3))
x := shr(factor, x)
result := or(result, factor)
}
// 2^1
// No need to shift x any more.
assembly ("memory-safe") {
let factor := gt(x, 0x1)
result := or(result, factor)
}
}
/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - The denominator must not be zero.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as a uint256.
/// @param y The multiplier as a uint256.
/// @param denominator The divisor as a uint256.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256 result) {
// 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 ("memory-safe") {
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) {
unchecked {
return prod0 / denominator;
}
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (prod1 >= denominator) {
revert PRBMath_MulDiv_Overflow(x, y, denominator);
}
////////////////////////////////////////////////////////////////////////////
// 512 by 256 division
////////////////////////////////////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using the mulmod Yul instruction.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512-bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
unchecked {
// Calculate the largest power of two divisor of the denominator using the unary operator ~. This operation cannot overflow
// because the denominator cannot be zero at this point in the function execution. The result is always >= 1.
// For more detail, see https://cs.stackexchange.com/q/138556/92363.
uint256 lpotdod = denominator & (~denominator + 1);
uint256 flippedLpotdod;
assembly ("memory-safe") {
// Factor powers of two out of denominator.
denominator := div(denominator, lpotdod)
// Divide [prod1 prod0] by lpotdod.
prod0 := div(prod0, lpotdod)
// Get the flipped value `2^256 / lpotdod`. If the `lpotdod` is zero, the flipped value is one.
// `sub(0, lpotdod)` produces the two's complement version of `lpotdod`, which is equivalent to flipping all the bits.
// However, `div` interprets this value as an unsigned value: https://ethereum.stackexchange.com/q/147168/24693
flippedLpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * flippedLpotdod;
// 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;
}
}
/// @notice Calculates x*y÷1e18 with 512-bit precision.
///
/// @dev A variant of {mulDiv} with constant folding, i.e. in which the denominator is hard coded to 1e18.
///
/// Notes:
/// - The body is purposely left uncommented; to understand how this works, see the documentation in {mulDiv}.
/// - The result is rounded toward zero.
/// - We take as an axiom that the result cannot be `MAX_UINT256` when x and y solve the following system of equations:
///
/// $$
/// \begin{cases}
/// x * y = {MAX\_UINT256} * {UNIT} \\
/// (x * y) \% {UNIT} \geq \frac{UNIT}{2}
/// \end{cases}
/// $$
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function mulDiv18(uint256 x, uint256 y) pure returns (uint256 result) {
uint256 prod0;
uint256 prod1;
assembly ("memory-safe") {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 == 0) {
unchecked {
return prod0 / UNIT;
}
}
if (prod1 >= UNIT) {
revert PRBMath_MulDiv18_Overflow(x, y);
}
uint256 remainder;
assembly ("memory-safe") {
remainder := mulmod(x, y, UNIT)
result := mul(
or(
div(sub(prod0, remainder), UNIT_LPOTD),
mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, UNIT_LPOTD), UNIT_LPOTD), 1))
),
UNIT_INVERSE
)
}
}
/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev This is an extension of {mulDiv} for signed numbers, which works by computing the signs and the absolute values separately.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - None of the inputs can be `type(int256).min`.
/// - The result must fit in int256.
///
/// @param x The multiplicand as an int256.
/// @param y The multiplier as an int256.
/// @param denominator The divisor as an int256.
/// @return result The result as an int256.
/// @custom:smtchecker abstract-function-nondet
function mulDivSigned(int256 x, int256 y, int256 denominator) pure returns (int256 result) {
if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {
revert PRBMath_MulDivSigned_InputTooSmall();
}
// Get hold of the absolute values of x, y and the denominator.
uint256 xAbs;
uint256 yAbs;
uint256 dAbs;
unchecked {
xAbs = x < 0 ? uint256(-x) : uint256(x);
yAbs = y < 0 ? uint256(-y) : uint256(y);
dAbs = denominator < 0 ? uint256(-denominator) : uint256(denominator);
}
// Compute the absolute value of x*y÷denominator. The result must fit in int256.
uint256 resultAbs = mulDiv(xAbs, yAbs, dAbs);
if (resultAbs > uint256(type(int256).max)) {
revert PRBMath_MulDivSigned_Overflow(x, y);
}
// Get the signs of x, y and the denominator.
uint256 sx;
uint256 sy;
uint256 sd;
assembly ("memory-safe") {
// "sgt" is the "signed greater than" assembly instruction and "sub(0,1)" is -1 in two's complement.
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
sd := sgt(denominator, sub(0, 1))
}
// XOR over sx, sy and sd. What this does is to check whether there are 1 or 3 negative signs in the inputs.
// If there are, the result should be negative. Otherwise, it should be positive.
unchecked {
result = sx ^ sy ^ sd == 0 ? -int256(resultAbs) : int256(resultAbs);
}
}
/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// The implementation satisfies these properties:
///
/// $$
/// \begin{cases}
/// \lfloor\sqrt{x}\rfloor \leq \sqrt{x} < \lfloor\sqrt{x}\rfloor + 1 \\[0.5em]
/// \lfloor\sqrt{x}\rfloor^2 \leq x < (\lfloor\sqrt{x}\rfloor + 1)^2
/// \end{cases}
/// $$
///
/// Notes:
/// - If x is not a perfect square, the result is rounded down.
/// - Credits to OpenZeppelin for the explanations in comments below.
///
/// @param x The uint256 number for which to calculate the square root.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function sqrt(uint256 x) pure returns (uint256 result) {
if (x == 0) {
return 0;
}
// For our first guess, we calculate the biggest power of 2 which is smaller than the square root of x.
//
// We know that the "msb" (most significant bit) of x is a power of 2 such that we have:
//
// $$
// msb(x) <= x <= 2*msb(x)
// $$
//
// We write $msb(x)$ as $2^k$, and we get:
//
// $$
// k = log_2(x)
// $$
//
// Thus, we can write the initial inequality as:
//
// $$
// 2^{log_2(x)} <= x <= 2*2^{log_2(x)+1} \\
// sqrt(2^k) <= sqrt(x) < sqrt(2^{k+1}) \\
// 2^{k/2} <= sqrt(x) < 2^{(k+1)/2} <= 2^{(k/2)+1}
// $$
//
// Consequently, $2^{log_2(x) / 2}$ is a good first approximation of sqrt(x) with at least one correct bit.
uint256 xAux = uint256(x);
result = 1;
if (xAux >= 2 ** 128) {
xAux >>= 128;
result <<= 64;
}
if (xAux >= 2 ** 64) {
xAux >>= 64;
result <<= 32;
}
if (xAux >= 2 ** 32) {
xAux >>= 32;
result <<= 16;
}
if (xAux >= 2 ** 16) {
xAux >>= 16;
result <<= 8;
}
if (xAux >= 2 ** 8) {
xAux >>= 8;
result <<= 4;
}
if (xAux >= 2 ** 4) {
xAux >>= 4;
result <<= 2;
}
if (xAux >= 2 ** 2) {
result <<= 1;
}
// At this point, `result` is an estimation with at least one bit of precision. We know the true value has at
// most 128 bits, 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 iterations to turn our partial result with one bit of
// precision into the expected uint128 result.
unchecked {
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
// If x is not a perfect square, round the result toward zero.
uint256 roundedResult = x / result;
if (result >= roundedResult) {
result = roundedResult;
}
}
}
lib/prb-math/src/UD60x18.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
/*
██████╗ ██████╗ ██████╗ ███╗ ███╗ █████╗ ████████╗██╗ ██╗
██╔══██╗██╔══██╗██╔══██╗████╗ ████║██╔══██╗╚══██╔══╝██║ ██║
██████╔╝██████╔╝██████╔╝██╔████╔██║███████║ ██║ ███████║
██╔═══╝ ██╔══██╗██╔══██╗██║╚██╔╝██║██╔══██║ ██║ ██╔══██║
██║ ██║ ██║██████╔╝██║ ╚═╝ ██║██║ ██║ ██║ ██║ ██║
╚═╝ ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝
██╗ ██╗██████╗ ██████╗ ██████╗ ██╗ ██╗ ██╗ █████╗
██║ ██║██╔══██╗██╔════╝ ██╔═████╗╚██╗██╔╝███║██╔══██╗
██║ ██║██║ ██║███████╗ ██║██╔██║ ╚███╔╝ ╚██║╚█████╔╝
██║ ██║██║ ██║██╔═══██╗████╔╝██║ ██╔██╗ ██║██╔══██╗
╚██████╔╝██████╔╝╚██████╔╝╚██████╔╝██╔╝ ██╗ ██║╚█████╔╝
╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚════╝
*/
import "./ud60x18/Casting.sol";
import "./ud60x18/Constants.sol";
import "./ud60x18/Conversions.sol";
import "./ud60x18/Errors.sol";
import "./ud60x18/Helpers.sol";
import "./ud60x18/Math.sol";
import "./ud60x18/ValueType.sol";
lib/prb-math/src/sd1x18/Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as CastingErrors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD1x18 } from "./ValueType.sol";
/// @notice Casts an SD1x18 number into SD59x18.
/// @dev There is no overflow check because SD1x18 ⊆ SD59x18.
function intoSD59x18(SD1x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(SD1x18.unwrap(x)));
}
/// @notice Casts an SD1x18 number into UD60x18.
/// @dev Requirements:
/// - x ≥ 0
function intoUD60x18(SD1x18 x) pure returns (UD60x18 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUD60x18_Underflow(x);
}
result = UD60x18.wrap(uint64(xInt));
}
/// @notice Casts an SD1x18 number into uint128.
/// @dev Requirements:
/// - x ≥ 0
function intoUint128(SD1x18 x) pure returns (uint128 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUint128_Underflow(x);
}
result = uint128(uint64(xInt));
}
/// @notice Casts an SD1x18 number into uint256.
/// @dev Requirements:
/// - x ≥ 0
function intoUint256(SD1x18 x) pure returns (uint256 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUint256_Underflow(x);
}
result = uint256(uint64(xInt));
}
/// @notice Casts an SD1x18 number into uint40.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ MAX_UINT40
function intoUint40(SD1x18 x) pure returns (uint40 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUint40_Underflow(x);
}
if (xInt > int64(uint64(Common.MAX_UINT40))) {
revert CastingErrors.PRBMath_SD1x18_ToUint40_Overflow(x);
}
result = uint40(uint64(xInt));
}
/// @notice Alias for {wrap}.
function sd1x18(int64 x) pure returns (SD1x18 result) {
result = SD1x18.wrap(x);
}
/// @notice Unwraps an SD1x18 number into int64.
function unwrap(SD1x18 x) pure returns (int64 result) {
result = SD1x18.unwrap(x);
}
/// @notice Wraps an int64 number into SD1x18.
function wrap(int64 x) pure returns (SD1x18 result) {
result = SD1x18.wrap(x);
}
lib/prb-math/src/sd1x18/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD1x18 } from "./ValueType.sol";
/// @dev Euler's number as an SD1x18 number.
SD1x18 constant E = SD1x18.wrap(2_718281828459045235);
/// @dev The maximum value an SD1x18 number can have.
int64 constant uMAX_SD1x18 = 9_223372036854775807;
SD1x18 constant MAX_SD1x18 = SD1x18.wrap(uMAX_SD1x18);
/// @dev The minimum value an SD1x18 number can have.
int64 constant uMIN_SD1x18 = -9_223372036854775808;
SD1x18 constant MIN_SD1x18 = SD1x18.wrap(uMIN_SD1x18);
/// @dev PI as an SD1x18 number.
SD1x18 constant PI = SD1x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of SD1x18.
SD1x18 constant UNIT = SD1x18.wrap(1e18);
int64 constant uUNIT = 1e18;
lib/prb-math/src/sd1x18/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD1x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in UD60x18.
error PRBMath_SD1x18_ToUD60x18_Underflow(SD1x18 x);
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint128.
error PRBMath_SD1x18_ToUint128_Underflow(SD1x18 x);
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint256.
error PRBMath_SD1x18_ToUint256_Underflow(SD1x18 x);
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint40.
error PRBMath_SD1x18_ToUint40_Overflow(SD1x18 x);
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint40.
error PRBMath_SD1x18_ToUint40_Underflow(SD1x18 x);
lib/prb-math/src/sd1x18/ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The signed 1.18-decimal fixed-point number representation, which can have up to 1 digit and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int64. This is useful when end users want to use int64 to save gas, e.g. with tight variable packing in contract
/// storage.
type SD1x18 is int64;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD59x18,
Casting.intoUD60x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for SD1x18 global;
lib/prb-math/src/sd21x18/Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as CastingErrors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD21x18 } from "./ValueType.sol";
/// @notice Casts an SD21x18 number into SD59x18.
/// @dev There is no overflow check because SD21x18 ⊆ SD59x18.
function intoSD59x18(SD21x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(SD21x18.unwrap(x)));
}
/// @notice Casts an SD21x18 number into UD60x18.
/// @dev Requirements:
/// - x ≥ 0
function intoUD60x18(SD21x18 x) pure returns (UD60x18 result) {
int128 xInt = SD21x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD21x18_ToUD60x18_Underflow(x);
}
result = UD60x18.wrap(uint128(xInt));
}
/// @notice Casts an SD21x18 number into uint128.
/// @dev Requirements:
/// - x ≥ 0
function intoUint128(SD21x18 x) pure returns (uint128 result) {
int128 xInt = SD21x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD21x18_ToUint128_Underflow(x);
}
result = uint128(xInt);
}
/// @notice Casts an SD21x18 number into uint256.
/// @dev Requirements:
/// - x ≥ 0
function intoUint256(SD21x18 x) pure returns (uint256 result) {
int128 xInt = SD21x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD21x18_ToUint256_Underflow(x);
}
result = uint256(uint128(xInt));
}
/// @notice Casts an SD21x18 number into uint40.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ MAX_UINT40
function intoUint40(SD21x18 x) pure returns (uint40 result) {
int128 xInt = SD21x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD21x18_ToUint40_Underflow(x);
}
if (xInt > int128(uint128(Common.MAX_UINT40))) {
revert CastingErrors.PRBMath_SD21x18_ToUint40_Overflow(x);
}
result = uint40(uint128(xInt));
}
/// @notice Alias for {wrap}.
function sd21x18(int128 x) pure returns (SD21x18 result) {
result = SD21x18.wrap(x);
}
/// @notice Unwraps an SD21x18 number into int128.
function unwrap(SD21x18 x) pure returns (int128 result) {
result = SD21x18.unwrap(x);
}
/// @notice Wraps an int128 number into SD21x18.
function wrap(int128 x) pure returns (SD21x18 result) {
result = SD21x18.wrap(x);
}
lib/prb-math/src/sd21x18/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD21x18 } from "./ValueType.sol";
/// @dev Euler's number as an SD21x18 number.
SD21x18 constant E = SD21x18.wrap(2_718281828459045235);
/// @dev The maximum value an SD21x18 number can have.
int128 constant uMAX_SD21x18 = 170141183460469231731_687303715884105727;
SD21x18 constant MAX_SD21x18 = SD21x18.wrap(uMAX_SD21x18);
/// @dev The minimum value an SD21x18 number can have.
int128 constant uMIN_SD21x18 = -170141183460469231731_687303715884105728;
SD21x18 constant MIN_SD21x18 = SD21x18.wrap(uMIN_SD21x18);
/// @dev PI as an SD21x18 number.
SD21x18 constant PI = SD21x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of SD21x18.
SD21x18 constant UNIT = SD21x18.wrap(1e18);
int128 constant uUNIT = 1e18;
lib/prb-math/src/sd21x18/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD21x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint128.
error PRBMath_SD21x18_ToUint128_Underflow(SD21x18 x);
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in UD60x18.
error PRBMath_SD21x18_ToUD60x18_Underflow(SD21x18 x);
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint256.
error PRBMath_SD21x18_ToUint256_Underflow(SD21x18 x);
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint40.
error PRBMath_SD21x18_ToUint40_Overflow(SD21x18 x);
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint40.
error PRBMath_SD21x18_ToUint40_Underflow(SD21x18 x);
lib/prb-math/src/sd21x18/ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The signed 21.18-decimal fixed-point number representation, which can have up to 21 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int128. This is useful when end users want to use int128 to save gas, e.g. with tight variable packing in contract
/// storage.
type SD21x18 is int128;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD59x18,
Casting.intoUD60x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for SD21x18 global;
lib/prb-math/src/sd59x18/Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Errors.sol" as CastingErrors;
import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
import { uMAX_SD1x18, uMIN_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { uMAX_SD21x18, uMIN_SD21x18 } from "../sd21x18/Constants.sol";
import { SD21x18 } from "../sd21x18/ValueType.sol";
import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { uMAX_UD21x18 } from "../ud21x18/Constants.sol";
import { UD21x18 } from "../ud21x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD59x18 } from "./ValueType.sol";
/// @notice Casts an SD59x18 number into int256.
/// @dev This is basically a functional alias for {unwrap}.
function intoInt256(SD59x18 x) pure returns (int256 result) {
result = SD59x18.unwrap(x);
}
/// @notice Casts an SD59x18 number into SD1x18.
/// @dev Requirements:
/// - x ≥ uMIN_SD1x18
/// - x ≤ uMAX_SD1x18
function intoSD1x18(SD59x18 x) pure returns (SD1x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < uMIN_SD1x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Underflow(x);
}
if (xInt > uMAX_SD1x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Overflow(x);
}
result = SD1x18.wrap(int64(xInt));
}
/// @notice Casts an SD59x18 number into SD21x18.
/// @dev Requirements:
/// - x ≥ uMIN_SD21x18
/// - x ≤ uMAX_SD21x18
function intoSD21x18(SD59x18 x) pure returns (SD21x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < uMIN_SD21x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD21x18_Underflow(x);
}
if (xInt > uMAX_SD21x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD21x18_Overflow(x);
}
result = SD21x18.wrap(int128(xInt));
}
/// @notice Casts an SD59x18 number into UD2x18.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ uMAX_UD2x18
function intoUD2x18(SD59x18 x) pure returns (UD2x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Underflow(x);
}
if (xInt > int256(uint256(uMAX_UD2x18))) {
revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Overflow(x);
}
result = UD2x18.wrap(uint64(uint256(xInt)));
}
/// @notice Casts an SD59x18 number into UD21x18.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ uMAX_UD21x18
function intoUD21x18(SD59x18 x) pure returns (UD21x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUD21x18_Underflow(x);
}
if (xInt > int256(uint256(uMAX_UD21x18))) {
revert CastingErrors.PRBMath_SD59x18_IntoUD21x18_Overflow(x);
}
result = UD21x18.wrap(uint128(uint256(xInt)));
}
/// @notice Casts an SD59x18 number into UD60x18.
/// @dev Requirements:
/// - x ≥ 0
function intoUD60x18(SD59x18 x) pure returns (UD60x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUD60x18_Underflow(x);
}
result = UD60x18.wrap(uint256(xInt));
}
/// @notice Casts an SD59x18 number into uint256.
/// @dev Requirements:
/// - x ≥ 0
function intoUint256(SD59x18 x) pure returns (uint256 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUint256_Underflow(x);
}
result = uint256(xInt);
}
/// @notice Casts an SD59x18 number into uint128.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ uMAX_UINT128
function intoUint128(SD59x18 x) pure returns (uint128 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUint128_Underflow(x);
}
if (xInt > int256(uint256(MAX_UINT128))) {
revert CastingErrors.PRBMath_SD59x18_IntoUint128_Overflow(x);
}
result = uint128(uint256(xInt));
}
/// @notice Casts an SD59x18 number into uint40.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ MAX_UINT40
function intoUint40(SD59x18 x) pure returns (uint40 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUint40_Underflow(x);
}
if (xInt > int256(uint256(MAX_UINT40))) {
revert CastingErrors.PRBMath_SD59x18_IntoUint40_Overflow(x);
}
result = uint40(uint256(xInt));
}
/// @notice Alias for {wrap}.
function sd(int256 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(x);
}
/// @notice Alias for {wrap}.
function sd59x18(int256 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(x);
}
/// @notice Unwraps an SD59x18 number into int256.
function unwrap(SD59x18 x) pure returns (int256 result) {
result = SD59x18.unwrap(x);
}
/// @notice Wraps an int256 number into SD59x18.
function wrap(int256 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(x);
}
lib/prb-math/src/sd59x18/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD59x18 } from "./ValueType.sol";
// NOTICE: the "u" prefix stands for "unwrapped".
/// @dev Euler's number as an SD59x18 number.
SD59x18 constant E = SD59x18.wrap(2_718281828459045235);
/// @dev The maximum input permitted in {exp}.
int256 constant uEXP_MAX_INPUT = 133_084258667509499440;
SD59x18 constant EXP_MAX_INPUT = SD59x18.wrap(uEXP_MAX_INPUT);
/// @dev Any value less than this returns 0 in {exp}.
int256 constant uEXP_MIN_THRESHOLD = -41_446531673892822322;
SD59x18 constant EXP_MIN_THRESHOLD = SD59x18.wrap(uEXP_MIN_THRESHOLD);
/// @dev The maximum input permitted in {exp2}.
int256 constant uEXP2_MAX_INPUT = 192e18 - 1;
SD59x18 constant EXP2_MAX_INPUT = SD59x18.wrap(uEXP2_MAX_INPUT);
/// @dev Any value less than this returns 0 in {exp2}.
int256 constant uEXP2_MIN_THRESHOLD = -59_794705707972522261;
SD59x18 constant EXP2_MIN_THRESHOLD = SD59x18.wrap(uEXP2_MIN_THRESHOLD);
/// @dev Half the UNIT number.
int256 constant uHALF_UNIT = 0.5e18;
SD59x18 constant HALF_UNIT = SD59x18.wrap(uHALF_UNIT);
/// @dev $log_2(10)$ as an SD59x18 number.
int256 constant uLOG2_10 = 3_321928094887362347;
SD59x18 constant LOG2_10 = SD59x18.wrap(uLOG2_10);
/// @dev $log_2(e)$ as an SD59x18 number.
int256 constant uLOG2_E = 1_442695040888963407;
SD59x18 constant LOG2_E = SD59x18.wrap(uLOG2_E);
/// @dev The maximum value an SD59x18 number can have.
int256 constant uMAX_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_792003956564819967;
SD59x18 constant MAX_SD59x18 = SD59x18.wrap(uMAX_SD59x18);
/// @dev The maximum whole value an SD59x18 number can have.
int256 constant uMAX_WHOLE_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_000000000000000000;
SD59x18 constant MAX_WHOLE_SD59x18 = SD59x18.wrap(uMAX_WHOLE_SD59x18);
/// @dev The minimum value an SD59x18 number can have.
int256 constant uMIN_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_792003956564819968;
SD59x18 constant MIN_SD59x18 = SD59x18.wrap(uMIN_SD59x18);
/// @dev The minimum whole value an SD59x18 number can have.
int256 constant uMIN_WHOLE_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_000000000000000000;
SD59x18 constant MIN_WHOLE_SD59x18 = SD59x18.wrap(uMIN_WHOLE_SD59x18);
/// @dev PI as an SD59x18 number.
SD59x18 constant PI = SD59x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of SD59x18.
int256 constant uUNIT = 1e18;
SD59x18 constant UNIT = SD59x18.wrap(1e18);
/// @dev The unit number squared.
int256 constant uUNIT_SQUARED = 1e36;
SD59x18 constant UNIT_SQUARED = SD59x18.wrap(uUNIT_SQUARED);
/// @dev Zero as an SD59x18 number.
SD59x18 constant ZERO = SD59x18.wrap(0);
lib/prb-math/src/sd59x18/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD59x18 } from "./ValueType.sol";
/// @notice Thrown when taking the absolute value of `MIN_SD59x18`.
error PRBMath_SD59x18_Abs_MinSD59x18();
/// @notice Thrown when ceiling a number overflows SD59x18.
error PRBMath_SD59x18_Ceil_Overflow(SD59x18 x);
/// @notice Thrown when converting a basic integer to the fixed-point format overflows SD59x18.
error PRBMath_SD59x18_Convert_Overflow(int256 x);
/// @notice Thrown when converting a basic integer to the fixed-point format underflows SD59x18.
error PRBMath_SD59x18_Convert_Underflow(int256 x);
/// @notice Thrown when dividing two numbers and one of them is `MIN_SD59x18`.
error PRBMath_SD59x18_Div_InputTooSmall();
/// @notice Thrown when dividing two numbers and one of the intermediary unsigned results overflows SD59x18.
error PRBMath_SD59x18_Div_Overflow(SD59x18 x, SD59x18 y);
/// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441.
error PRBMath_SD59x18_Exp_InputTooBig(SD59x18 x);
/// @notice Thrown when taking the binary exponent of a base greater than 192e18.
error PRBMath_SD59x18_Exp2_InputTooBig(SD59x18 x);
/// @notice Thrown when flooring a number underflows SD59x18.
error PRBMath_SD59x18_Floor_Underflow(SD59x18 x);
/// @notice Thrown when taking the geometric mean of two numbers and their product is negative.
error PRBMath_SD59x18_Gm_NegativeProduct(SD59x18 x, SD59x18 y);
/// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows SD59x18.
error PRBMath_SD59x18_Gm_Overflow(SD59x18 x, SD59x18 y);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD1x18.
error PRBMath_SD59x18_IntoSD1x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD1x18.
error PRBMath_SD59x18_IntoSD1x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD21x18.
error PRBMath_SD59x18_IntoSD21x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD21x18.
error PRBMath_SD59x18_IntoSD21x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD2x18.
error PRBMath_SD59x18_IntoUD2x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD2x18.
error PRBMath_SD59x18_IntoUD2x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD21x18.
error PRBMath_SD59x18_IntoUD21x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD21x18.
error PRBMath_SD59x18_IntoUD21x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD60x18.
error PRBMath_SD59x18_IntoUD60x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint128.
error PRBMath_SD59x18_IntoUint128_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint128.
error PRBMath_SD59x18_IntoUint128_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint256.
error PRBMath_SD59x18_IntoUint256_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint40.
error PRBMath_SD59x18_IntoUint40_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint40.
error PRBMath_SD59x18_IntoUint40_Underflow(SD59x18 x);
/// @notice Thrown when taking the logarithm of a number less than or equal to zero.
error PRBMath_SD59x18_Log_InputTooSmall(SD59x18 x);
/// @notice Thrown when multiplying two numbers and one of the inputs is `MIN_SD59x18`.
error PRBMath_SD59x18_Mul_InputTooSmall();
/// @notice Thrown when multiplying two numbers and the intermediary absolute result overflows SD59x18.
error PRBMath_SD59x18_Mul_Overflow(SD59x18 x, SD59x18 y);
/// @notice Thrown when raising a number to a power and the intermediary absolute result overflows SD59x18.
error PRBMath_SD59x18_Powu_Overflow(SD59x18 x, uint256 y);
/// @notice Thrown when taking the square root of a negative number.
error PRBMath_SD59x18_Sqrt_NegativeInput(SD59x18 x);
/// @notice Thrown when calculating the square root overflows SD59x18.
error PRBMath_SD59x18_Sqrt_Overflow(SD59x18 x);
lib/prb-math/src/sd59x18/Helpers.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { wrap } from "./Casting.sol";
import { SD59x18 } from "./ValueType.sol";
/// @notice Implements the checked addition operation (+) in the SD59x18 type.
function add(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
return wrap(x.unwrap() + y.unwrap());
}
/// @notice Implements the AND (&) bitwise operation in the SD59x18 type.
function and(SD59x18 x, int256 bits) pure returns (SD59x18 result) {
return wrap(x.unwrap() & bits);
}
/// @notice Implements the AND (&) bitwise operation in the SD59x18 type.
function and2(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
return wrap(x.unwrap() & y.unwrap());
}
/// @notice Implements the equal (=) operation in the SD59x18 type.
function eq(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() == y.unwrap();
}
/// @notice Implements the greater than operation (>) in the SD59x18 type.
function gt(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() > y.unwrap();
}
/// @notice Implements the greater than or equal to operation (>=) in the SD59x18 type.
function gte(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() >= y.unwrap();
}
/// @notice Implements a zero comparison check function in the SD59x18 type.
function isZero(SD59x18 x) pure returns (bool result) {
result = x.unwrap() == 0;
}
/// @notice Implements the left shift operation (<<) in the SD59x18 type.
function lshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
result = wrap(x.unwrap() << bits);
}
/// @notice Implements the lower than operation (<) in the SD59x18 type.
function lt(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() < y.unwrap();
}
/// @notice Implements the lower than or equal to operation (<=) in the SD59x18 type.
function lte(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() <= y.unwrap();
}
/// @notice Implements the unchecked modulo operation (%) in the SD59x18 type.
function mod(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() % y.unwrap());
}
/// @notice Implements the not equal operation (!=) in the SD59x18 type.
function neq(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() != y.unwrap();
}
/// @notice Implements the NOT (~) bitwise operation in the SD59x18 type.
function not(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(~x.unwrap());
}
/// @notice Implements the OR (|) bitwise operation in the SD59x18 type.
function or(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() | y.unwrap());
}
/// @notice Implements the right shift operation (>>) in the SD59x18 type.
function rshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
result = wrap(x.unwrap() >> bits);
}
/// @notice Implements the checked subtraction operation (-) in the SD59x18 type.
function sub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() - y.unwrap());
}
/// @notice Implements the checked unary minus operation (-) in the SD59x18 type.
function unary(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(-x.unwrap());
}
/// @notice Implements the unchecked addition operation (+) in the SD59x18 type.
function uncheckedAdd(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
unchecked {
result = wrap(x.unwrap() + y.unwrap());
}
}
/// @notice Implements the unchecked subtraction operation (-) in the SD59x18 type.
function uncheckedSub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
unchecked {
result = wrap(x.unwrap() - y.unwrap());
}
}
/// @notice Implements the unchecked unary minus operation (-) in the SD59x18 type.
function uncheckedUnary(SD59x18 x) pure returns (SD59x18 result) {
unchecked {
result = wrap(-x.unwrap());
}
}
/// @notice Implements the XOR (^) bitwise operation in the SD59x18 type.
function xor(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() ^ y.unwrap());
}
lib/prb-math/src/sd59x18/Math.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import {
uEXP_MAX_INPUT,
uEXP2_MAX_INPUT,
uEXP_MIN_THRESHOLD,
uEXP2_MIN_THRESHOLD,
uHALF_UNIT,
uLOG2_10,
uLOG2_E,
uMAX_SD59x18,
uMAX_WHOLE_SD59x18,
uMIN_SD59x18,
uMIN_WHOLE_SD59x18,
UNIT,
uUNIT,
uUNIT_SQUARED,
ZERO
} from "./Constants.sol";
import { wrap } from "./Helpers.sol";
import { SD59x18 } from "./ValueType.sol";
/// @notice Calculates the absolute value of x.
///
/// @dev Requirements:
/// - x > MIN_SD59x18.
///
/// @param x The SD59x18 number for which to calculate the absolute value.
/// @return result The absolute value of x as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function abs(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt == uMIN_SD59x18) {
revert Errors.PRBMath_SD59x18_Abs_MinSD59x18();
}
result = xInt < 0 ? wrap(-xInt) : x;
}
/// @notice Calculates the arithmetic average of x and y.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// @param x The first operand as an SD59x18 number.
/// @param y The second operand as an SD59x18 number.
/// @return result The arithmetic average as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function avg(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
unchecked {
// This operation is equivalent to `x / 2 + y / 2`, and it can never overflow.
int256 sum = (xInt >> 1) + (yInt >> 1);
if (sum < 0) {
// If at least one of x and y is odd, add 1 to the result, because shifting negative numbers to the right
// rounds toward negative infinity. The right part is equivalent to `sum + (x % 2 == 1 || y % 2 == 1)`.
assembly ("memory-safe") {
result := add(sum, and(or(xInt, yInt), 1))
}
} else {
// Add 1 if both x and y are odd to account for the double 0.5 remainder truncated after shifting.
result = wrap(sum + (xInt & yInt & 1));
}
}
}
/// @notice Yields the smallest whole number greater than or equal to x.
///
/// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x ≤ MAX_WHOLE_SD59x18
///
/// @param x The SD59x18 number to ceil.
/// @return result The smallest whole number greater than or equal to x, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function ceil(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt > uMAX_WHOLE_SD59x18) {
revert Errors.PRBMath_SD59x18_Ceil_Overflow(x);
}
int256 remainder = xInt % uUNIT;
if (remainder == 0) {
result = x;
} else {
unchecked {
// Solidity uses C fmod style, which returns a modulus with the same sign as x.
int256 resultInt = xInt - remainder;
if (xInt > 0) {
resultInt += uUNIT;
}
result = wrap(resultInt);
}
}
}
/// @notice Divides two SD59x18 numbers, returning a new SD59x18 number.
///
/// @dev This is an extension of {Common.mulDiv} for signed numbers, which works by computing the signs and the absolute
/// values separately.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
/// - The result is rounded toward zero.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
/// - None of the inputs can be `MIN_SD59x18`.
/// - The denominator must not be zero.
/// - The result must fit in SD59x18.
///
/// @param x The numerator as an SD59x18 number.
/// @param y The denominator as an SD59x18 number.
/// @return result The quotient as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function div(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
revert Errors.PRBMath_SD59x18_Div_InputTooSmall();
}
// Get hold of the absolute values of x and y.
uint256 xAbs;
uint256 yAbs;
unchecked {
xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
}
// Compute the absolute value (x*UNIT÷y). The resulting value must fit in SD59x18.
uint256 resultAbs = Common.mulDiv(xAbs, uint256(uUNIT), yAbs);
if (resultAbs > uint256(uMAX_SD59x18)) {
revert Errors.PRBMath_SD59x18_Div_Overflow(x, y);
}
// Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for
// negative, 0 for positive or zero).
bool sameSign = (xInt ^ yInt) > -1;
// If the inputs have the same sign, the result should be positive. Otherwise, it should be negative.
unchecked {
result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
}
}
/// @notice Calculates the natural exponent of x using the following formula:
///
/// $$
/// e^x = 2^{x * log_2{e}}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {exp2}.
///
/// Requirements:
/// - Refer to the requirements in {exp2}.
/// - x < 133_084258667509499441.
///
/// @param x The exponent as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
// Any input less than the threshold returns zero.
// This check also prevents an overflow for very small numbers.
if (xInt < uEXP_MIN_THRESHOLD) {
return ZERO;
}
// This check prevents values greater than 192e18 from being passed to {exp2}.
if (xInt > uEXP_MAX_INPUT) {
revert Errors.PRBMath_SD59x18_Exp_InputTooBig(x);
}
unchecked {
// Inline the fixed-point multiplication to save gas.
int256 doubleUnitProduct = xInt * uLOG2_E;
result = exp2(wrap(doubleUnitProduct / uUNIT));
}
}
/// @notice Calculates the binary exponent of x using the binary fraction method using the following formula:
///
/// $$
/// 2^{-x} = \frac{1}{2^x}
/// $$
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693.
///
/// Notes:
/// - If x < -59_794705707972522261, the result is zero.
///
/// Requirements:
/// - x < 192e18.
/// - The result must fit in SD59x18.
///
/// @param x The exponent as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp2(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < 0) {
// The inverse of any number less than the threshold is truncated to zero.
if (xInt < uEXP2_MIN_THRESHOLD) {
return ZERO;
}
unchecked {
// Inline the fixed-point inversion to save gas.
result = wrap(uUNIT_SQUARED / exp2(wrap(-xInt)).unwrap());
}
} else {
// Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format.
if (xInt > uEXP2_MAX_INPUT) {
revert Errors.PRBMath_SD59x18_Exp2_InputTooBig(x);
}
unchecked {
// Convert x to the 192.64-bit fixed-point format.
uint256 x_192x64 = uint256((xInt << 64) / uUNIT);
// It is safe to cast the result to int256 due to the checks above.
result = wrap(int256(Common.exp2(x_192x64)));
}
}
}
/// @notice Yields the greatest whole number less than or equal to x.
///
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional
/// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x ≥ MIN_WHOLE_SD59x18
///
/// @param x The SD59x18 number to floor.
/// @return result The greatest whole number less than or equal to x, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function floor(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < uMIN_WHOLE_SD59x18) {
revert Errors.PRBMath_SD59x18_Floor_Underflow(x);
}
int256 remainder = xInt % uUNIT;
if (remainder == 0) {
result = x;
} else {
unchecked {
// Solidity uses C fmod style, which returns a modulus with the same sign as x.
int256 resultInt = xInt - remainder;
if (xInt < 0) {
resultInt -= uUNIT;
}
result = wrap(resultInt);
}
}
}
/// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right.
/// of the radix point for negative numbers.
/// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part
/// @param x The SD59x18 number to get the fractional part of.
/// @return result The fractional part of x as an SD59x18 number.
function frac(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(x.unwrap() % uUNIT);
}
/// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x * y must fit in SD59x18.
/// - x * y must not be negative, since complex numbers are not supported.
///
/// @param x The first operand as an SD59x18 number.
/// @param y The second operand as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function gm(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
if (xInt == 0 || yInt == 0) {
return ZERO;
}
unchecked {
// Equivalent to `xy / x != y`. Checking for overflow this way is faster than letting Solidity do it.
int256 xyInt = xInt * yInt;
if (xyInt / xInt != yInt) {
revert Errors.PRBMath_SD59x18_Gm_Overflow(x, y);
}
// The product must not be negative, since complex numbers are not supported.
if (xyInt < 0) {
revert Errors.PRBMath_SD59x18_Gm_NegativeProduct(x, y);
}
// We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT`
// during multiplication. See the comments in {Common.sqrt}.
uint256 resultUint = Common.sqrt(uint256(xyInt));
result = wrap(int256(resultUint));
}
}
/// @notice Calculates the inverse of x.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x must not be zero.
///
/// @param x The SD59x18 number for which to calculate the inverse.
/// @return result The inverse as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function inv(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(uUNIT_SQUARED / x.unwrap());
}
/// @notice Calculates the natural logarithm of x using the following formula:
///
/// $$
/// ln{x} = log_2{x} / log_2{e}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
/// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The SD59x18 number for which to calculate the natural logarithm.
/// @return result The natural logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function ln(SD59x18 x) pure returns (SD59x18 result) {
// Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that
// {log2} can return is ~195_205294292027477728.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E);
}
/// @notice Calculates the common logarithm of x using the following formula:
///
/// $$
/// log_{10}{x} = log_2{x} / log_2{10}
/// $$
///
/// However, if x is an exact power of ten, a hard coded value is returned.
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The SD59x18 number for which to calculate the common logarithm.
/// @return result The common logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function log10(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < 0) {
revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x);
}
// Note that the `mul` in this block is the standard multiplication operation, not {SD59x18.mul}.
// prettier-ignore
assembly ("memory-safe") {
switch x
case 1 { result := mul(uUNIT, sub(0, 18)) }
case 10 { result := mul(uUNIT, sub(1, 18)) }
case 100 { result := mul(uUNIT, sub(2, 18)) }
case 1000 { result := mul(uUNIT, sub(3, 18)) }
case 10000 { result := mul(uUNIT, sub(4, 18)) }
case 100000 { result := mul(uUNIT, sub(5, 18)) }
case 1000000 { result := mul(uUNIT, sub(6, 18)) }
case 10000000 { result := mul(uUNIT, sub(7, 18)) }
case 100000000 { result := mul(uUNIT, sub(8, 18)) }
case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
case 1000000000000000000 { result := 0 }
case 10000000000000000000 { result := uUNIT }
case 100000000000000000000 { result := mul(uUNIT, 2) }
case 1000000000000000000000 { result := mul(uUNIT, 3) }
case 10000000000000000000000 { result := mul(uUNIT, 4) }
case 100000000000000000000000 { result := mul(uUNIT, 5) }
case 1000000000000000000000000 { result := mul(uUNIT, 6) }
case 10000000000000000000000000 { result := mul(uUNIT, 7) }
case 100000000000000000000000000 { result := mul(uUNIT, 8) }
case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
default { result := uMAX_SD59x18 }
}
if (result.unwrap() == uMAX_SD59x18) {
unchecked {
// Inline the fixed-point division to save gas.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10);
}
}
}
/// @notice Calculates the binary logarithm of x using the iterative approximation algorithm:
///
/// $$
/// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2)
/// $$
///
/// For $0 \leq x \lt 1$, the input is inverted:
///
/// $$
/// log_2{x} = -log_2{\frac{1}{x}}
/// $$
///
/// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation.
///
/// Notes:
/// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal.
///
/// Requirements:
/// - x > 0
///
/// @param x The SD59x18 number for which to calculate the binary logarithm.
/// @return result The binary logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function log2(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt <= 0) {
revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x);
}
unchecked {
int256 sign;
if (xInt >= uUNIT) {
sign = 1;
} else {
sign = -1;
// Inline the fixed-point inversion to save gas.
xInt = uUNIT_SQUARED / xInt;
}
// Calculate the integer part of the logarithm.
uint256 n = Common.msb(uint256(xInt / uUNIT));
// This is the integer part of the logarithm as an SD59x18 number. The operation can't overflow
// because n is at most 255, `UNIT` is 1e18, and the sign is either 1 or -1.
int256 resultInt = int256(n) * uUNIT;
// Calculate $y = x * 2^{-n}$.
int256 y = xInt >> n;
// If y is the unit number, the fractional part is zero.
if (y == uUNIT) {
return wrap(resultInt * sign);
}
// Calculate the fractional part via the iterative approximation.
// The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient.
int256 doubleUnit = 2e18;
for (int256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
y = (y * y) / uUNIT;
// Is y^2 >= 2e18 and so in the range [2e18, 4e18)?
if (y >= doubleUnit) {
// Add the 2^{-m} factor to the logarithm.
resultInt = resultInt + delta;
// Halve y, which corresponds to z/2 in the Wikipedia article.
y >>= 1;
}
}
resultInt *= sign;
result = wrap(resultInt);
}
}
/// @notice Multiplies two SD59x18 numbers together, returning a new SD59x18 number.
///
/// @dev Notes:
/// - Refer to the notes in {Common.mulDiv18}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv18}.
/// - None of the inputs can be `MIN_SD59x18`.
/// - The result must fit in SD59x18.
///
/// @param x The multiplicand as an SD59x18 number.
/// @param y The multiplier as an SD59x18 number.
/// @return result The product as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function mul(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
revert Errors.PRBMath_SD59x18_Mul_InputTooSmall();
}
// Get hold of the absolute values of x and y.
uint256 xAbs;
uint256 yAbs;
unchecked {
xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
}
// Compute the absolute value (x*y÷UNIT). The resulting value must fit in SD59x18.
uint256 resultAbs = Common.mulDiv18(xAbs, yAbs);
if (resultAbs > uint256(uMAX_SD59x18)) {
revert Errors.PRBMath_SD59x18_Mul_Overflow(x, y);
}
// Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for
// negative, 0 for positive or zero).
bool sameSign = (xInt ^ yInt) > -1;
// If the inputs have the same sign, the result should be positive. Otherwise, it should be negative.
unchecked {
result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
}
}
/// @notice Raises x to the power of y using the following formula:
///
/// $$
/// x^y = 2^{log_2{x} * y}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {exp2}, {log2}, and {mul}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - Refer to the requirements in {exp2}, {log2}, and {mul}.
///
/// @param x The base as an SD59x18 number.
/// @param y Exponent to raise x to, as an SD59x18 number
/// @return result x raised to power y, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function pow(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
// If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero.
if (xInt == 0) {
return yInt == 0 ? UNIT : ZERO;
}
// If x is `UNIT`, the result is always `UNIT`.
else if (xInt == uUNIT) {
return UNIT;
}
// If y is zero, the result is always `UNIT`.
if (yInt == 0) {
return UNIT;
}
// If y is `UNIT`, the result is always x.
else if (yInt == uUNIT) {
return x;
}
// Calculate the result using the formula.
result = exp2(mul(log2(x), y));
}
/// @notice Raises x (an SD59x18 number) to the power y (an unsigned basic integer) using the well-known
/// algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv18}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - Refer to the requirements in {abs} and {Common.mulDiv18}.
/// - The result must fit in SD59x18.
///
/// @param x The base as an SD59x18 number.
/// @param y The exponent as a uint256.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function powu(SD59x18 x, uint256 y) pure returns (SD59x18 result) {
uint256 xAbs = uint256(abs(x).unwrap());
// Calculate the first iteration of the loop in advance.
uint256 resultAbs = y & 1 > 0 ? xAbs : uint256(uUNIT);
// Equivalent to `for(y /= 2; y > 0; y /= 2)`.
uint256 yAux = y;
for (yAux >>= 1; yAux > 0; yAux >>= 1) {
xAbs = Common.mulDiv18(xAbs, xAbs);
// Equivalent to `y % 2 == 1`.
if (yAux & 1 > 0) {
resultAbs = Common.mulDiv18(resultAbs, xAbs);
}
}
// The result must fit in SD59x18.
if (resultAbs > uint256(uMAX_SD59x18)) {
revert Errors.PRBMath_SD59x18_Powu_Overflow(x, y);
}
unchecked {
// Is the base negative and the exponent odd? If yes, the result should be negative.
int256 resultInt = int256(resultAbs);
bool isNegative = x.unwrap() < 0 && y & 1 == 1;
if (isNegative) {
resultInt = -resultInt;
}
result = wrap(resultInt);
}
}
/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - Only the positive root is returned.
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x ≥ 0, since complex numbers are not supported.
/// - x ≤ MAX_SD59x18 / UNIT
///
/// @param x The SD59x18 number for which to calculate the square root.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function sqrt(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < 0) {
revert Errors.PRBMath_SD59x18_Sqrt_NegativeInput(x);
}
if (xInt > uMAX_SD59x18 / uUNIT) {
revert Errors.PRBMath_SD59x18_Sqrt_Overflow(x);
}
unchecked {
// Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two SD59x18 numbers.
// In this case, the two numbers are both the square root.
uint256 resultUint = Common.sqrt(uint256(xInt * uUNIT));
result = wrap(int256(resultUint));
}
}
lib/prb-math/src/sd59x18/ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
import "./Helpers.sol" as Helpers;
import "./Math.sol" as Math;
/// @notice The signed 59.18-decimal fixed-point number representation, which can have up to 59 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int256.
type SD59x18 is int256;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoInt256,
Casting.intoSD1x18,
Casting.intoSD21x18,
Casting.intoUD2x18,
Casting.intoUD21x18,
Casting.intoUD60x18,
Casting.intoUint256,
Casting.intoUint128,
Casting.intoUint40,
Casting.unwrap
} for SD59x18 global;
/*//////////////////////////////////////////////////////////////////////////
MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
using {
Math.abs,
Math.avg,
Math.ceil,
Math.div,
Math.exp,
Math.exp2,
Math.floor,
Math.frac,
Math.gm,
Math.inv,
Math.log10,
Math.log2,
Math.ln,
Math.mul,
Math.pow,
Math.powu,
Math.sqrt
} for SD59x18 global;
/*//////////////////////////////////////////////////////////////////////////
HELPER FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
using {
Helpers.add,
Helpers.and,
Helpers.eq,
Helpers.gt,
Helpers.gte,
Helpers.isZero,
Helpers.lshift,
Helpers.lt,
Helpers.lte,
Helpers.mod,
Helpers.neq,
Helpers.not,
Helpers.or,
Helpers.rshift,
Helpers.sub,
Helpers.uncheckedAdd,
Helpers.uncheckedSub,
Helpers.uncheckedUnary,
Helpers.xor
} for SD59x18 global;
/*//////////////////////////////////////////////////////////////////////////
OPERATORS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes it possible to use these operators on the SD59x18 type.
using {
Helpers.add as +,
Helpers.and2 as &,
Math.div as /,
Helpers.eq as ==,
Helpers.gt as >,
Helpers.gte as >=,
Helpers.lt as <,
Helpers.lte as <=,
Helpers.mod as %,
Math.mul as *,
Helpers.neq as !=,
Helpers.not as ~,
Helpers.or as |,
Helpers.sub as -,
Helpers.unary as -,
Helpers.xor as ^
} for SD59x18 global;
lib/prb-math/src/ud21x18/Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { UD21x18 } from "./ValueType.sol";
/// @notice Casts a UD21x18 number into SD59x18.
/// @dev There is no overflow check because UD21x18 ⊆ SD59x18.
function intoSD59x18(UD21x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(uint256(UD21x18.unwrap(x))));
}
/// @notice Casts a UD21x18 number into UD60x18.
/// @dev There is no overflow check because UD21x18 ⊆ UD60x18.
function intoUD60x18(UD21x18 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(UD21x18.unwrap(x));
}
/// @notice Casts a UD21x18 number into uint128.
/// @dev This is basically an alias for {unwrap}.
function intoUint128(UD21x18 x) pure returns (uint128 result) {
result = UD21x18.unwrap(x);
}
/// @notice Casts a UD21x18 number into uint256.
/// @dev There is no overflow check because UD21x18 ⊆ uint256.
function intoUint256(UD21x18 x) pure returns (uint256 result) {
result = uint256(UD21x18.unwrap(x));
}
/// @notice Casts a UD21x18 number into uint40.
/// @dev Requirements:
/// - x ≤ MAX_UINT40
function intoUint40(UD21x18 x) pure returns (uint40 result) {
uint128 xUint = UD21x18.unwrap(x);
if (xUint > uint128(Common.MAX_UINT40)) {
revert Errors.PRBMath_UD21x18_IntoUint40_Overflow(x);
}
result = uint40(xUint);
}
/// @notice Alias for {wrap}.
function ud21x18(uint128 x) pure returns (UD21x18 result) {
result = UD21x18.wrap(x);
}
/// @notice Unwrap a UD21x18 number into uint128.
function unwrap(UD21x18 x) pure returns (uint128 result) {
result = UD21x18.unwrap(x);
}
/// @notice Wraps a uint128 number into UD21x18.
function wrap(uint128 x) pure returns (UD21x18 result) {
result = UD21x18.wrap(x);
}
lib/prb-math/src/ud21x18/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD21x18 } from "./ValueType.sol";
/// @dev Euler's number as a UD21x18 number.
UD21x18 constant E = UD21x18.wrap(2_718281828459045235);
/// @dev The maximum value a UD21x18 number can have.
uint128 constant uMAX_UD21x18 = 340282366920938463463_374607431768211455;
UD21x18 constant MAX_UD21x18 = UD21x18.wrap(uMAX_UD21x18);
/// @dev PI as a UD21x18 number.
UD21x18 constant PI = UD21x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of UD21x18.
uint256 constant uUNIT = 1e18;
UD21x18 constant UNIT = UD21x18.wrap(1e18);
lib/prb-math/src/ud21x18/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD21x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast a UD21x18 number that doesn't fit in uint40.
error PRBMath_UD21x18_IntoUint40_Overflow(UD21x18 x);
lib/prb-math/src/ud21x18/ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The unsigned 21.18-decimal fixed-point number representation, which can have up to 21 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type uint128. This is useful when end users want to use uint128 to save gas, e.g. with tight variable packing in contract
/// storage.
type UD21x18 is uint128;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD59x18,
Casting.intoUD60x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for UD21x18 global;
lib/prb-math/src/ud2x18/Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { UD2x18 } from "./ValueType.sol";
/// @notice Casts a UD2x18 number into SD59x18.
/// @dev There is no overflow check because UD2x18 ⊆ SD59x18.
function intoSD59x18(UD2x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(uint256(UD2x18.unwrap(x))));
}
/// @notice Casts a UD2x18 number into UD60x18.
/// @dev There is no overflow check because UD2x18 ⊆ UD60x18.
function intoUD60x18(UD2x18 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(UD2x18.unwrap(x));
}
/// @notice Casts a UD2x18 number into uint128.
/// @dev There is no overflow check because UD2x18 ⊆ uint128.
function intoUint128(UD2x18 x) pure returns (uint128 result) {
result = uint128(UD2x18.unwrap(x));
}
/// @notice Casts a UD2x18 number into uint256.
/// @dev There is no overflow check because UD2x18 ⊆ uint256.
function intoUint256(UD2x18 x) pure returns (uint256 result) {
result = uint256(UD2x18.unwrap(x));
}
/// @notice Casts a UD2x18 number into uint40.
/// @dev Requirements:
/// - x ≤ MAX_UINT40
function intoUint40(UD2x18 x) pure returns (uint40 result) {
uint64 xUint = UD2x18.unwrap(x);
if (xUint > uint64(Common.MAX_UINT40)) {
revert Errors.PRBMath_UD2x18_IntoUint40_Overflow(x);
}
result = uint40(xUint);
}
/// @notice Alias for {wrap}.
function ud2x18(uint64 x) pure returns (UD2x18 result) {
result = UD2x18.wrap(x);
}
/// @notice Unwrap a UD2x18 number into uint64.
function unwrap(UD2x18 x) pure returns (uint64 result) {
result = UD2x18.unwrap(x);
}
/// @notice Wraps a uint64 number into UD2x18.
function wrap(uint64 x) pure returns (UD2x18 result) {
result = UD2x18.wrap(x);
}
lib/prb-math/src/ud2x18/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD2x18 } from "./ValueType.sol";
/// @dev Euler's number as a UD2x18 number.
UD2x18 constant E = UD2x18.wrap(2_718281828459045235);
/// @dev The maximum value a UD2x18 number can have.
uint64 constant uMAX_UD2x18 = 18_446744073709551615;
UD2x18 constant MAX_UD2x18 = UD2x18.wrap(uMAX_UD2x18);
/// @dev PI as a UD2x18 number.
UD2x18 constant PI = UD2x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of UD2x18.
UD2x18 constant UNIT = UD2x18.wrap(1e18);
uint64 constant uUNIT = 1e18;
lib/prb-math/src/ud2x18/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD2x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast a UD2x18 number that doesn't fit in uint40.
error PRBMath_UD2x18_IntoUint40_Overflow(UD2x18 x);
lib/prb-math/src/ud2x18/ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The unsigned 2.18-decimal fixed-point number representation, which can have up to 2 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type uint64. This is useful when end users want to use uint64 to save gas, e.g. with tight variable packing in contract
/// storage.
type UD2x18 is uint64;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD59x18,
Casting.intoUD60x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for UD2x18 global;
lib/prb-math/src/ud60x18/Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Errors.sol" as CastingErrors;
import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
import { uMAX_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { uMAX_SD21x18 } from "../sd21x18/Constants.sol";
import { SD21x18 } from "../sd21x18/ValueType.sol";
import { uMAX_SD59x18 } from "../sd59x18/Constants.sol";
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
import { uMAX_UD21x18 } from "../ud21x18/Constants.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { UD21x18 } from "../ud21x18/ValueType.sol";
import { UD60x18 } from "./ValueType.sol";
/// @notice Casts a UD60x18 number into SD1x18.
/// @dev Requirements:
/// - x ≤ uMAX_SD1x18
function intoSD1x18(UD60x18 x) pure returns (SD1x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uint256(int256(uMAX_SD1x18))) {
revert CastingErrors.PRBMath_UD60x18_IntoSD1x18_Overflow(x);
}
result = SD1x18.wrap(int64(uint64(xUint)));
}
/// @notice Casts a UD60x18 number into SD21x18.
/// @dev Requirements:
/// - x ≤ uMAX_SD21x18
function intoSD21x18(UD60x18 x) pure returns (SD21x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uint256(int256(uMAX_SD21x18))) {
revert CastingErrors.PRBMath_UD60x18_IntoSD21x18_Overflow(x);
}
result = SD21x18.wrap(int128(uint128(xUint)));
}
/// @notice Casts a UD60x18 number into UD2x18.
/// @dev Requirements:
/// - x ≤ uMAX_UD2x18
function intoUD2x18(UD60x18 x) pure returns (UD2x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uMAX_UD2x18) {
revert CastingErrors.PRBMath_UD60x18_IntoUD2x18_Overflow(x);
}
result = UD2x18.wrap(uint64(xUint));
}
/// @notice Casts a UD60x18 number into UD21x18.
/// @dev Requirements:
/// - x ≤ uMAX_UD21x18
function intoUD21x18(UD60x18 x) pure returns (UD21x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uMAX_UD21x18) {
revert CastingErrors.PRBMath_UD60x18_IntoUD21x18_Overflow(x);
}
result = UD21x18.wrap(uint128(xUint));
}
/// @notice Casts a UD60x18 number into SD59x18.
/// @dev Requirements:
/// - x ≤ uMAX_SD59x18
function intoSD59x18(UD60x18 x) pure returns (SD59x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uint256(uMAX_SD59x18)) {
revert CastingErrors.PRBMath_UD60x18_IntoSD59x18_Overflow(x);
}
result = SD59x18.wrap(int256(xUint));
}
/// @notice Casts a UD60x18 number into uint128.
/// @dev This is basically an alias for {unwrap}.
function intoUint256(UD60x18 x) pure returns (uint256 result) {
result = UD60x18.unwrap(x);
}
/// @notice Casts a UD60x18 number into uint128.
/// @dev Requirements:
/// - x ≤ MAX_UINT128
function intoUint128(UD60x18 x) pure returns (uint128 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > MAX_UINT128) {
revert CastingErrors.PRBMath_UD60x18_IntoUint128_Overflow(x);
}
result = uint128(xUint);
}
/// @notice Casts a UD60x18 number into uint40.
/// @dev Requirements:
/// - x ≤ MAX_UINT40
function intoUint40(UD60x18 x) pure returns (uint40 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > MAX_UINT40) {
revert CastingErrors.PRBMath_UD60x18_IntoUint40_Overflow(x);
}
result = uint40(xUint);
}
/// @notice Alias for {wrap}.
function ud(uint256 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(x);
}
/// @notice Alias for {wrap}.
function ud60x18(uint256 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(x);
}
/// @notice Unwraps a UD60x18 number into uint256.
function unwrap(UD60x18 x) pure returns (uint256 result) {
result = UD60x18.unwrap(x);
}
/// @notice Wraps a uint256 number into the UD60x18 value type.
function wrap(uint256 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(x);
}
lib/prb-math/src/ud60x18/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD60x18 } from "./ValueType.sol";
// NOTICE: the "u" prefix stands for "unwrapped".
/// @dev Euler's number as a UD60x18 number.
UD60x18 constant E = UD60x18.wrap(2_718281828459045235);
/// @dev The maximum input permitted in {exp}.
uint256 constant uEXP_MAX_INPUT = 133_084258667509499440;
UD60x18 constant EXP_MAX_INPUT = UD60x18.wrap(uEXP_MAX_INPUT);
/// @dev The maximum input permitted in {exp2}.
uint256 constant uEXP2_MAX_INPUT = 192e18 - 1;
UD60x18 constant EXP2_MAX_INPUT = UD60x18.wrap(uEXP2_MAX_INPUT);
/// @dev Half the UNIT number.
uint256 constant uHALF_UNIT = 0.5e18;
UD60x18 constant HALF_UNIT = UD60x18.wrap(uHALF_UNIT);
/// @dev $log_2(10)$ as a UD60x18 number.
uint256 constant uLOG2_10 = 3_321928094887362347;
UD60x18 constant LOG2_10 = UD60x18.wrap(uLOG2_10);
/// @dev $log_2(e)$ as a UD60x18 number.
uint256 constant uLOG2_E = 1_442695040888963407;
UD60x18 constant LOG2_E = UD60x18.wrap(uLOG2_E);
/// @dev The maximum value a UD60x18 number can have.
uint256 constant uMAX_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_584007913129639935;
UD60x18 constant MAX_UD60x18 = UD60x18.wrap(uMAX_UD60x18);
/// @dev The maximum whole value a UD60x18 number can have.
uint256 constant uMAX_WHOLE_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_000000000000000000;
UD60x18 constant MAX_WHOLE_UD60x18 = UD60x18.wrap(uMAX_WHOLE_UD60x18);
/// @dev PI as a UD60x18 number.
UD60x18 constant PI = UD60x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of UD60x18.
uint256 constant uUNIT = 1e18;
UD60x18 constant UNIT = UD60x18.wrap(uUNIT);
/// @dev The unit number squared.
uint256 constant uUNIT_SQUARED = 1e36;
UD60x18 constant UNIT_SQUARED = UD60x18.wrap(uUNIT_SQUARED);
/// @dev Zero as a UD60x18 number.
UD60x18 constant ZERO = UD60x18.wrap(0);
lib/prb-math/src/ud60x18/Conversions.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { uMAX_UD60x18, uUNIT } from "./Constants.sol";
import { PRBMath_UD60x18_Convert_Overflow } from "./Errors.sol";
import { UD60x18 } from "./ValueType.sol";
/// @notice Converts a UD60x18 number to a simple integer by dividing it by `UNIT`.
/// @dev The result is rounded toward zero.
/// @param x The UD60x18 number to convert.
/// @return result The same number in basic integer form.
function convert(UD60x18 x) pure returns (uint256 result) {
result = UD60x18.unwrap(x) / uUNIT;
}
/// @notice Converts a simple integer to UD60x18 by multiplying it by `UNIT`.
///
/// @dev Requirements:
/// - x ≤ MAX_UD60x18 / UNIT
///
/// @param x The basic integer to convert.
/// @return result The same number converted to UD60x18.
function convert(uint256 x) pure returns (UD60x18 result) {
if (x > uMAX_UD60x18 / uUNIT) {
revert PRBMath_UD60x18_Convert_Overflow(x);
}
unchecked {
result = UD60x18.wrap(x * uUNIT);
}
}
lib/prb-math/src/ud60x18/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD60x18 } from "./ValueType.sol";
/// @notice Thrown when ceiling a number overflows UD60x18.
error PRBMath_UD60x18_Ceil_Overflow(UD60x18 x);
/// @notice Thrown when converting a basic integer to the fixed-point format overflows UD60x18.
error PRBMath_UD60x18_Convert_Overflow(uint256 x);
/// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441.
error PRBMath_UD60x18_Exp_InputTooBig(UD60x18 x);
/// @notice Thrown when taking the binary exponent of a base greater than 192e18.
error PRBMath_UD60x18_Exp2_InputTooBig(UD60x18 x);
/// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows UD60x18.
error PRBMath_UD60x18_Gm_Overflow(UD60x18 x, UD60x18 y);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD1x18.
error PRBMath_UD60x18_IntoSD1x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD21x18.
error PRBMath_UD60x18_IntoSD21x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD59x18.
error PRBMath_UD60x18_IntoSD59x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18.
error PRBMath_UD60x18_IntoUD2x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD21x18.
error PRBMath_UD60x18_IntoUD21x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128.
error PRBMath_UD60x18_IntoUint128_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint40.
error PRBMath_UD60x18_IntoUint40_Overflow(UD60x18 x);
/// @notice Thrown when taking the logarithm of a number less than UNIT.
error PRBMath_UD60x18_Log_InputTooSmall(UD60x18 x);
/// @notice Thrown when calculating the square root overflows UD60x18.
error PRBMath_UD60x18_Sqrt_Overflow(UD60x18 x);
lib/prb-math/src/ud60x18/Helpers.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { wrap } from "./Casting.sol";
import { UD60x18 } from "./ValueType.sol";
/// @notice Implements the checked addition operation (+) in the UD60x18 type.
function add(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() + y.unwrap());
}
/// @notice Implements the AND (&) bitwise operation in the UD60x18 type.
function and(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
result = wrap(x.unwrap() & bits);
}
/// @notice Implements the AND (&) bitwise operation in the UD60x18 type.
function and2(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() & y.unwrap());
}
/// @notice Implements the equal operation (==) in the UD60x18 type.
function eq(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() == y.unwrap();
}
/// @notice Implements the greater than operation (>) in the UD60x18 type.
function gt(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() > y.unwrap();
}
/// @notice Implements the greater than or equal to operation (>=) in the UD60x18 type.
function gte(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() >= y.unwrap();
}
/// @notice Implements a zero comparison check function in the UD60x18 type.
function isZero(UD60x18 x) pure returns (bool result) {
// This wouldn't work if x could be negative.
result = x.unwrap() == 0;
}
/// @notice Implements the left shift operation (<<) in the UD60x18 type.
function lshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
result = wrap(x.unwrap() << bits);
}
/// @notice Implements the lower than operation (<) in the UD60x18 type.
function lt(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() < y.unwrap();
}
/// @notice Implements the lower than or equal to operation (<=) in the UD60x18 type.
function lte(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() <= y.unwrap();
}
/// @notice Implements the checked modulo operation (%) in the UD60x18 type.
function mod(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() % y.unwrap());
}
/// @notice Implements the not equal operation (!=) in the UD60x18 type.
function neq(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() != y.unwrap();
}
/// @notice Implements the NOT (~) bitwise operation in the UD60x18 type.
function not(UD60x18 x) pure returns (UD60x18 result) {
result = wrap(~x.unwrap());
}
/// @notice Implements the OR (|) bitwise operation in the UD60x18 type.
function or(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() | y.unwrap());
}
/// @notice Implements the right shift operation (>>) in the UD60x18 type.
function rshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
result = wrap(x.unwrap() >> bits);
}
/// @notice Implements the checked subtraction operation (-) in the UD60x18 type.
function sub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() - y.unwrap());
}
/// @notice Implements the unchecked addition operation (+) in the UD60x18 type.
function uncheckedAdd(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
unchecked {
result = wrap(x.unwrap() + y.unwrap());
}
}
/// @notice Implements the unchecked subtraction operation (-) in the UD60x18 type.
function uncheckedSub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
unchecked {
result = wrap(x.unwrap() - y.unwrap());
}
}
/// @notice Implements the XOR (^) bitwise operation in the UD60x18 type.
function xor(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() ^ y.unwrap());
}
lib/prb-math/src/ud60x18/Math.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { wrap } from "./Casting.sol";
import {
uEXP_MAX_INPUT,
uEXP2_MAX_INPUT,
uHALF_UNIT,
uLOG2_10,
uLOG2_E,
uMAX_UD60x18,
uMAX_WHOLE_UD60x18,
UNIT,
uUNIT,
uUNIT_SQUARED,
ZERO
} from "./Constants.sol";
import { UD60x18 } from "./ValueType.sol";
/*//////////////////////////////////////////////////////////////////////////
MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Calculates the arithmetic average of x and y using the following formula:
///
/// $$
/// avg(x, y) = (x & y) + ((xUint ^ yUint) / 2)
/// $$
///
/// In English, this is what this formula does:
///
/// 1. AND x and y.
/// 2. Calculate half of XOR x and y.
/// 3. Add the two results together.
///
/// This technique is known as SWAR, which stands for "SIMD within a register". You can read more about it here:
/// https://devblogs.microsoft.com/oldnewthing/20220207-00/?p=106223
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// @param x The first operand as a UD60x18 number.
/// @param y The second operand as a UD60x18 number.
/// @return result The arithmetic average as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function avg(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
uint256 yUint = y.unwrap();
unchecked {
result = wrap((xUint & yUint) + ((xUint ^ yUint) >> 1));
}
}
/// @notice Yields the smallest whole number greater than or equal to x.
///
/// @dev This is optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional
/// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x ≤ MAX_WHOLE_UD60x18
///
/// @param x The UD60x18 number to ceil.
/// @return result The smallest whole number greater than or equal to x, as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function ceil(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
if (xUint > uMAX_WHOLE_UD60x18) {
revert Errors.PRBMath_UD60x18_Ceil_Overflow(x);
}
assembly ("memory-safe") {
// Equivalent to `x % UNIT`.
let remainder := mod(x, uUNIT)
// Equivalent to `UNIT - remainder`.
let delta := sub(uUNIT, remainder)
// Equivalent to `x + remainder > 0 ? delta : 0`.
result := add(x, mul(delta, gt(remainder, 0)))
}
}
/// @notice Divides two UD60x18 numbers, returning a new UD60x18 number.
///
/// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
///
/// @param x The numerator as a UD60x18 number.
/// @param y The denominator as a UD60x18 number.
/// @return result The quotient as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function div(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(Common.mulDiv(x.unwrap(), uUNIT, y.unwrap()));
}
/// @notice Calculates the natural exponent of x using the following formula:
///
/// $$
/// e^x = 2^{x * log_2{e}}
/// $$
///
/// @dev Requirements:
/// - x ≤ 133_084258667509499440
///
/// @param x The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
// This check prevents values greater than 192e18 from being passed to {exp2}.
if (xUint > uEXP_MAX_INPUT) {
revert Errors.PRBMath_UD60x18_Exp_InputTooBig(x);
}
unchecked {
// Inline the fixed-point multiplication to save gas.
uint256 doubleUnitProduct = xUint * uLOG2_E;
result = exp2(wrap(doubleUnitProduct / uUNIT));
}
}
/// @notice Calculates the binary exponent of x using the binary fraction method.
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693
///
/// Requirements:
/// - x < 192e18
/// - The result must fit in UD60x18.
///
/// @param x The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp2(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
// Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format.
if (xUint > uEXP2_MAX_INPUT) {
revert Errors.PRBMath_UD60x18_Exp2_InputTooBig(x);
}
// Convert x to the 192.64-bit fixed-point format.
uint256 x_192x64 = (xUint << 64) / uUNIT;
// Pass x to the {Common.exp2} function, which uses the 192.64-bit fixed-point number representation.
result = wrap(Common.exp2(x_192x64));
}
/// @notice Yields the greatest whole number less than or equal to x.
/// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
/// @param x The UD60x18 number to floor.
/// @return result The greatest whole number less than or equal to x, as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function floor(UD60x18 x) pure returns (UD60x18 result) {
assembly ("memory-safe") {
// Equivalent to `x % UNIT`.
let remainder := mod(x, uUNIT)
// Equivalent to `x - remainder > 0 ? remainder : 0)`.
result := sub(x, mul(remainder, gt(remainder, 0)))
}
}
/// @notice Yields the excess beyond the floor of x using the odd function definition.
/// @dev See https://en.wikipedia.org/wiki/Fractional_part.
/// @param x The UD60x18 number to get the fractional part of.
/// @return result The fractional part of x as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function frac(UD60x18 x) pure returns (UD60x18 result) {
assembly ("memory-safe") {
result := mod(x, uUNIT)
}
}
/// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$, rounding down.
///
/// @dev Requirements:
/// - x * y must fit in UD60x18.
///
/// @param x The first operand as a UD60x18 number.
/// @param y The second operand as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function gm(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
uint256 yUint = y.unwrap();
if (xUint == 0 || yUint == 0) {
return ZERO;
}
unchecked {
// Checking for overflow this way is faster than letting Solidity do it.
uint256 xyUint = xUint * yUint;
if (xyUint / xUint != yUint) {
revert Errors.PRBMath_UD60x18_Gm_Overflow(x, y);
}
// We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT`
// during multiplication. See the comments in {Common.sqrt}.
result = wrap(Common.sqrt(xyUint));
}
}
/// @notice Calculates the inverse of x.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x must not be zero.
///
/// @param x The UD60x18 number for which to calculate the inverse.
/// @return result The inverse as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function inv(UD60x18 x) pure returns (UD60x18 result) {
unchecked {
result = wrap(uUNIT_SQUARED / x.unwrap());
}
}
/// @notice Calculates the natural logarithm of x using the following formula:
///
/// $$
/// ln{x} = log_2{x} / log_2{e}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
/// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The UD60x18 number for which to calculate the natural logarithm.
/// @return result The natural logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function ln(UD60x18 x) pure returns (UD60x18 result) {
unchecked {
// Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that
// {log2} can return is ~196_205294292027477728.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E);
}
}
/// @notice Calculates the common logarithm of x using the following formula:
///
/// $$
/// log_{10}{x} = log_2{x} / log_2{10}
/// $$
///
/// However, if x is an exact power of ten, a hard coded value is returned.
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The UD60x18 number for which to calculate the common logarithm.
/// @return result The common logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function log10(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
if (xUint < uUNIT) {
revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x);
}
// Note that the `mul` in this assembly block is the standard multiplication operation, not {UD60x18.mul}.
// prettier-ignore
assembly ("memory-safe") {
switch x
case 1 { result := mul(uUNIT, sub(0, 18)) }
case 10 { result := mul(uUNIT, sub(1, 18)) }
case 100 { result := mul(uUNIT, sub(2, 18)) }
case 1000 { result := mul(uUNIT, sub(3, 18)) }
case 10000 { result := mul(uUNIT, sub(4, 18)) }
case 100000 { result := mul(uUNIT, sub(5, 18)) }
case 1000000 { result := mul(uUNIT, sub(6, 18)) }
case 10000000 { result := mul(uUNIT, sub(7, 18)) }
case 100000000 { result := mul(uUNIT, sub(8, 18)) }
case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
case 1000000000000000000 { result := 0 }
case 10000000000000000000 { result := uUNIT }
case 100000000000000000000 { result := mul(uUNIT, 2) }
case 1000000000000000000000 { result := mul(uUNIT, 3) }
case 10000000000000000000000 { result := mul(uUNIT, 4) }
case 100000000000000000000000 { result := mul(uUNIT, 5) }
case 1000000000000000000000000 { result := mul(uUNIT, 6) }
case 10000000000000000000000000 { result := mul(uUNIT, 7) }
case 100000000000000000000000000 { result := mul(uUNIT, 8) }
case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 59) }
default { result := uMAX_UD60x18 }
}
if (result.unwrap() == uMAX_UD60x18) {
unchecked {
// Inline the fixed-point division to save gas.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10);
}
}
}
/// @notice Calculates the binary logarithm of x using the iterative approximation algorithm:
///
/// $$
/// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2)
/// $$
///
/// For $0 \leq x \lt 1$, the input is inverted:
///
/// $$
/// log_2{x} = -log_2{\frac{1}{x}}
/// $$
///
/// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
///
/// Notes:
/// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal.
///
/// Requirements:
/// - x ≥ UNIT
///
/// @param x The UD60x18 number for which to calculate the binary logarithm.
/// @return result The binary logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function log2(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
if (xUint < uUNIT) {
revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x);
}
unchecked {
// Calculate the integer part of the logarithm.
uint256 n = Common.msb(xUint / uUNIT);
// This is the integer part of the logarithm as a UD60x18 number. The operation can't overflow because
// n is at most 255 and UNIT is 1e18.
uint256 resultUint = n * uUNIT;
// Calculate $y = x * 2^{-n}$.
uint256 y = xUint >> n;
// If y is the unit number, the fractional part is zero.
if (y == uUNIT) {
return wrap(resultUint);
}
// Calculate the fractional part via the iterative approximation.
// The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient.
uint256 doubleUnit = 2e18;
for (uint256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
y = (y * y) / uUNIT;
// Is y^2 >= 2e18 and so in the range [2e18, 4e18)?
if (y >= doubleUnit) {
// Add the 2^{-m} factor to the logarithm.
resultUint += delta;
// Halve y, which corresponds to z/2 in the Wikipedia article.
y >>= 1;
}
}
result = wrap(resultUint);
}
}
/// @notice Multiplies two UD60x18 numbers together, returning a new UD60x18 number.
///
/// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
///
/// @dev See the documentation in {Common.mulDiv18}.
/// @param x The multiplicand as a UD60x18 number.
/// @param y The multiplier as a UD60x18 number.
/// @return result The product as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function mul(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(Common.mulDiv18(x.unwrap(), y.unwrap()));
}
/// @notice Raises x to the power of y.
///
/// For $1 \leq x \leq \infty$, the following standard formula is used:
///
/// $$
/// x^y = 2^{log_2{x} * y}
/// $$
///
/// For $0 \leq x \lt 1$, since the unsigned {log2} is undefined, an equivalent formula is used:
///
/// $$
/// i = \frac{1}{x}
/// w = 2^{log_2{i} * y}
/// x^y = \frac{1}{w}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2} and {mul}.
/// - Returns `UNIT` for 0^0.
/// - It may not perform well with very small values of x. Consider using SD59x18 as an alternative.
///
/// Requirements:
/// - Refer to the requirements in {exp2}, {log2}, and {mul}.
///
/// @param x The base as a UD60x18 number.
/// @param y The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function pow(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
uint256 yUint = y.unwrap();
// If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero.
if (xUint == 0) {
return yUint == 0 ? UNIT : ZERO;
}
// If x is `UNIT`, the result is always `UNIT`.
else if (xUint == uUNIT) {
return UNIT;
}
// If y is zero, the result is always `UNIT`.
if (yUint == 0) {
return UNIT;
}
// If y is `UNIT`, the result is always x.
else if (yUint == uUNIT) {
return x;
}
// If x is > UNIT, use the standard formula.
if (xUint > uUNIT) {
result = exp2(mul(log2(x), y));
}
// Conversely, if x < UNIT, use the equivalent formula.
else {
UD60x18 i = wrap(uUNIT_SQUARED / xUint);
UD60x18 w = exp2(mul(log2(i), y));
result = wrap(uUNIT_SQUARED / w.unwrap());
}
}
/// @notice Raises x (a UD60x18 number) to the power y (an unsigned basic integer) using the well-known
/// algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv18}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - The result must fit in UD60x18.
///
/// @param x The base as a UD60x18 number.
/// @param y The exponent as a uint256.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function powu(UD60x18 x, uint256 y) pure returns (UD60x18 result) {
// Calculate the first iteration of the loop in advance.
uint256 xUint = x.unwrap();
uint256 resultUint = y & 1 > 0 ? xUint : uUNIT;
// Equivalent to `for(y /= 2; y > 0; y /= 2)`.
for (y >>= 1; y > 0; y >>= 1) {
xUint = Common.mulDiv18(xUint, xUint);
// Equivalent to `y % 2 == 1`.
if (y & 1 > 0) {
resultUint = Common.mulDiv18(resultUint, xUint);
}
}
result = wrap(resultUint);
}
/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x ≤ MAX_UD60x18 / UNIT
///
/// @param x The UD60x18 number for which to calculate the square root.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function sqrt(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
unchecked {
if (xUint > uMAX_UD60x18 / uUNIT) {
revert Errors.PRBMath_UD60x18_Sqrt_Overflow(x);
}
// Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two UD60x18 numbers.
// In this case, the two numbers are both the square root.
result = wrap(Common.sqrt(xUint * uUNIT));
}
}
lib/prb-math/src/ud60x18/ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
import "./Helpers.sol" as Helpers;
import "./Math.sol" as Math;
/// @notice The unsigned 60.18-decimal fixed-point number representation, which can have up to 60 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the Solidity type uint256.
/// @dev The value type is defined here so it can be imported in all other files.
type UD60x18 is uint256;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD1x18,
Casting.intoSD21x18,
Casting.intoSD59x18,
Casting.intoUD2x18,
Casting.intoUD21x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for UD60x18 global;
/*//////////////////////////////////////////////////////////////////////////
MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
using {
Math.avg,
Math.ceil,
Math.div,
Math.exp,
Math.exp2,
Math.floor,
Math.frac,
Math.gm,
Math.inv,
Math.ln,
Math.log10,
Math.log2,
Math.mul,
Math.pow,
Math.powu,
Math.sqrt
} for UD60x18 global;
/*//////////////////////////////////////////////////////////////////////////
HELPER FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
using {
Helpers.add,
Helpers.and,
Helpers.eq,
Helpers.gt,
Helpers.gte,
Helpers.isZero,
Helpers.lshift,
Helpers.lt,
Helpers.lte,
Helpers.mod,
Helpers.neq,
Helpers.not,
Helpers.or,
Helpers.rshift,
Helpers.sub,
Helpers.uncheckedAdd,
Helpers.uncheckedSub,
Helpers.xor
} for UD60x18 global;
/*//////////////////////////////////////////////////////////////////////////
OPERATORS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes it possible to use these operators on the UD60x18 type.
using {
Helpers.add as +,
Helpers.and2 as &,
Math.div as /,
Helpers.eq as ==,
Helpers.gt as >,
Helpers.gte as >=,
Helpers.lt as <,
Helpers.lte as <=,
Helpers.or as |,
Helpers.mod as %,
Math.mul as *,
Helpers.neq as !=,
Helpers.not as ~,
Helpers.sub as -,
Helpers.xor as ^
} for UD60x18 global;
src/PHSolver.sol
// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Charu Punjani. Licensed under the Business Source License 1.1.
// PUNZI(TM) and PUNZI WARS(TM) are trademarks of Charu Punjani.
// See LICENSE for full terms.
pragma solidity 0.8.38;
/// @notice Read-only views of the token that calls the solver.
interface ICurveView {
function getBuyCost(uint256 currentK, uint256 tokenAmount) external view returns (uint256);
function cumulativeK() external view returns (uint256);
function totalSupply() external view returns (uint256);
function treasury() external view returns (uint256);
function collateralScale() external view returns (uint256);
}
/**
* @notice Interface of the sell-side book solver.
* @dev `Book` fields: `kk` the lifetime purchase position (cumulativeK), `n` circulating
* supply, `bal` the treasury in 18-decimal units, `tipLow` and `dLow` the stored tip
* position and depth, `elapsed` the time since the stored heal timestamp, scaled to
* HEAL_DURATION.
*/
interface IPHSolver {
struct Book {
uint256 kk;
uint256 n;
uint256 bal;
uint256 tipLow;
uint256 dLow;
uint256 elapsed;
}
function quote(address curve, uint256 tipLow, uint256 dLow, uint256 elapsed, uint256 amount)
external view returns (uint256 seg, uint256 nextTipLow, uint256 nextDepth, uint256 priced);
function HEAL_DURATION() external view returns (uint256);
function canonicalDomains() external view returns (string memory);
}
/**
* @title PHSolver
* @notice Computes the sell-side support book for PUNZI tokens: the tip position, the depth of
* the book below it, and the curve cost of the part of a sale inside the book.
* @dev Stateless, ownerless and read-only. A token calls it with a staticcall and prices the
* sale itself if the call fails or returns an out-of-range answer.
*/
contract PHSolver is IPHSolver {
/// @notice Heal length in seconds (30 minutes). Tokens scale the time since the last sale
/// to it.
uint256 public constant HEAL_DURATION = 1800;
/// @notice The dApp's canonical domains and ENS name, comma-separated.
/// @dev The same value on every PUNZI contract.
function canonicalDomains() external pure returns (string memory) {
return "punzi.xyz,punziwars.com,punzi.eth";
}
/// @dev Curve cost of the window of depth `d` that ends at position `t`. Returns
/// `type(uint256).max` when `d` exceeds the supply `n` or `t`, or the cost saturates.
function _bookAt(ICurveView c, uint256 t, uint256 d, uint256 n) private view returns (uint256) {
if (d > n || d > t) return type(uint256).max;
return d == 0 ? 0 : c.getBuyCost(t - d, d);
}
/// @dev True when the treasury `bal` covers 97% of a book worth `v` (the 3% spread floor).
/// Values above max/97 are not backed.
function _backed(uint256 v, uint256 bal) private pure returns (bool) {
return v <= type(uint256).max / 97 && (v * 97) / 100 <= bal;
}
/// @dev `_backed`, applied to the book with its tip at `t` and depth `d`.
function _fits(ICurveView c, uint256 t, uint256 d, uint256 n, uint256 bal) private view returns (bool) {
return _backed(_bookAt(c, t, d, n), bal);
}
/// @notice Price a sale against the book and return the state it leaves behind.
/// @param curve the calling token; its position, supply and treasury are read from it
/// @param tipLow stored tip position
/// @param dLow stored tip depth
/// @param elapsed time since the stored heal timestamp, scaled by the token to HEAL_DURATION
/// @param amount tokens being sold
/// @return seg curve cost of the part of the sale inside the book, or
/// `type(uint256).max` if it cannot be priced
/// @return nextTipLow tip position after the sale
/// @return nextDepth tip depth after the sale
/// @return priced tokens of the sale inside the book, the part `seg` prices (the
/// whole sale when the sale is larger than the supply)
function quote(address curve, uint256 tipLow, uint256 dLow, uint256 elapsed, uint256 amount)
external view override returns (uint256 seg, uint256 nextTipLow, uint256 nextDepth, uint256 priced)
{
ICurveView c = ICurveView(curve);
return quoteBook(
c,
Book({
kk: c.cumulativeK(),
n: c.totalSupply(),
bal: c.treasury() * c.collateralScale(),
tipLow: tipLow,
dLow: dLow,
elapsed: elapsed
}),
amount
);
}
/// @notice `quote`, for a caller-supplied `Book`.
/// @dev The book is not checked against the curve's state. Tokens use `quote`.
function quoteBook(ICurveView c, Book memory b, uint256 amount)
public view returns (uint256 seg, uint256 nextTipLow, uint256 nextDepth, uint256 priced)
{
(uint256 t, uint256 d) = tipAndDepth(c, b);
if (amount > b.n) {
// A sale larger than the supply cannot be priced: return the sentinel.
seg = type(uint256).max;
priced = amount;
} else {
// The sale walks down from the tip. Tokens past the book's depth are priced at zero.
priced = amount < d ? amount : d;
seg = priced == 0 ? 0 : c.getBuyCost(t - priced, priced);
}
nextTipLow = t > amount ? t - amount : 0;
nextDepth = d > amount ? d - amount : 0;
}
/// @notice The current tip position and the depth of the book below it.
/// @dev Over HEAL_DURATION the tip moves linearly from its stored position to `kk`, and the
/// depth from its stored value to the target `_dmax` gives at that position. The depth
/// takes the target at once when the target is lower or the interpolated depth is not
/// backed. The treasury limits the depth, never the tip's position. The book is not
/// checked against the curve's state.
function tipAndDepth(ICurveView c, Book memory b) public view returns (uint256 t, uint256 d) {
if (b.n == 0) return (0, 0);
if (b.tipLow >= b.kk || b.elapsed >= HEAL_DURATION) t = b.kk;
// If the interpolation would overflow, keep the stored position.
else if (b.elapsed != 0 && (b.kk - b.tipLow) > type(uint256).max / b.elapsed) t = b.tipLow;
else t = b.tipLow + ((b.kk - b.tipLow) * b.elapsed) / HEAL_DURATION;
uint256 dTarget = _dmax(c, b, t);
if (b.dLow >= dTarget || b.elapsed >= HEAL_DURATION) d = dTarget;
else {
// Interpolate; if that would overflow, keep the stored depth. Either way, fall back
// to the target when the result is not backed.
d = b.elapsed != 0 && (dTarget - b.dLow) > type(uint256).max / b.elapsed
? b.dLow
: b.dLow + ((dTarget - b.dLow) * b.elapsed) / HEAL_DURATION;
if (!_fits(c, t, d, b.n, b.bal)) d = dTarget;
}
}
/// @dev Maximum number of steps in the depth search.
uint256 private constant DEPTH_STEPS = 40;
/// @dev The tip depth at position `t`: the full depth (the smaller of the supply and `t`)
/// when that window is backed; otherwise the deepest backed depth the search finds.
/// The search keeps a backed depth `lo` (from zero, the empty window) and an unbacked
/// depth `bad` (from the full depth) and interpolates between them on book value (regula
/// falsi with the Illinois adjustment; bisection when the values are too large to
/// multiply safely). It stops when the backed book is within capB / 2^40 of `capB`, when
/// no depth lies between the two ends, or after DEPTH_STEPS steps.
function _dmax(ICurveView c, Book memory b, uint256 t) private view returns (uint256 lo) {
uint256 bad = b.n > t ? t : b.n;
uint256 vBad = _bookAt(c, t, bad, b.n);
if (_backed(vBad, b.bal)) return bad;
// capB is the largest value `_backed` accepts: `_backed(v)` holds exactly when v <= capB.
uint256 capB = b.bal > (type(uint256).max - 99) / 100 ? type(uint256).max / 97 : (b.bal * 100 + 99) / 97;
// Interpolation weights: each end's distance from capB (the empty window is worth zero).
uint256 wLo = capB;
uint256 wBad = vBad - capB;
uint256 moved; // the end the previous step moved: 1 = lo, 2 = bad
for (uint256 i; i < DEPTH_STEPS && bad - lo > 1; ++i) {
uint256 mid;
{
uint256 w = bad - lo;
// Interpolate only where the product cannot overflow; bisect otherwise.
uint256 step = (w | wLo | wBad) >> 128 == 0 ? (w * wLo) / (wLo + wBad) : w / 2;
if (step == 0) step = 1;
else if (step >= w) step = w - 1;
mid = lo + step;
}
uint256 v = _bookAt(c, t, mid, b.n);
if (_backed(v, b.bal)) {
lo = mid;
wLo = capB - v;
if (wLo <= capB >> 40) break;
if (moved == 1) wBad = (wBad + 1) / 2;
moved = 1;
} else {
bad = mid;
wBad = v - capB;
if (moved == 2) wLo = (wLo + 1) / 2;
moved = 2;
}
}
}
}
src/PUNZI.sol
// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Charu Punjani. Licensed under the Business Source License 1.1.
// PUNZI(TM) and PUNZI WARS(TM) are trademarks of Charu Punjani.
// See LICENSE for full terms.
pragma solidity 0.8.38;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {UD60x18, ud, uEXP2_MAX_INPUT, uLOG2_10} from "@prb/math/UD60x18.sol";
import {mulDiv} from "@prb/math/Common.sol";
import {IPHSolver} from "./PHSolver.sol";
/**
* @title PUNZI
* @notice A bonding-curve token backed by the chain's native currency. `buy` mints tokens
* along the supply curve and keeps the payment, less the 1% fee, in the contract's
* treasury. `sell` burns tokens and pays out of the treasury, less the 3% fee, along
* the sell-side support book. One of 64 deployments across 22 EVM-compatible
* networks (21 primary chains plus Base).
* @dev The sell spread recovers toward a 3% floor over time; medium and large sells set it to
* at least a level that depends on their size. Standard ERC-20 transfers, with no transfer
* tax. Ownership is renounced at deployment. The whitepaper is published at the domains
* returned by `canonicalDomains()`.
*/
contract PUNZI is ERC20, Ownable, ReentrancyGuard {
// Custom errors
error FeeRecipientZero();
/// @notice Thrown by the constructor when minPurchase is below 100.
error MinPurchaseTooSmall();
/// @notice Thrown by the constructor when the collateral decimals are not 18.
error NativeCollateralDecimalsNot18();
/// @notice Thrown by the constructor when the first curve parameter is zero.
error CurveParam1Zero();
/// @notice Thrown by the constructor when curveParam2 is zero (except STEP and HYPERBOLIC).
error CurveParam2Zero();
/// @notice Thrown by the constructor when the STEP multiplier is at most 1 or ln(mult) is zero.
error StepMultiplierTooSmall();
/// @notice Thrown by the constructor when the STEP tier size is zero.
error StepTierSizeZero();
/// @notice Thrown by the constructor when the STEP tier size is below one token.
error StepTierSizeBelowMin();
/// @notice Thrown by the constructor when the HYPERBOLIC Kmax is below one token.
error HyperbolicKmaxTooSmall();
/// @notice Thrown by the constructor when the HYPERBOLIC product a*Kmax is too large.
error HyperbolicAKmaxTooLarge();
/// @notice Thrown by the constructor when the POWER_LAW exponent exceeds POWER_LAW_N_MAX.
error PowerLawExponentTooLarge();
/// @notice Thrown by the constructor when the SIGMOID midpoint S0 is zero.
error SigmoidS0Zero();
/// @notice Thrown by the constructor when the SIGMOID c*S0 is at least EXP_OVERFLOW_THRESHOLD.
error SigmoidSoftplusOverflow();
/// @notice Thrown by the constructor when maturityScale is zero.
error MaturityScaleZero();
/// @notice Thrown by the constructor when maturityScale is below 1e18.
error MaturityScaleTooSmall();
/// @notice Thrown when a buy is below minPurchase.
error BelowMinPurchase();
/// @notice Thrown when the buy fee rounds to zero.
error FeeTooSmall();
/// @notice Thrown when a buy would mint no tokens.
error ZeroTokens();
/// @notice Thrown when a trade gives less than the caller's minimum.
error SlippageExceeded();
/// @notice Thrown when a sale is for zero tokens.
error ZeroAmount();
/// @notice Thrown when the seller holds fewer tokens than the sale amount.
error InsufficientBalance();
/// @notice Thrown when the payment to the seller fails.
error PayoutTransferFailed();
/// @notice Thrown by `getSupportValue` when the amount exceeds a nonzero circulating supply.
error SellExceedsSupply();
/// @notice Thrown by `transferOwnership()`: ownership can only be renounced.
error TransferOwnershipDisabled();
// Enums
/// @notice The 8 supply curve types, which set how the price grows with purchases.
enum SupplyCurve {
// Price formulas, with k the lifetime purchase position:
LINEAR_EXPONENTIAL, // 0 P = m * k * e^(b*k)
POWER_LAW, // 1 P = m * k^n
SIGMOID, // 2 P = L/(1 + e^(-c*(k-S0))) + tau tail
STEP, // 3 P = base * mult^floor(k/tier)
EXPONENTIAL, // 4 P = a * e^(b*k)
HYPERBOLIC, // 5 P = a/(1 - k/Kmax)^3
DUAL_POWER, // 6 P = m * (k^1.5 + B*k^3.5)
ROOT_EXPONENTIAL // 7 P = a * e^(b*sqrt k)
}
/// @notice The 8 support curve types. Each sets the base sell spread, which depends on the
/// token's maturity, and, with the supply curve, the shape factor ψ that scales the
/// payout of larger sells.
enum SupportCurve {
LINEAR_EXPONENTIAL, // g = (1-u)*e^(-T9C_S_L*mHat*u)
POWER_LAW, // g = (1-u)^nu
HYPERBOLIC, // g = ((1-rho)/(1-rho+rho*u))^3
EXPONENTIAL, // g = e^(-T9C_S_E*mHat*u)
SIGMOID, // g = normalized logistic curve with a tail term (see _cardSig)
STEP, // g = step shelves
DUAL_POWER, // g = ((1-u)^1.5 + w*(1-u)^3.5)/(1+w), w = T9C_W_D*mHat^2
ROOT_EXPONENTIAL // g = e^(-T9C_S_R*sqrt(mHat)*(1-sqrt(1-u)))
}
// Constants and series helpers
/// @notice Buy fee in basis points (1%).
uint256 public constant BUY_FEE_BPS = 100;
/// @notice Sell fee in basis points (3%).
uint256 public constant SELL_FEE_BPS = 300;
/// @notice Basis-point denominator.
uint256 public constant BPS_DENOMINATOR = 10_000;
/// @notice Shortest spread recovery after a medium sell: 90 minutes.
uint256 public constant SPREAD_RECOVERY_DURATION = 5400;
/// @notice Spread recovery after a large sell, and the length of Storm: 9 hours.
uint256 public constant STORM_RECOVERY_DURATION = 32_400;
/// @dev Shortest tip recovery after a small sell: 30 minutes.
uint256 private constant TIP_HEAL_DURATION = 1800;
/// @notice Spread floor: 3% (18-decimal fraction).
uint256 public constant MIN_SPREAD = 0.03e18;
// Sell size tiers, compared with total supply before the sale:
// medium (0.01% to under 0.3%): the spread widens to at least MIN_SPREAD + 75% of the
// base spread and recovers over at least 90 minutes;
// large (>= 0.3%): the spread widens to at least MIN_SPREAD + the full base spread and
// recovers over 9 hours (Storm).
// Every sale also lowers the sell-side tip. After a medium or large sale it recovers over
// the spread's recovery; after a small sale, over the time left in a recovery that is still
// running, or over 30 minutes if that is longer. A sale can lengthen a recovery already
// running but never shorten it. Buys never snap the spread or restart its recovery.
/// @notice Denominator of the tier thresholds (parts per million).
uint256 public constant TIER_DENOMINATOR = 1_000_000;
/// @notice Medium-sell threshold: 0.01% of totalSupply.
uint256 public constant RATCHET_TRIGGER_PPM = 100;
/// @notice Large-sell (Storm) threshold: 0.3% of totalSupply.
uint256 public constant STORM_TRIGGER_PPM = 3_000;
uint256 internal constant EXP_OVERFLOW_THRESHOLD = 130e18; // Safe limit for PRBMath exp() (~133 max)
/// @dev DUAL_POWER saturation point for k, in 18-decimal units. It relies on the evaluation
/// order used in `_dualAntideriv`.
uint256 private constant DUAL_K_SATURATION = 6.5e30;
/// @dev SIGMOID tail coefficient (tau = 0.03).
uint256 private constant SIGMOID_TAIL_TAU = 0.03e18;
/// @dev Constructor bound on HYPERBOLIC's a*Kmax product (UD60x18 raw): half the smallest
/// product at which the cost formula overflows.
uint256 private constant HYP_A_KMAX_MAX = 2.6596457305e39;
/// @dev Largest POWER_LAW exponent n for which PRBMath's pow cannot revert for any base below
/// one token (a base of 1 wei is the worst case). Larger bases are bounded by the ln
/// checks in the price and cost functions.
uint256 private constant POWER_LAW_N_MAX = (uEXP2_MAX_INPUT * 1e18) / (18 * uLOG2_10);
/// @dev Saturation bound for the SIGMOID tail term in `_sigmoidPrice`.
uint256 private constant SIGMOID_TAIL_SATURATION = 1.7e47;
/// @dev Below this argument the LEXP, REXP and EXPONENTIAL cost terms use series forms
/// instead of closed-form differences, which lose precision for small values.
uint256 private constant SERIES_U_CROSSOVER = 1e15; // = 1e-3 in 18-dec
/// @dev Largest input PRBMath's sqrt accepts (uMAX_UD60x18 / uUNIT). ROOT_EXPONENTIAL
/// saturates above it instead of reverting.
uint256 private constant SQRT_MAX_INPUT = 115792089237316195423570985008687907853269984665640564039457;
uint256 private constant SMALL_STEP_CROSSOVER = 1e15; // 1e-3: quadrature threshold for small steps
/// @dev Two-point Gauss-Legendre nodes on [0,1]: 1/2 -+ 1/(2*sqrt 3).
uint256 private constant GAUSS2_LO = 211324865405187118;
uint256 private constant GAUSS2_HI = 788675134594812882;
/// @dev S(u) = 1/2 + u/3 + u^2/8 + u^3/30 + u^4/144, the small-u series used by the LEXP and
/// REXP cost terms to avoid cancellation.
function _seriesS(UD60x18 u) private pure returns (UD60x18) {
UD60x18 u2 = u.mul(u);
return ud(0.5e18) + u.div(ud(3e18)) + u2.div(ud(8e18)) + u2.mul(u).div(ud(30e18))
+ u2.mul(u2).div(ud(144e18));
}
/// @dev E(v) = (e^v - 1)/v = 1 + v/2 + v^2/6 + v^3/24 + v^4/120, the small-v series used by
/// the EXPONENTIAL cost and the small-step forms, so that the cost of a small purchase is
/// not rounded to zero.
function _seriesE(UD60x18 v) private pure returns (UD60x18) {
UD60x18 v2 = v.mul(v);
return ud(1e18) + v.div(ud(2e18)) + v2.div(ud(6e18)) + v2.mul(v).div(ud(24e18))
+ v2.mul(v2).div(ud(120e18));
}
/// @dev Saturation threshold for exp inputs in `_softplus` and `_sigmaAt`, just below
/// PRBMath's limit.
uint256 internal constant SOFTPLUS_OVERFLOW_THRESHOLD = 133e18;
// Constants for the support-curve shapes and the base spread (`_ladderG`, `_getBaseSpread`,
// `_mSat`).
uint256 internal constant T9C_S_E = 7945188265645434456;
uint256 internal constant T9C_S_R = 7904403512923135366;
uint256 internal constant T9C_S_L = 4233139843924272228;
uint256 internal constant T9C_N_HAT = 2500000000000000000;
uint256 internal constant T9C_W_D = 11599233591932428311;
uint256 internal constant T9C_R_H = 932177743341965126;
uint256 internal constant T9C_C_S = 9786665809458927612;
uint256 internal constant T9C_THETA_S = 1054798377878377602;
uint256 internal constant T9C_T_S = 36000000000000007105;
uint256 internal constant T9C_MULT_HAT = 1200000000000000000;
uint256 internal constant T9C_M_CAP = 2000000000000000000;
uint256 internal constant T9C_RHO_CAP = 995000000000000000;
uint256 internal constant T9C_N_MIN = 1900000000000000000;
uint256 internal constant T9C_N_MAX = 3100000000000000000;
uint256 internal constant T9C_MULT_MIN = 1200000000000000000;
uint256 internal constant T9C_MULT_MAX = 1300000000000000000;
uint256 internal constant T9C_T_CAP = 350000000000000000000;
uint256 internal constant T9C_LN2 = 693147180559945286;
// Immutables
/// @notice Supply curve type of this token.
SupplyCurve public immutable supplyCurveType;
/// @notice Support curve type of this token.
SupportCurve public immutable supportCurveType;
address payable public immutable buyFeeRecipient;
address payable public immutable sellFeeRecipient;
/// @notice Minimum native amount per buy.
uint256 public immutable minPurchase;
/// @notice Decimal scale factor for the collateral; always 1 for native collateral.
uint256 public immutable collateralScale;
/// @notice First supply curve parameter, in SupplyCurve order: m, m, L, base, a, a, m, a.
uint256 public immutable curveParam1;
/// @notice Second supply curve parameter, in SupplyCurve order: b, n, c, mult, b, Kmax, B, b.
uint256 public immutable curveParam2;
/// @notice Third supply curve parameter, in SupplyCurve order: unused, unused, S0, tier, unused, unused, unused, unused.
uint256 public immutable curveParam3;
/// @notice Maturity denominator for this token: maturity m = cumulativeK / maturityScale.
/// The base sell spread moves with maturity, as do most support shapes (see
/// `_ladderG`).
uint256 public immutable maturityScale;
// Mutable state
/// @notice Total tokens ever bought (the lifetime purchase position). It never decreases,
/// even when tokens are burned, and it sets the supply curve price.
uint256 public cumulativeK;
/// @notice Supply curve price at the lifetime purchase position after the last buy
/// (reported in Buy events).
uint256 public lastPurchasePrice;
/// @notice Time of the last spread snap (medium or large sell). The spread recovers from
/// `lastSnapSpread` toward MIN_SPREAD starting at this time. Before the first such
/// sell it holds the deployment time, and the recovery starts from the base spread.
uint256 public lastRatchetTime;
/// @notice Spread set by the last medium or large sell (18-decimal fraction). Zero until
/// the first such sell.
uint256 public lastSnapSpread;
/// @notice Time of the last large (Storm) sell. Storm lasts STORM_RECOVERY_DURATION
/// (9 hours) from this time; a new large sell restarts it.
uint256 public lastStormTriggerTime;
/// @notice Total collateral received from buys, after fees.
uint256 public totalVolumeIn;
/// @notice Total collateral paid to sellers, after fees.
uint256 public totalVolumeOut;
// Sell-side support book
/// @dev Stored tip position. The tip recovers from here toward `cumulativeK` over the
/// current recovery (`healWindowPH`); the treasury limits its depth, not its position.
uint256 internal tipLowPH;
/// @dev Stored tip depth; the live depth, counted down from the tip, is computed from it.
uint256 internal tipDepthPH;
/// @dev Time the last sale set the tip; the tip's recovery runs from here. Only sales
/// write it.
uint40 internal healTimePH;
/// @dev Length of the tip's current recovery in seconds (zero before any sale). After a
/// medium or large sale it matches the spread's; after a small sale it is the longer
/// of 30 minutes and the time left in a running recovery.
uint32 internal healWindowPH;
/// @notice The sell-side book solver. If a call to it fails or answers out of range, the
/// token prices the sale itself.
IPHSolver public immutable phSolver;
// Other mutable state
/// @notice Length of the current spread recovery in seconds: 90 minutes after a medium
/// sell, 9 hours after a large one. A sale during a running recovery keeps the
/// longer duration.
uint32 public spreadRecoveryDuration;
/// @notice Number of distinct addresses that have bought.
uint256 public uniqueBuyerCount;
/// @dev Tracks whether an address has already been counted in uniqueBuyerCount.
mapping(address => bool) private _hasBought;
// Events
/// @notice Emitted by a buy. `nativeIn` includes the fee; `pricePerToken` is the curve price
/// after the buy.
event Buy(address indexed buyer, uint256 nativeIn, uint256 tokensMinted, uint256 pricePerToken, uint256 fee);
/// @notice Emitted by a sale. `nativeOut` is the seller's payout after the fee;
/// `pricePerToken` is the seller's average price per token after fees.
event Sell(address indexed seller, uint256 tokensBurned, uint256 nativeOut, uint256 pricePerToken, uint256 fee);
/// @notice Emitted when a large sell starts Storm. Storm ends 9 hours after the last large
/// sell, with no event.
event StormModeActivated(uint256 timestamp);
// Constructor and receive
/// @param _name Token name.
/// @param _symbol Token symbol (e.g., "PUNZI-ETH").
/// @param _supplyCurve Supply curve type.
/// @param _supportCurve Support curve type.
/// @param _minPurchase Minimum native amount per buy.
/// @param _collateralDecimals Decimals of the native currency (must be 18).
/// @param _curveParams The three supply curve parameters (18-decimal fixed point).
/// @param _maturityScale Maturity denominator: maturity m = cumulativeK / _maturityScale.
/// @param _phSolver The sell-side book solver.
constructor(
string memory _name,
string memory _symbol,
SupplyCurve _supplyCurve,
SupportCurve _supportCurve,
address payable[2] memory _feeRecipients,
uint256 _minPurchase,
uint8 _collateralDecimals,
uint256[3] memory _curveParams,
uint256 _maturityScale,
IPHSolver _phSolver
) ERC20(_name, _symbol) Ownable(msg.sender) {
if (_feeRecipients[0] == address(0) || _feeRecipients[1] == address(0)) revert FeeRecipientZero();
// minPurchase must be at least 100 so the 1% fee on a minimum purchase is not zero.
if (_minPurchase < BPS_DENOMINATOR / BUY_FEE_BPS) revert MinPurchaseTooSmall();
if (_collateralDecimals != 18) revert NativeCollateralDecimalsNot18();
supplyCurveType = _supplyCurve;
supportCurveType = _supportCurve;
buyFeeRecipient = _feeRecipients[0];
sellFeeRecipient = _feeRecipients[1];
minPurchase = _minPurchase;
collateralScale = 10 ** (18 - _collateralDecimals);
curveParam1 = _curveParams[0];
curveParam2 = _curveParams[1];
curveParam3 = _curveParams[2];
if (_curveParams[0] == 0) revert CurveParam1Zero();
if (_supplyCurve == SupplyCurve.STEP) {
// The `<= 1e18` check runs first because ln() reverts below one.
if (_curveParams[1] <= 1e18 || ud(_curveParams[1]).ln().unwrap() == 0) {
revert StepMultiplierTooSmall();
}
if (_curveParams[2] == 0) revert StepTierSizeZero();
if (_curveParams[2] < 1e18) revert StepTierSizeBelowMin();
}
if (_supplyCurve == SupplyCurve.HYPERBOLIC) {
if (_curveParams[1] < 1e18) revert HyperbolicKmaxTooSmall();
// Bound a*Kmax without forming the product, so this check cannot overflow itself.
if (_curveParams[0] > (HYP_A_KMAX_MAX * 1e18) / _curveParams[1]) {
revert HyperbolicAKmaxTooLarge();
}
}
// STEP and HYPERBOLIC have already rejected a zero curveParam2 above.
if (_curveParams[1] == 0) revert CurveParam2Zero();
if (_supplyCurve == SupplyCurve.POWER_LAW) {
if (_curveParams[1] > POWER_LAW_N_MAX) revert PowerLawExponentTooLarge();
}
if (_supplyCurve == SupplyCurve.SIGMOID) {
if (_curveParams[2] == 0) revert SigmoidS0Zero();
if (ud(_curveParams[1]).mul(ud(_curveParams[2])).unwrap() >= EXP_OVERFLOW_THRESHOLD) {
revert SigmoidSoftplusOverflow();
}
}
if (_maturityScale == 0) revert MaturityScaleZero();
if (_maturityScale < 1e18) revert MaturityScaleTooSmall();
maturityScale = _maturityScale;
phSolver = _phSolver;
lastRatchetTime = block.timestamp;
spreadRecoveryDuration = uint32(SPREAD_RECOVERY_DURATION);
}
/// @notice Accept direct native currency transfers, which add to the treasury.
receive() external payable {}
// Core functions
/// @notice Buy with the caller's estimate of the tokens the payment buys.
/// @dev The estimate is used only if its curve cost is at most the payment after the fee;
/// otherwise the contract finds the amount itself, as `buy` does. An estimate that is
/// too low mints fewer tokens than the payment could buy.
/// @param minTokensOut Minimum tokens to receive
/// @param tokensHint Estimated tokens for this payment, for example
/// `getTokensForExactCost(cumulativeK(), msg.value - (msg.value * BUY_FEE_BPS) / BPS_DENOMINATOR)`.
/// Pass 0 to skip the estimate.
function buyWithHint(uint256 minTokensOut, uint256 tokensHint) external payable nonReentrant {
_buy(minTokensOut, tokensHint);
}
/// @notice Buy PUNZI tokens with the native currency.
/// @dev The 1% fee is taken from msg.value; the rest stays in the treasury and is priced on
/// the supply curve.
/// @param minTokensOut Minimum tokens to receive
function buy(uint256 minTokensOut) external payable nonReentrant {
_buy(minTokensOut, 0);
}
/// @dev Shared buy logic. A zero hint uses the search.
function _buy(uint256 minTokensOut, uint256 tokensHint) private {
if (msg.value < minPurchase) revert BelowMinPurchase();
uint256 fee = (msg.value * BUY_FEE_BPS) / BPS_DENOMINATOR;
uint256 purchaseValue = msg.value - fee;
if (fee == 0) revert FeeTooSmall();
uint256 normalizedValue = purchaseValue * collateralScale;
uint256 tokensOut;
if (tokensHint != 0 && _affordable(cumulativeK, tokensHint, normalizedValue)) tokensOut = tokensHint;
if (tokensOut == 0) tokensOut = getTokensForExactCost(cumulativeK, normalizedValue);
if (tokensOut == 0) revert ZeroTokens();
if (tokensOut < minTokensOut) revert SlippageExceeded();
// Safe: an amount whose end position would overflow is priced at the sentinel and rejected.
unchecked { cumulativeK += tokensOut; }
lastPurchasePrice = getSupplyCurvePrice(cumulativeK);
totalVolumeIn += purchaseValue;
if (!_hasBought[msg.sender]) {
_hasBought[msg.sender] = true;
uniqueBuyerCount++;
}
_mint(msg.sender, tokensOut);
_phCommitBuy(tokensOut);
// The 1% fee.
address feeTo = buyFeeRecipient;
assembly ("memory-safe") {
pop(call(gas(), feeTo, fee, 0x00, 0x00, 0x00, 0x00))
}
emit Buy(msg.sender, msg.value, tokensOut, lastPurchasePrice, fee);
}
/// @notice Sell PUNZI tokens to the contract.
/// @dev The tokens are burned. The payout comes from the treasury, less the 3% fee. Tokens
/// past the depth of the support book are priced at zero, so the payout can be zero, and a
/// zero payout does not by itself revert the sale.
/// @param amount Number of tokens to sell
/// @param minValueOut Minimum native amount to receive
function sell(uint256 amount, uint256 minValueOut) external nonReentrant {
if (amount == 0) revert ZeroAmount();
if (balanceOf(msg.sender) < amount) revert InsufficientBalance();
uint256 supplyAtSell = totalSupply();
uint256 amountScaled = amount * TIER_DENOMINATOR;
bool aboveStormThreshold = amountScaled >= supplyAtSell * STORM_TRIGGER_PPM;
bool aboveRatchetThreshold = amountScaled >= supplyAtSell * RATCHET_TRIGGER_PPM;
// The sale is priced at the spread in effect before it.
(uint256 grossPayout, uint256 phNextTip, uint256 phNextDepth) =
_supportValueAndNext(amount);
// Deduct the 3% fee.
uint256 fee = (grossPayout * SELL_FEE_BPS) / BPS_DENOMINATOR;
uint256 sellerPayout = grossPayout - fee;
if (sellerPayout < minValueOut) revert SlippageExceeded();
if (aboveRatchetThreshold) {
uint256 maturity = ud(cumulativeK).div(ud(maturityScale)).unwrap();
uint256 base = _getBaseSpread(maturity);
uint256 target = MIN_SPREAD + (aboveStormThreshold ? base : (base * 3) / 4);
uint256 current = getSupportSpread(maturity);
if (target < current) target = current;
// Use the longer duration while its recovery is still running.
uint256 spreadDur = aboveStormThreshold ? STORM_RECOVERY_DURATION : SPREAD_RECOVERY_DURATION;
if (current > MIN_SPREAD && spreadRecoveryDuration > spreadDur) {
spreadDur = spreadRecoveryDuration;
}
lastSnapSpread = target;
lastRatchetTime = block.timestamp;
// Safe cast: spreadDur is 5400, 32400 or a value this field already held.
spreadRecoveryDuration = uint32(spreadDur);
// The tip and depth recover over the same window.
healWindowPH = uint32(spreadDur);
if (aboveStormThreshold) {
if (!stormMode()) {
emit StormModeActivated(block.timestamp);
}
lastStormTriggerTime = block.timestamp;
}
} else {
// A small sale: the tip recovers over max(30 minutes, time left in the running recovery).
uint256 running = healWindowPH;
unchecked {
uint256 since = block.timestamp > healTimePH ? block.timestamp - healTimePH : 0;
// Safe cast: the result is 1800 or at most a value this field already held.
healWindowPH = uint32(running > since + TIP_HEAL_DURATION ? running - since : TIP_HEAL_DURATION);
}
}
// Store the tip state this sale leaves and restart its recovery.
tipLowPH = phNextTip;
tipDepthPH = phNextDepth;
healTimePH = uint40(block.timestamp);
_burn(msg.sender, amount);
totalVolumeOut += sellerPayout;
// Pay the seller; return data is not copied.
if (sellerPayout > 0) {
bool payoutSuccess;
assembly ("memory-safe") {
payoutSuccess := call(gas(), caller(), sellerPayout, 0x00, 0x00, 0x00, 0x00)
}
if (!payoutSuccess) revert PayoutTransferFailed();
}
// The 3% fee.
if (fee > 0) {
address feeTo = sellFeeRecipient;
assembly ("memory-safe") {
pop(call(gas(), feeTo, fee, 0x00, 0x00, 0x00, 0x00))
}
}
uint256 effectivePricePerToken = (sellerPayout * collateralScale * 1e18) / amount;
emit Sell(msg.sender, amount, sellerPayout, effectivePricePerToken, fee);
}
/// @notice Disabled: ownership can only be renounced, never transferred.
function transferOwnership(address) public pure override {
revert TransferOwnershipDisabled();
}
// Supply curve
/// @notice Price per token at lifetime purchase position `k`.
/// @dev Depends only on `k` and the immutable curve parameters.
/// @param k Position on the supply curve (18-decimal; 1 token = 1e18)
/// @return price Price per token in collateral units (18 decimals), or `type(uint256).max`
/// when it is too large to represent; with extreme inputs or curve parameters the call
/// can revert instead
function getSupplyCurvePrice(uint256 k) public view returns (uint256 price) {
SupplyCurve ct = supplyCurveType;
if (ct == SupplyCurve.LINEAR_EXPONENTIAL) {
UD60x18 uP = ud(curveParam2).mul(ud(k));
if (uP.unwrap() > EXP_OVERFLOW_THRESHOLD) return type(uint256).max;
UD60x18 mL = ud(curveParam1);
if (_mulDiv18WouldOverflow(mL, ud(k))) return type(uint256).max;
UD60x18 mkL = mL.mul(ud(k));
UD60x18 eU = uP.exp();
return _mulOrSat(mkL, eU);
}
if (ct == SupplyCurve.POWER_LAW) {
// ln() reverts below one, so the overflow check runs only for k >= 1e18.
UD60x18 kk = ud(k);
if (k >= 1e18) {
if (kk.ln().mul(ud(curveParam2)).unwrap() > EXP_OVERFLOW_THRESHOLD) {
return type(uint256).max;
}
}
UD60x18 kPowP = kk.pow(ud(curveParam2));
return _mulOrSat(ud(curveParam1), kPowP);
}
if (ct == SupplyCurve.SIGMOID) {
return _sigmoidPrice(k);
}
if (ct == SupplyCurve.STEP) {
UD60x18 tierIndex = ud(k).div(ud(curveParam3)).floor();
UD60x18 lnMult = ud(curveParam2).ln();
if (lnMult.mul(tierIndex).unwrap() > EXP_OVERFLOW_THRESHOLD) return type(uint256).max;
UD60x18 pwS = ud(curveParam2).pow(tierIndex);
return _mulOrSat(ud(curveParam1), pwS);
}
if (ct == SupplyCurve.EXPONENTIAL) {
UD60x18 exponent = ud(curveParam2).mul(ud(k));
if (exponent.unwrap() > EXP_OVERFLOW_THRESHOLD) return type(uint256).max;
UD60x18 eE = exponent.exp();
return _mulOrSat(ud(curveParam1), eE);
}
if (ct == SupplyCurve.HYPERBOLIC) {
// P = a/(1-k/Kmax)^3 = a*w^3, w = Kmax/(Kmax-k).
uint256 kmaxP = curveParam2;
if (k >= kmaxP) return type(uint256).max;
UD60x18 w = ud(kmaxP).div(ud(kmaxP - k));
if (ud(3e18).mul(w.ln()).unwrap() > EXP_OVERFLOW_THRESHOLD) return type(uint256).max;
UD60x18 w3 = w.powu(3);
return _mulOrSat(ud(curveParam1), w3);
}
if (ct == SupplyCurve.DUAL_POWER) {
// Powers are built from square roots; k^3.5 is formed before B is applied.
if (k > DUAL_K_SATURATION) return type(uint256).max;
UD60x18 kk = ud(k);
UD60x18 rt = kk.sqrt();
UD60x18 k15 = kk.mul(rt);
UD60x18 k35 = kk.mul(kk).mul(kk).mul(rt);
if (_mulDiv18WouldOverflow(ud(curveParam2), k35)) return type(uint256).max;
UD60x18 bk35 = ud(curveParam2).mul(k35);
if (bk35.unwrap() > type(uint256).max - k15.unwrap()) return type(uint256).max;
UD60x18 innerD = k15 + bk35;
return _mulOrSat(ud(curveParam1), innerD);
}
// SupplyCurve.ROOT_EXPONENTIAL
{
if (k > SQRT_MAX_INPUT) return type(uint256).max;
UD60x18 uR = ud(curveParam2).mul(ud(k).sqrt());
if (uR.unwrap() > EXP_OVERFLOW_THRESHOLD) return type(uint256).max;
UD60x18 eR = uR.exp();
return _mulOrSat(ud(curveParam1), eR);
}
}
/// @dev Subtraction clamped at zero, for differences that are non-negative in exact
/// arithmetic but can invert by rounding.
function _monoSub(UD60x18 hi, UD60x18 lo) private pure returns (UD60x18) {
return hi.unwrap() >= lo.unwrap() ? hi - lo : ud(0);
}
/// @dev Antiderivative of m*x*e^(b*x) = (m/b^2)*[e^(bx)(bx-1)+1], arranged so every term is
/// non-negative. Divides by b twice instead of by b*b, which would round to zero for
/// small b.
function _lexpAntideriv(UD60x18 m, UD60x18 b, UD60x18 x) private pure returns (UD60x18) {
UD60x18 u = b.mul(x);
// For small u the closed form loses its digits to cancellation; use the series instead.
if (u.unwrap() < SERIES_U_CROSSOVER) {
return m.mul(x).mul(x).mul(_seriesS(u));
}
UD60x18 ONE_ = ud(1e18);
UD60x18 eu = u.exp();
UD60x18 bracket = u.unwrap() < 1e18 ? _monoSub(ONE_, eu.mul(ONE_ - u)) : ONE_ + eu.mul(u - ONE_);
// Divide by b twice without first rounding m * bracket down to 18 decimals:
// floor(floor(m * bracket / b) * 1e18 / b) on the raw values.
return ud(mulDiv(mulDiv(m.unwrap(), bracket.unwrap(), b.unwrap()), 1e18, b.unwrap()));
}
/// @dev Antiderivative of m*(x^1.5 + B*x^3.5), built from square roots. x^4.5 is
/// formed before B (`beta`) is applied.
function _dualAntideriv(UD60x18 m, UD60x18 beta, UD60x18 x) private pure returns (UD60x18) {
UD60x18 rt = x.sqrt();
UD60x18 x2 = x.mul(x);
return m.mul(x2.mul(rt).div(ud(2.5e18)) + beta.mul(x2.mul(x2).mul(rt)).div(ud(4.5e18)));
}
/// @dev Antiderivative of a*e^(b*sqrt(x)) = (2a/b^2)*(u*e^u - (e^u - 1)), u = b*sqrt(x).
/// Arranged so every term is non-negative.
function _rexpAntideriv(UD60x18 a_, UD60x18 b_, UD60x18 x) private pure returns (UD60x18) {
UD60x18 u = b_.mul(x.sqrt());
// For small u, use the same series as _lexpAntideriv.
if (u.unwrap() < SERIES_U_CROSSOVER) {
return a_.mul(ud(2e18)).mul(x).mul(_seriesS(u));
}
UD60x18 eu = u.exp();
UD60x18 bracket = _monoSub(u.mul(eu), _monoSub(eu, ud(1e18)));
return ud(_rexpScale(a_, b_, bracket));
}
/// @dev floor(2*a*bracket*1e18 / b^2) on raw values, computed without overflow;
/// saturates if the result does not fit.
function _rexpScale(UD60x18 a_, UD60x18 b_, UD60x18 bracket) private pure returns (uint256) {
unchecked {
uint256 doubled = a_.unwrap() * 2;
uint256 denominator = b_.unwrap() * b_.unwrap();
if (_mulDivWouldOverflow(doubled, bracket.unwrap(), denominator)) return type(uint256).max;
uint256 quotient = mulDiv(doubled, bracket.unwrap(), denominator);
if (quotient > type(uint256).max / 1e18) return type(uint256).max;
uint256 scaled = quotient * 1e18;
uint256 tail = mulDiv(mulmod(doubled, bracket.unwrap(), denominator), 1e18, denominator);
if (tail > type(uint256).max - scaled) return type(uint256).max;
return scaled + tail;
}
}
/// @dev tau*L*(y - S0)^2 / (2*S0): the tail term's contribution to the buy integral. Zero
/// at and below S0. Callers check the input range first.
function _sigTail(UD60x18 y, UD60x18 s0, UD60x18 L) private pure returns (UD60x18) {
if (y.unwrap() <= s0.unwrap()) return ud(0);
UD60x18 e = y - s0;
return ud(SIGMOID_TAIL_TAU).mul(L).mul(e).mul(e).div(s0).div(ud(2e18));
}
/// @dev True when the UD60x18 product a*b (a*b/1e18) would not fit in uint256. It may
/// report overflow early, never late.
function _mulDiv18WouldOverflow(UD60x18 a_, UD60x18 b_) private pure returns (bool) {
uint256 ar = a_.unwrap();
if (ar == 0) return false;
uint256 q = type(uint256).max / ar;
// Threshold beyond any representable operand: the product cannot overflow.
if (q > type(uint256).max / 1e18) return false;
return b_.unwrap() > q * 1e18;
}
/// @dev a*b, or type(uint256).max when the product would overflow.
function _mulOrSat(UD60x18 a_, UD60x18 b_) private pure returns (uint256) {
if (_mulDiv18WouldOverflow(a_, b_)) return type(uint256).max;
return a_.mul(b_).unwrap();
}
/// @dev Integral of the price over [k, k + x] by two-point Gauss-Legendre quadrature, used
/// for small steps where the closed-form difference loses precision. Saturates if the
/// price at either quadrature point saturates.
function _gauss2Integral(UD60x18 k, UD60x18 x) private view returns (uint256) {
uint256 pLo = getSupplyCurvePrice((k + x.mul(ud(GAUSS2_LO))).unwrap());
uint256 pHi = getSupplyCurvePrice((k + x.mul(ud(GAUSS2_HI))).unwrap());
if (pLo == type(uint256).max || pHi == type(uint256).max) return type(uint256).max;
if (pHi > type(uint256).max - pLo) return type(uint256).max;
UD60x18 avg = (ud(pLo) + ud(pHi)).div(ud(2e18));
if (_mulDiv18WouldOverflow(x, avg)) return type(uint256).max;
return x.mul(avg).unwrap();
}
/// @dev True when the UD60x18 division a/b would not fit in uint256, or b is zero. Checked
/// by division so the check itself cannot overflow; it may report overflow slightly
/// early.
function _divWouldOverflow(UD60x18 a_, UD60x18 b_) private pure returns (bool) {
uint256 br = b_.unwrap();
if (br == 0) return true;
return a_.unwrap() / br >= type(uint256).max / 1e18;
}
/// @dev True when PRBMath mulDiv(a, b, denominator) would revert: the denominator is zero, or the
/// high limb of the 512-bit product is at least the denominator.
function _mulDivWouldOverflow(uint256 a_, uint256 b_, uint256 denominator) private pure returns (bool) {
if (denominator == 0) return true;
uint256 high;
assembly ("memory-safe") {
let low := mul(a_, b_)
let mm := mulmod(a_, b_, not(0))
high := sub(sub(mm, low), lt(mm, low))
}
return high >= denominator;
}
/// @dev LINEAR_EXPONENTIAL cost for a small step: T = m*n*e^(b*k) * [k*E(v) + n*S(v)],
/// v = b*n. An exact rearrangement of the antiderivative difference in which the
/// divisions by b cancel, so it keeps its precision when the step is small.
function _lexpSmallStep(UD60x18 m, UD60x18 b, UD60x18 k, UD60x18 n, UD60x18 v)
private
pure
returns (uint256)
{
UD60x18 inner = k.mul(_seriesE(v)) + n.mul(_seriesS(v));
UD60x18 eK = b.mul(k).exp();
// Multiply by the step n last to keep precision.
if (_mulDiv18WouldOverflow(m, inner)) return type(uint256).max;
UD60x18 t = m.mul(inner);
if (_mulDiv18WouldOverflow(t, eK)) return type(uint256).max;
t = t.mul(eK);
if (_mulDiv18WouldOverflow(t, n)) return type(uint256).max;
return t.mul(n).unwrap();
}
/// @dev ROOT_EXPONENTIAL cost for a small step:
/// T = 2a*e^(b*sqrt k) * n * [sqrt(k)*E(w) + d*S(w)] / (sqrt(kn) + sqrt(k)),
/// kn = k + n, d = n / (sqrt(kn) + sqrt(k)), w = b*d. An exact rearrangement in which the
/// divisions by b cancel; d is computed without subtracting two square roots.
function _rexpSmallStep(UD60x18 a_, UD60x18 b_, UD60x18 rk, UD60x18 n, UD60x18 denom)
private
pure
returns (uint256)
{
UD60x18 d = n.div(denom);
UD60x18 w = b_.mul(d);
UD60x18 inner = rk.mul(_seriesE(w)) + d.mul(_seriesS(w));
UD60x18 t = a_.mul(ud(2e18));
UD60x18 eK = b_.mul(rk).exp();
if (_mulDiv18WouldOverflow(t, eK)) return type(uint256).max;
t = t.mul(eK);
if (_mulDiv18WouldOverflow(t, n)) return type(uint256).max;
t = t.mul(n);
if (_mulDiv18WouldOverflow(t, inner)) return type(uint256).max;
// The final division needs no overflow check: inner / denom is at most max(E(w)/2, S(w)),
// about one half for the small w used here, so the result stays below t.
return t.mul(inner).div(denom).unwrap();
}
/// @notice Cost to buy `tokenAmount` tokens starting at position `currentK`.
/// @dev Closed-form integrals of the price, with series or quadrature for small steps.
/// Returns `type(uint256).max` when the cost is too large to represent; with extreme
/// inputs or curve parameters the call can revert instead.
/// @param currentK Starting position (18-decimal)
/// @param tokenAmount Tokens to buy (18-decimal)
/// @return cost Cost in collateral units (18 decimals)
function getBuyCost(uint256 currentK, uint256 tokenAmount) public view returns (uint256 cost) {
if (tokenAmount == 0) return 0;
if (tokenAmount > type(uint256).max - currentK) return type(uint256).max;
SupplyCurve ct = supplyCurveType;
UD60x18 k = ud(currentK);
UD60x18 n = ud(tokenAmount);
UD60x18 kn = k + n;
if (ct == SupplyCurve.LINEAR_EXPONENTIAL) {
UD60x18 mL = ud(curveParam1);
UD60x18 bL = ud(curveParam2);
if (_mulDiv18WouldOverflow(bL, kn)) return type(uint256).max;
UD60x18 uHi = bL.mul(kn);
if (uHi.unwrap() > EXP_OVERFLOW_THRESHOLD) return type(uint256).max;
UD60x18 bHi = uHi.unwrap() < 1e18
? _monoSub(ud(1e18), uHi.exp().mul(ud(1e18) - uHi))
: ud(1e18) + uHi.exp().mul(uHi - ud(1e18));
// Check each mulDiv quotient for overflow before computing it.
if (_mulDivWouldOverflow(mL.unwrap(), bHi.unwrap(), bL.unwrap())) return type(uint256).max;
uint256 mbH = mulDiv(mL.unwrap(), bHi.unwrap(), bL.unwrap());
if (_mulDivWouldOverflow(mbH, 1e18, bL.unwrap())) return type(uint256).max;
UD60x18 vL = bL.mul(n);
if (vL.unwrap() < SERIES_U_CROSSOVER) return _lexpSmallStep(mL, bL, k, n, vL);
return _monoSub(_lexpAntideriv(mL, bL, kn), _lexpAntideriv(mL, bL, k)).unwrap();
}
if (ct == SupplyCurve.POWER_LAW) {
// T = m*(kn^(p+1) - k^(p+1))/(p+1), p the exponent and kn = k + n. k^(p+1) is
// computed as pow(k, p) * k, since p+1 can exceed the exponent range of PRBMath's pow.
UD60x18 mP = ud(curveParam1);
UD60x18 nP = ud(curveParam2);
UD60x18 p1 = nP + ud(1e18);
if (kn.unwrap() >= 1e18) {
if (kn.ln().mul(p1).unwrap() > EXP_OVERFLOW_THRESHOLD) return type(uint256).max;
}
if (k.unwrap() > 0 && n.div(k).unwrap() < SMALL_STEP_CROSSOVER) return _gauss2Integral(k, n);
UD60x18 knPow = kn.pow(nP);
if (_mulDiv18WouldOverflow(knPow, kn)) return type(uint256).max;
UD60x18 hiP = knPow.mul(kn);
UD60x18 kPow = k.pow(nP);
if (_mulDiv18WouldOverflow(kPow, k)) return type(uint256).max;
UD60x18 loP = kPow.mul(k);
UD60x18 diffP = _monoSub(hiP, loP);
if (_mulDiv18WouldOverflow(mP, diffP)) return type(uint256).max;
return mP.mul(diffP).div(p1).unwrap();
}
if (ct == SupplyCurve.SIGMOID) {
// T = (L/c)*[softplus(c(kn-S0)) - softplus(c(k-S0))] plus the tail term.
UD60x18 L = ud(curveParam1);
UD60x18 c = ud(curveParam2);
UD60x18 s0 = ud(curveParam3);
// Above S0, check each product of the tail term for overflow before forming it.
if (kn.unwrap() > s0.unwrap()) {
UD60x18 e = kn - s0;
UD60x18 tauL = ud(SIGMOID_TAIL_TAU).mul(L);
if (_mulDiv18WouldOverflow(tauL, e)) return type(uint256).max;
UD60x18 te = tauL.mul(e);
if (_mulDiv18WouldOverflow(te, e)) return type(uint256).max;
if (_divWouldOverflow(te.mul(e), s0)) return type(uint256).max;
}
if (c.mul(n).unwrap() < SMALL_STEP_CROSSOVER) return _gauss2Integral(k, n);
UD60x18 upper_ = _softplus(c, kn, s0);
UD60x18 lower_ = _softplus(c, k, s0);
UD60x18 logistic = L.mul(_monoSub(upper_, lower_)).div(c);
UD60x18 tailDiff = _monoSub(_sigTail(kn, s0, L), _sigTail(k, s0, L));
if (logistic.unwrap() > type(uint256).max - tailDiff.unwrap()) return type(uint256).max;
return (logistic + tailDiff).unwrap();
}
if (ct == SupplyCurve.STEP) {
return _stepCost(currentK, tokenAmount);
}
if (ct == SupplyCurve.EXPONENTIAL) {
UD60x18 a = ud(curveParam1);
UD60x18 b = ud(curveParam2);
UD60x18 bkn = b.mul(kn);
if (bkn.unwrap() > EXP_OVERFLOW_THRESHOLD) return type(uint256).max;
UD60x18 v = b.mul(n);
if (v.unwrap() < SERIES_U_CROSSOVER) {
return a.mul((b.mul(k)).exp()).mul(n).mul(_seriesE(v)).unwrap();
}
UD60x18 upper_ = bkn.exp();
UD60x18 lower_ = (b.mul(k)).exp();
UD60x18 diff_ = _monoSub(upper_, lower_);
if (_mulDiv18WouldOverflow(a, diff_)) return type(uint256).max;
UD60x18 num_ = a.mul(diff_);
if (_divWouldOverflow(num_, b)) return type(uint256).max;
return num_.div(b).unwrap();
}
if (ct == SupplyCurve.HYPERBOLIC) {
// T = C*(w(kn)^2 - w(k)^2), C = a*Kmax/2.
uint256 kmaxI = curveParam2;
if (kn.unwrap() >= kmaxI) return type(uint256).max;
UD60x18 gapHi = ud(kmaxI - kn.unwrap());
if (n.div(gapHi).unwrap() < SMALL_STEP_CROSSOVER) {
return _gauss2Integral(k, n);
}
UD60x18 wHi = ud(kmaxI).div(gapHi);
UD60x18 wLo = ud(kmaxI).div(ud(kmaxI - k.unwrap()));
if (ud(3e18).mul(wHi.ln()).unwrap() > EXP_OVERFLOW_THRESHOLD) return type(uint256).max;
UD60x18 cCoef = ud(curveParam1).mul(ud(kmaxI)).div(ud(2e18));
return cCoef.mul(_monoSub(wHi.powu(2), wLo.powu(2))).unwrap();
}
if (ct == SupplyCurve.DUAL_POWER) {
if (kn.unwrap() > DUAL_K_SATURATION) return type(uint256).max;
if (k.unwrap() > 0 && n.div(k).unwrap() < SMALL_STEP_CROSSOVER) return _gauss2Integral(k, n);
UD60x18 mD = ud(curveParam1);
UD60x18 betaD = ud(curveParam2);
return _monoSub(_dualAntideriv(mD, betaD, kn), _dualAntideriv(mD, betaD, k)).unwrap();
}
// SupplyCurve.ROOT_EXPONENTIAL
{
UD60x18 aR = ud(curveParam1);
UD60x18 bR = ud(curveParam2);
// kn >= k, so checking the upper endpoint covers every sqrt on this path.
if (kn.unwrap() > SQRT_MAX_INPUT || aR.unwrap() > type(uint256).max / 2) {
return type(uint256).max;
}
UD60x18 rtKn = kn.sqrt();
if (_mulDiv18WouldOverflow(bR, rtKn)) return type(uint256).max;
{
UD60x18 uHiR = bR.mul(rtKn);
if (uHiR.unwrap() > EXP_OVERFLOW_THRESHOLD) return type(uint256).max;
// Saturate if the upper endpoint's term would overflow, as in _rexpAntideriv.
UD60x18 euH = uHiR.exp();
UD60x18 brH = _monoSub(uHiR.mul(euH), _monoSub(euH, ud(1e18)));
if (_rexpScale(aR, bR, brH) == type(uint256).max) return type(uint256).max;
}
// n > 0 here, so the denominator is positive.
UD60x18 rtK = k.sqrt();
UD60x18 denomR = rtKn + rtK;
if (bR.mul(n).div(denomR).unwrap() < SERIES_U_CROSSOVER) {
return _rexpSmallStep(aR, bR, rtK, n, denomR);
}
return _monoSub(_rexpAntideriv(aR, bR, kn), _rexpAntideriv(aR, bR, k)).unwrap();
}
}
/// @dev True when buying `n_` tokens from `currentK_` costs at most `maxCost_`. A saturated
/// cost never counts as affordable.
function _affordable(uint256 currentK_, uint256 n_, uint256 maxCost_) private view returns (bool) {
uint256 c = getBuyCost(currentK_, n_);
return c != type(uint256).max && c <= maxCost_;
}
/// @notice Number of tokens `maxCost` buys starting at position `currentK` (the inverse of
/// getBuyCost).
/// @dev Binary search; works for any increasing supply curve.
/// @param currentK Starting position (18-decimal)
/// @param maxCost Amount to spend (18-decimal)
/// @return tokenAmount Tokens purchasable (18-decimal)
function getTokensForExactCost(uint256 currentK, uint256 maxCost) public view returns (uint256 tokenAmount) {
if (maxCost == 0) return 0;
uint256 spotPrice = getSupplyCurvePrice(currentK);
// Initial upper bound: about twice cost / spot price, computed without overflow.
uint256 hi;
if (spotPrice == 0) {
// Some curves have a zero price at k = 0, which gives no price scale: start at one
// token and let the doubling loop find the magnitude.
hi = 1e18;
} else if (maxCost > type(uint256).max / (2 * 1e18)) {
uint256 q = maxCost / spotPrice;
if (q > type(uint256).max / (2 * 1e18)) {
hi = type(uint256).max / 2; // the multiply would overflow: widest safe bracket
} else {
hi = q * 2 * 1e18;
if (hi < maxCost) hi = type(uint256).max / 2; // below maxCost: widest safe bracket
}
} else {
hi = (maxCost * 2 * 1e18) / spotPrice;
}
if (hi == 0) hi = 1e18;
uint256 lo = 0;
// Double the upper bound while it is still affordable (capped to avoid overflow).
while (hi < type(uint256).max / 2 && _affordable(currentK, hi, maxCost)) {
lo = hi;
hi = hi * 2;
}
while (hi - lo > 1) {
uint256 mid = lo + (hi - lo) / 2;
if (_affordable(currentK, mid, maxCost)) {
lo = mid;
} else {
hi = mid;
}
}
return lo;
}
// Supply and support curve helpers
/// @dev Sigmoid price: P = L / (1 + e^(-c*(k - S0))), plus the tail tau*L*(k - S0)/S0 above S0.
/// Arranged to avoid negative exponents (UD60x18 is unsigned):
/// k >= S0: logistic term L * e^(c*(k-S0)) / (e^(c*(k-S0)) + 1), plus the tail
/// k < S0: P = L / (1 + e^(c*(S0-k)))
function _sigmoidPrice(uint256 k) internal view returns (uint256) {
UD60x18 L = ud(curveParam1);
UD60x18 c = ud(curveParam2);
UD60x18 s0 = ud(curveParam3);
if (k >= curveParam3) {
UD60x18 excess = ud(k) - s0;
UD60x18 exponent = c.mul(excess);
if (excess.unwrap() > SIGMOID_TAIL_SATURATION) return type(uint256).max;
// Tail term tau*L*(k - S0)/S0, zero at S0.
UD60x18 tauL = ud(SIGMOID_TAIL_TAU).mul(L);
if (_mulDiv18WouldOverflow(tauL, excess)) return type(uint256).max;
UD60x18 tailNum = tauL.mul(excess);
if (_divWouldOverflow(tailNum, s0)) return type(uint256).max;
UD60x18 tail = tailNum.div(s0);
// Past the exp limit the logistic term has saturated at L.
if (exponent.unwrap() > EXP_OVERFLOW_THRESHOLD) {
if (tail.unwrap() > type(uint256).max - L.unwrap()) return type(uint256).max;
return (L + tail).unwrap();
}
UD60x18 expD = exponent.exp();
if (_mulDiv18WouldOverflow(L, expD)) return type(uint256).max;
UD60x18 sigTerm = L.mul(expD).div(expD + ud(1e18));
if (sigTerm.unwrap() > type(uint256).max - tail.unwrap()) return type(uint256).max;
return (sigTerm + tail).unwrap();
} else {
// The constructor keeps c * S0, and so this exponent, below the exp limit.
UD60x18 exponent = c.mul(s0 - ud(k));
UD60x18 expD = exponent.exp();
return L.div(ud(1e18) + expD).unwrap();
}
}
/// @dev softplus(z) = ln(1 + e^z) with z = c*(x - S0), used by the SIGMOID cost and the
/// SIGMOID support shape; callers divide by c.
function _softplus(UD60x18 c, UD60x18 x, UD60x18 s0) internal pure returns (UD60x18) {
if (x.unwrap() >= s0.unwrap()) {
UD60x18 z = c.mul(x - s0);
if (z.unwrap() > SOFTPLUS_OVERFLOW_THRESHOLD) return z;
UD60x18 expZ = z.exp();
return (expZ + ud(1e18)).ln();
} else {
UD60x18 z = c.mul(s0 - x);
// softplus(-z) = ln(e^z + 1) - z.
if (z.unwrap() > SOFTPLUS_OVERFLOW_THRESHOLD) return ud(0);
UD60x18 expZ = z.exp();
// ln(e^z + 1) can round slightly below z for large z; clamp the difference at zero.
UD60x18 lnv = (expZ + ud(1e18)).ln();
return lnv.unwrap() > z.unwrap() ? lnv - z : ud(0);
}
}
/// @dev Shape id of a SupportCurve (0 LINEAR_EXPONENTIAL, 1 POWER_LAW, 2 HYPERBOLIC,
/// 3 EXPONENTIAL, 4 SIGMOID, 5 STEP, 6 DUAL_POWER, 7 ROOT_EXPONENTIAL): the SupportCurve
/// order is the shape id order. SupplyCurve lists the same names in a different order,
/// so its ids go through _supplyShapeId.
function _supportShapeId(SupportCurve st) internal pure returns (uint8) {
return uint8(st);
}
/// @dev Shape id of a SupplyCurve, with the same ids as _supportShapeId. The enum order
/// differs, so each member is mapped explicitly.
function _supplyShapeId(SupplyCurve st) internal pure returns (uint8) {
if (st == SupplyCurve.LINEAR_EXPONENTIAL) return 0;
if (st == SupplyCurve.POWER_LAW) return 1;
if (st == SupplyCurve.HYPERBOLIC) return 2;
if (st == SupplyCurve.EXPONENTIAL) return 3;
if (st == SupplyCurve.SIGMOID) return 4;
if (st == SupplyCurve.STEP) return 5;
if (st == SupplyCurve.DUAL_POWER) return 6;
return 7; // ROOT_EXPONENTIAL
}
/// @dev Smooth maturity saturation: T9C_M_CAP * (1 - e^(-m*ln2)). Increasing in m, about 1
/// at m = 1, and approaching T9C_M_CAP. Returns T9C_M_CAP once e^(-x) is below one unit
/// of 18-decimal precision, which also keeps the exponent in range.
function _mSat(uint256 m) internal pure returns (UD60x18) {
UD60x18 x = ud(m).mul(ud(T9C_LN2));
if (x.unwrap() > 41.45e18) return ud(T9C_M_CAP);
return ud(T9C_M_CAP).mul(ud(1e18) - _expNeg(x));
}
/// @dev max(a - b, 0).
function _sub0(UD60x18 a, UD60x18 b) internal pure returns (UD60x18) {
return a.unwrap() > b.unwrap() ? a - b : ud(0);
}
/// @dev e^(-x) for x >= 0, as 1 / e^x.
function _expNeg(UD60x18 x) internal pure returns (UD60x18) {
return ud(1e18).div(x.exp());
}
/// @dev G(u, mHat): the integrated support shape of family `familyId` (ids as in
/// _supportShapeId), for u in [0, 1] (18-decimal) and maturity mHat. For POWER_LAW,
/// HYPERBOLIC and STEP, the token's own supply family uses its own curve parameters,
/// clamped to their valid ranges (HYPERBOLIC and STEP also use cumulativeK); otherwise
/// the shared constants above are used.
function _ladderG(uint8 familyId, UD60x18 u, UD60x18 mHat) internal view returns (UD60x18) {
if (mHat.unwrap() > T9C_M_CAP) mHat = ud(T9C_M_CAP);
if (familyId == 0) return _cardLexp(u, mHat);
if (familyId == 1) return _cardPl(u, supplyCurveType == SupplyCurve.POWER_LAW ? _clampNu(curveParam2) : T9C_N_HAT);
if (familyId == 2) return _cardHyp(u, _rhoFor(mHat));
if (familyId == 3) return _cardExp(u, mHat);
if (familyId == 4) return _cardSig(u, mHat);
if (familyId == 5) {
if (supplyCurveType == SupplyCurve.STEP) {
return _cardStep(u, _clampMult(curveParam2), ud(cumulativeK).div(ud(curveParam3)));
}
return _cardStep(u, T9C_MULT_HAT, ud(T9C_T_S).mul(mHat));
}
if (familyId == 6) return _cardDual(u, mHat);
return _cardRexp(u, mHat);
}
/// @dev Clamps `nu` to [T9C_N_MIN, T9C_N_MAX] = [1.9, 3.1] (18-decimal).
function _clampNu(uint256 nu) internal pure returns (uint256) {
if (nu < T9C_N_MIN) return T9C_N_MIN;
if (nu > T9C_N_MAX) return T9C_N_MAX;
return nu;
}
/// @dev Clamps `mult` to [T9C_MULT_MIN, T9C_MULT_MAX] = [1.2, 1.3] (18-decimal).
function _clampMult(uint256 mult) internal pure returns (uint256) {
if (mult < T9C_MULT_MIN) return T9C_MULT_MIN;
if (mult > T9C_MULT_MAX) return T9C_MULT_MAX;
return mult;
}
/// @dev rho for the HYPERBOLIC shape: cumulativeK/Kmax for a HYPERBOLIC token, otherwise
/// T9C_R_H * mHat / 2; capped at T9C_RHO_CAP.
function _rhoFor(UD60x18 mHat) internal view returns (uint256) {
uint256 rho = supplyCurveType == SupplyCurve.HYPERBOLIC
? ud(cumulativeK).div(ud(curveParam2)).unwrap()
: ud(T9C_R_H).mul(mHat).div(ud(2e18)).unwrap();
return rho > T9C_RHO_CAP ? T9C_RHO_CAP : rho;
}
/// @dev LINEAR_EXPONENTIAL shape: g = (1-u)*e^(-su), s = T9C_S_L*mHat;
/// G = (1-e^(-su))/s - [1-e^(-su)(1+su)]/s^2, with a series for small su.
function _cardLexp(UD60x18 u, UD60x18 mHat) internal pure returns (UD60x18) {
UD60x18 one = ud(1e18);
UD60x18 s = ud(T9C_S_L).mul(mHat);
UD60x18 su = s.mul(u);
if (su.unwrap() < 1e12) {
UD60x18 uu = u.mul(u);
return _sub0(u, _sub0((uu + s.mul(uu)).div(ud(2e18)), s.mul(uu).mul(u).div(ud(3e18))));
}
UD60x18 decay = _expNeg(su);
UD60x18 em1 = _sub0(one, decay);
return _sub0(em1.div(s), _sub0(em1, su.mul(decay)).div(s).div(s));
}
/// @dev POWER_LAW shape: g = (1-u)^nu; G = (1 - (1-u)^(nu+1))/(nu+1).
function _cardPl(UD60x18 u, uint256 nu) internal pure returns (UD60x18) {
UD60x18 one = ud(1e18);
UD60x18 base = one - u;
UD60x18 powed = base.unwrap() == 0 ? ud(0) : base.pow(ud(nu)).mul(base);
return (one - powed).div(ud(nu + 1e18));
}
/// @dev HYPERBOLIC shape: g = ((1-rho)/(1-rho+rho*u))^3. T9C_RHO_CAP keeps the denominator
/// positive.
function _cardHyp(UD60x18 u, uint256 rho) internal pure returns (UD60x18) {
UD60x18 one = ud(1e18);
if (rho < 1e11) return u; // nearly flat for very small rho: G = u
UD60x18 onemr = one - ud(rho);
UD60x18 ratio = onemr.div(onemr + ud(rho).mul(u));
return onemr.div(ud(rho).mul(ud(2e18))).mul(_sub0(one, ratio.mul(ratio)));
}
/// @dev EXPONENTIAL shape: g = e^(-su), s = T9C_S_E*mHat; G = (1-e^(-su))/s, with a series
/// for small su.
function _cardExp(UD60x18 u, UD60x18 mHat) internal pure returns (UD60x18) {
UD60x18 one = ud(1e18);
UD60x18 s = ud(T9C_S_E).mul(mHat);
UD60x18 su = s.mul(u);
if (su.unwrap() < 1e12) return u.mul(one - ud(su.unwrap() / 2) + su.mul(su).div(ud(6e18)));
return _sub0(one, _expNeg(su)).div(s);
}
/// @dev SIGMOID shape: a logistic curve with the tau tail term, normalized by its value at
/// u = 0. Uses _softplus.
function _cardSig(UD60x18 u, UD60x18 mHat) internal pure returns (UD60x18) {
UD60x18 one = ud(1e18);
UD60x18 a = ud(T9C_C_S).mul(mHat);
if (a.unwrap() < 1e12) return u; // at very low maturity the shape is flat: G = u
UD60x18 s0 = ud(T9C_THETA_S).div(mHat);
UD60x18 intSig = _sub0(_softplus(a, one, s0), _softplus(a, one - u, s0)).div(a);
UD60x18 intTail;
UD60x18 tail0;
if (mHat.unwrap() > T9C_THETA_S) {
{
UD60x18 hi = u.unwrap() < (one - ud(T9C_THETA_S).div(mHat)).unwrap()
? u
: one - ud(T9C_THETA_S).div(mHat);
if (hi.unwrap() > 0) {
UD60x18 inner = _sub0(mHat.mul(hi - hi.mul(hi).div(ud(2e18))), ud(T9C_THETA_S).mul(hi));
intTail = ud(SIGMOID_TAIL_TAU).mul(inner).div(ud(T9C_THETA_S));
}
}
tail0 = ud(SIGMOID_TAIL_TAU).mul(mHat - ud(T9C_THETA_S)).div(ud(T9C_THETA_S));
}
return (intSig + intTail).div(_sigmaAt(a, s0) + tail0);
}
/// @dev sigma(a*(1 - s0)), evaluated without negative exponents.
function _sigmaAt(UD60x18 a, UD60x18 s0) internal pure returns (UD60x18) {
UD60x18 one = ud(1e18);
if (one.unwrap() >= s0.unwrap()) {
UD60x18 z = a.mul(one - s0);
if (z.unwrap() > SOFTPLUS_OVERFLOW_THRESHOLD) return one;
UD60x18 ez = z.exp();
return ez.div(ez + one);
}
UD60x18 zn = a.mul(s0 - one);
if (zn.unwrap() > SOFTPLUS_OVERFLOW_THRESHOLD) return ud(0);
return one.div(one + zn.exp());
}
/// @dev STEP shape: a staircase of T steps, each 1/mult of the height before it (T capped
/// at T9C_T_CAP); constant time.
function _cardStep(UD60x18 u, uint256 mult, UD60x18 T) internal pure returns (UD60x18) {
UD60x18 one = ud(1e18);
if (T.unwrap() > T9C_T_CAP) T = ud(T9C_T_CAP);
if (T.unwrap() < 1e9 || mult <= 1e18 + 1e12) return u; // no shelves / flat: G = u
UD60x18 r = one.div(ud(mult));
uint256 j = T.mul(u).unwrap() / 1e18;
UD60x18 rj = r.powu(j);
return (one - rj).div(T.mul(one - r)) + rj.mul(_sub0(u, ud(j * 1e18).div(T)));
}
/// @dev DUAL_POWER shape: g = ((1-u)^1.5 + w*(1-u)^3.5)/(1+w), w = T9C_W_D*mHat^2, built
/// from square roots.
function _cardDual(UD60x18 u, UD60x18 mHat) internal pure returns (UD60x18) {
UD60x18 one = ud(1e18);
UD60x18 w = ud(T9C_W_D).mul(mHat).mul(mHat);
UD60x18 base = one - u;
UD60x18 b25 = base.mul(base).mul(base.sqrt());
UD60x18 b45 = b25.mul(base).mul(base);
return ((one - b25).div(ud(2.5e18)) + w.mul(one - b45).div(ud(4.5e18))).div(one + w);
}
/// @dev ROOT_EXPONENTIAL shape: g = e^(-s(1-sqrt(1-u))), s = T9C_S_R*sqrt(mHat);
/// G = (2/s^2)*[(s-1) - e^(-x)(sq-1)], q = sqrt(1-u), x = s(1-q), arranged to stay
/// non-negative, with a series for small s.
function _cardRexp(UD60x18 u, UD60x18 mHat) internal pure returns (UD60x18) {
UD60x18 one = ud(1e18);
UD60x18 sR = ud(T9C_S_R).mul(mHat.sqrt());
UD60x18 q = (one - u).sqrt();
if (sR.unwrap() < 1e13) {
UD60x18 t = one - u;
t = t.mul(q);
t = one - t;
t = t.mul(ud(2e18)).div(ud(3e18));
return _sub0(u, sR.mul(_sub0(u, t)));
}
UD60x18 dk = _expNeg(sR.mul(one - q));
UD60x18 sq_ = sR.mul(q);
UD60x18 core;
if (sR.unwrap() >= 1e18) {
core = sq_.unwrap() >= 1e18 ? _sub0(sR - one, dk.mul(sq_ - one)) : (sR - one) + dk.mul(one - sq_);
} else {
core = _sub0(dk.mul(one - sq_), one - sR);
}
return core.mul(ud(2e18)).div(sR).div(sR);
}
/// @dev STEP cost: tiers of `tier` tokens, tier i priced at base * mult^i. Computed as
/// C(k+n) - C(k), with C the cumulative cost from zero, in constant time.
function _stepCost(uint256 currentK, uint256 tokenAmount) internal view returns (uint256) {
UD60x18 mult = ud(curveParam2);
UD60x18 lnMult = mult.ln();
uint256 endPos = currentK + tokenAmount; // exclusive end
// Saturate if mult^floor(endPos/tier) would overflow pow; compared by division.
if (endPos / curveParam3 > EXP_OVERFLOW_THRESHOLD / lnMult.unwrap()) return type(uint256).max;
uint256 hi = _stepCumCost(endPos);
uint256 lo = _stepCumCost(currentK);
if (hi == type(uint256).max || lo == type(uint256).max) return type(uint256).max;
return hi > lo ? hi - lo : 0;
}
/// @dev Cumulative STEP cost of the first `x` tokens: the full tiers 0..ft-1 as the
/// geometric series base*tier*(mult^ft - 1)/(mult - 1), plus the partial tier ft at
/// base*mult^ft, ft = floor(x/tier).
function _stepCumCost(uint256 x) private view returns (uint256) {
if (x == 0) return 0;
UD60x18 mult = ud(curveParam2);
UD60x18 base = ud(curveParam1);
uint256 tier = curveParam3;
uint256 ft = x / tier; // number of full tiers below x
UD60x18 pft = mult.pow(ud(ft * 1e18)); // mult^ft
UD60x18 baseTier = base.mul(ud(tier));
UD60x18 series = (pft - ud(1e18)).div(mult - ud(1e18));
if (_mulDiv18WouldOverflow(baseTier, series)) return type(uint256).max;
UD60x18 full = baseTier.mul(series);
UD60x18 basePft = base.mul(pft);
UD60x18 part_ = ud(x - ft * tier);
if (_mulDiv18WouldOverflow(basePft, part_)) return type(uint256).max;
uint256 partialCost = basePft.mul(part_).unwrap();
if (partialCost > type(uint256).max - full.unwrap()) return type(uint256).max;
return full.unwrap() + partialCost;
}
// Support system
/// @notice Whether Storm is active: within 9 hours of the last large sell.
function stormMode() public view returns (bool) {
return lastStormTriggerTime != 0 && block.timestamp < lastStormTriggerTime + STORM_RECOVERY_DURATION;
}
/// @notice The sell spread for the given maturity.
/// @dev Before the first buy it returns the base spread. After that the spread recovers
/// linearly from the last snap level (`lastSnapSpread`) to MIN_SPREAD over
/// `spreadRecoveryDuration`, then stays at the floor. Medium and large sells set it to at
/// least their tier level and restart the recovery (see the tier constants); buys never
/// snap it. Until the first medium or large sell, the recovery runs from the deployment
/// time and starts from the base spread at the current maturity, which rises as tokens
/// are bought.
/// @param maturity cumulativeK / maturityScale (18-decimal)
/// @return spread The spread as an 18-decimal fraction (e.g. 0.12e18 = 12%)
function getSupportSpread(uint256 maturity) public view returns (uint256 spread) {
if (cumulativeK == 0) return _getBaseSpread(maturity);
uint256 snap = lastSnapSpread;
if (snap == 0) snap = _getBaseSpread(maturity);
if (snap <= MIN_SPREAD) return MIN_SPREAD;
uint256 elapsed;
unchecked {
elapsed = block.timestamp > lastRatchetTime ? block.timestamp - lastRatchetTime : 0;
}
uint256 duration = spreadRecoveryDuration;
if (elapsed >= duration) return MIN_SPREAD;
uint256 range = snap - MIN_SPREAD;
uint256 reduction = (range * elapsed) / duration;
return snap - reduction;
}
/// @notice The base spread for a given maturity, before recovery.
/// @param maturity cumulativeK / maturityScale for this token (18-decimal). The function
/// does not read either value itself.
function getBaseSpread(uint256 maturity) external view returns (uint256) {
return _getBaseSpread(maturity);
}
/// @dev Base spread by support curve and maturity. Each curve rises from a start value
/// toward a cap as maturity grows: start + span * N(m)/N(2), with N the curve's own
/// growth shape and m = _mSat(maturity) <= 2.
function _getBaseSpread(uint256 maturity) internal view returns (uint256 spread) {
UD60x18 one = ud(1e18);
UD60x18 m = _mSat(maturity); // smooth saturation keeps m at most T9C_M_CAP
SupportCurve st = supportCurveType;
if (st == SupportCurve.LINEAR_EXPONENTIAL) {
// LINEAR_EXPONENTIAL: N = m*e^((T9C_S_L/2)*m), 0.06 to 0.30
UD60x18 q = ud(T9C_S_L / 2);
UD60x18 nm = m.mul(q.mul(m).exp());
UD60x18 n2 = ud(2e18).mul(q.mul(ud(2e18)).exp());
return (ud(0.30e18) - ud(0.24e18).mul(n2 - nm).div(n2)).unwrap();
}
if (st == SupportCurve.POWER_LAW) {
// POWER_LAW: N = m^T9C_N_HAT, 0.06 to 0.28
if (m.unwrap() == 0) return 0.06e18;
UD60x18 nm = m.pow(ud(T9C_N_HAT));
UD60x18 n2 = ud(2e18).pow(ud(T9C_N_HAT));
return (ud(0.28e18) - ud(0.22e18).mul(n2 - nm).div(n2)).unwrap();
}
if (st == SupportCurve.HYPERBOLIC) {
// HYPERBOLIC: N = ln(1/(1-rho)^2), rho = T9C_R_H*m/2, 0.06 to 0.30
uint256 rho = ud(T9C_R_H).mul(m).div(ud(2e18)).unwrap();
UD60x18 nm = one.div(one - ud(rho)).ln().mul(ud(2e18));
UD60x18 n2 = one.div(one - ud(T9C_R_H)).ln().mul(ud(2e18));
return (ud(0.30e18) - ud(0.24e18).mul(n2 - nm).div(n2)).unwrap();
}
if (st == SupportCurve.EXPONENTIAL) {
// EXPONENTIAL: N = e^((T9C_S_E/2)*m) - 1, 0.06 to 0.30
UD60x18 q = ud(T9C_S_E / 2);
UD60x18 nm = _sub0(q.mul(m).exp(), one);
UD60x18 n2 = _sub0(q.mul(ud(2e18)).exp(), one);
return (ud(0.30e18) - ud(0.24e18).mul(n2 - nm).div(n2)).unwrap();
}
if (st == SupportCurve.SIGMOID) {
// SIGMOID: N = sigma(T9C_C_S*(m-T9C_THETA_S)) - sigma(-T9C_C_S*T9C_THETA_S), 0.08 to 0.26
UD60x18 sig0 = one.div(one + ud(T9C_C_S).mul(ud(T9C_THETA_S)).exp());
UD60x18 sigM;
if (m.unwrap() >= T9C_THETA_S) {
UD60x18 e = ud(T9C_C_S).mul(m - ud(T9C_THETA_S)).exp();
sigM = e.div(e + one);
} else {
sigM = one.div(one + ud(T9C_C_S).mul(ud(T9C_THETA_S) - m).exp());
}
UD60x18 sig2 = ud(T9C_C_S).mul(ud(2e18) - ud(T9C_THETA_S)).exp();
sig2 = sig2.div(sig2 + one);
UD60x18 numer = _sub0(sigM, sig0);
UD60x18 denom = _sub0(sig2, sig0);
return (ud(0.26e18) - ud(0.18e18).mul(denom - numer).div(denom)).unwrap();
}
if (st == SupportCurve.STEP) {
// STEP: up to nine shelves of 0.02 plus a continuous tail of 0.02*m/2, 0.08 to 0.28
uint256 j = ud(5e18).mul(m).unwrap() / 1e18;
if (j > 9) j = 9;
return 0.08e18 + j * 0.02e18 + ud(0.02e18).mul(m).div(ud(2e18)).unwrap();
}
if (st == SupportCurve.DUAL_POWER) {
// DUAL_POWER: N = m^1.5 + T9C_W_D*m^3.5, 0.06 to 0.30
UD60x18 m15 = m.mul(m.sqrt());
UD60x18 nm = m15 + ud(T9C_W_D).mul(m15.mul(m).mul(m));
UD60x18 two = ud(2e18);
UD60x18 t15 = two.mul(two.sqrt());
UD60x18 n2 = t15 + ud(T9C_W_D).mul(t15.mul(two).mul(two));
return (ud(0.30e18) - ud(0.24e18).mul(n2 - nm).div(n2)).unwrap();
}
// SupportCurve.ROOT_EXPONENTIAL: N = e^(T9C_S_R*sqrt(m/2)) - 1, 0.06 to 0.28
UD60x18 nmR = _sub0(ud(T9C_S_R).mul(m.div(ud(2e18)).sqrt()).exp(), one);
UD60x18 n2R = _sub0(ud(T9C_S_R).exp(), one);
return (ud(0.28e18) - ud(0.22e18).mul(n2R - nmR).div(n2R)).unwrap();
}
/// @dev Sell payout for `amount` tokens before fees, and the tip state the sale leaves.
/// The payout is (1 - spread) * seg * ψ, capped at the treasury. seg is the curve cost
/// of the part of the sale inside the solver's book, the window of tokens below the tip;
/// tokens past the book's depth add nothing. If the solver call fails or answers out of
/// range, seg is the cost of the window [H - amount, H], H = supportHead(). If seg is
/// the saturation sentinel, the payout is the treasury times u times ψ instead.
/// u = priced / supply, with priced the part of the sale the book prices (the whole sale
/// on the fallback window). ψ = min(1, G_support(u)/G_supply(u)) scales larger sales;
/// ψ is 1 when the shapes match.
/// @param amount Number of tokens being sold (18-decimal)
/// @return value Payout before fees
/// @return nt Tip position after the sale
/// @return nd Tip depth after the sale
function _supportValueAndNext(uint256 amount)
private view returns (uint256 value, uint256 nt, uint256 nd)
{
uint256 supply = totalSupply();
if (amount == 0 || supply == 0) return (0, 0, 0);
if (amount > supply) revert SellExceedsSupply();
uint256 maturity = ud(cumulativeK).div(ud(maturityScale)).unwrap();
uint256 spread = getSupportSpread(maturity);
uint256 normalizedTreasury = address(this).balance * collateralScale;
uint256 buyCost;
uint256 priced;
(buyCost, nt, nd, priced) = _phQuote(amount, supply);
uint256 raw;
{
// Scoped to limit stack use.
UD60x18 u = ud(priced).div(ud(supply));
UD60x18 psi;
{
UD60x18 mH = _mSat(maturity);
UD60x18 gX = _ladderG(_supportShapeId(supportCurveType), u, mH);
UD60x18 gY = _ladderG(_supplyShapeId(supplyCurveType), u, mH);
psi = gY.unwrap() == 0 ? ud(1e18) : gX.div(gY);
if (psi.unwrap() > 1e18) psi = ud(1e18);
}
if (buyCost == type(uint256).max) {
raw = ud(normalizedTreasury).mul(u).mul(psi).unwrap();
} else {
raw = ud(buyCost).mul(ud(1e18) - ud(spread)).mul(psi).unwrap();
}
}
uint256 normalizedPayout = raw < normalizedTreasury ? raw : normalizedTreasury;
return (normalizedPayout / collateralScale, nt, nd);
}
/// @notice Payout for selling `amount` tokens, before fees.
/// @dev Not a price oracle: it reads the live treasury and supply, and direct transfers can
/// increase the treasury.
/// @param amount Number of tokens being sold (18-decimal)
/// @return value Payout before fees
function getSupportValue(uint256 amount) public view returns (uint256 value) {
(value,,) = _supportValueAndNext(amount);
}
/// @dev Asks the solver for the sale's segment cost, the tip state it leaves and how many of
/// the tokens the book prices. If the call fails, returns data of the wrong size, or
/// returns a tip above cumulativeK, a depth above supply or more priced tokens than the
/// sale, the token prices the whole sale itself on the window [supply - amount, supply],
/// and the tip position and depth become the remaining supply.
function _phQuote(uint256 amount, uint256 n)
private view returns (uint256 seg, uint256 nt, uint256 nd, uint256 priced)
{
uint256 phElapsed;
unchecked {
phElapsed = block.timestamp > healTimePH ? block.timestamp - healTimePH : 0;
}
// Scale the elapsed time to the solver's 30-minute heal for a longer recovery.
{
uint256 healWindow = healWindowPH;
if (healWindow > TIP_HEAL_DURATION) phElapsed = (phElapsed * TIP_HEAL_DURATION) / healWindow;
}
bytes memory cd = abi.encodeCall(
IPHSolver.quote,
(address(this), tipLowPH, tipDepthPH, phElapsed, amount)
);
address solver = address(phSolver);
bool ok;
// Accept exactly four words of return data. A failed call, or an address with no code,
// leaves ok false.
assembly ("memory-safe") {
let out := mload(0x40)
mstore(0x40, add(out, 0x80))
ok := staticcall(gas(), solver, add(cd, 0x20), mload(cd), out, 0x80)
ok := and(ok, eq(returndatasize(), 0x80))
if ok {
seg := mload(out)
nt := mload(add(out, 0x20))
nd := mload(add(out, 0x40))
priced := mload(add(out, 0x60))
}
}
if (ok && nt <= cumulativeK && nd <= n && priced <= amount) return (seg, nt, nd, priced);
// The caller passes 1 <= amount <= n.
uint256 rest = n - amount;
return (getBuyCost(rest, amount), rest, rest, amount);
}
/// @dev Updates the tip after a buy: the minted tokens are added to its position (capped
/// at cumulativeK) and to its depth. Does not call the solver or reset the heal clock.
function _phCommitBuy(uint256 minted) private {
uint256 kk = cumulativeK;
uint256 t = tipLowPH + minted;
tipLowPH = t > kk ? kk : t;
// A sale stores a depth of at most the supply, and a buy adds the same amount to the depth
// as to cumulativeK, so the depth never exceeds cumulativeK.
tipDepthPH = tipDepthPH + minted;
}
// View functions
/// @notice Duration of the current spread recovery: 90 minutes after a medium sell, 9 hours
/// after a large one or after any snap while a 9-hour recovery is running.
function getCurrentRecoveryDuration() external view returns (uint256) {
return spreadRecoveryDuration;
}
/// @notice The support head: the circulating supply.
/// @dev The fallback window prices down from this value.
function supportHead() public view returns (uint256) {
return totalSupply();
}
/// @notice The stored tip state: tip position, tip depth, the time of the last sale and the
/// length of its recovery.
/// @dev The live tip and depth are computed from these with cumulativeK, circulating supply
/// and the treasury (see PHSolver.tipAndDepth). When healWindow is longer than the
/// solver's HEAL_DURATION, the time since healedAt is first scaled to it:
/// elapsed * HEAL_DURATION / healWindow.
/// @return tipLow stored tip position (18-decimal)
/// @return depth stored tip depth (18-decimal)
/// @return healedAt time of the last sale (zero before any sale); the tip's recovery runs
/// from here
/// @return healWindow length of that recovery in seconds (zero before any sale)
function phBook() external view returns (uint256 tipLow, uint256 depth, uint256 healedAt, uint256 healWindow) {
return (tipLowPH, tipDepthPH, healTimePH, healWindowPH);
}
/// @notice Treasury balance (native currency held by this contract).
function treasury() external view returns (uint256) {
return address(this).balance;
}
/// @notice Supply curve price at the current cumulativeK.
/// @dev Like any spot price, it can move within a block; it is not a price oracle.
function currentPrice() external view returns (uint256) {
return getSupplyCurvePrice(cumulativeK);
}
// Canonical domains
/// @notice The dApp's canonical domains and ENS name, comma-separated.
/// @dev The same value on every PUNZI contract.
function canonicalDomains() external pure returns (string memory) {
return "punzi.xyz,punziwars.com,punzi.eth";
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 30,
"enabled": true
},
"evmVersion": "shanghai",
"remappings": [
"forge-std/=lib/forge-std/src/",
"@prb/math/=lib/prb-math/src/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"prb-math/=lib/prb-math/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.