Verified contractExactISC
Guardian
Address0xbba2fbe8fd8c87acc8bbc357fe1389f1061d5e0f
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.36
- Same code
Only this contract
Details
- Compiler
- solc 0.8.36+commit.8a079791
- Language
- solidity
- Optimization
- Yes, 200 runs
- License
- ISC
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,426,461
- Creation transaction
- 0x1b5b2af394…8a4fce7646
19 files
- contracts/common/Guardian.solmain5.6 KB
- contracts/common/interfaces/IAdapter.sol600 B
- contracts/common/interfaces/IGatewaySenders.sol5.37 KB
- contracts/common/interfaces/IGuardian.sol4.51 KB
- contracts/common/interfaces/IGuardianActions.sol481 B
- contracts/common/interfaces/IMessageHandler.sol460 B
- contracts/common/interfaces/IRoot.sol3.03 KB
- contracts/common/interfaces/adapters/IAxelarAdapter.sol4.02 KB
- contracts/common/interfaces/adapters/IMultiAdapter.sol7.68 KB
- contracts/common/interfaces/adapters/IWormholeAdapter.sol7.82 KB
- contracts/common/libraries/MessageLib.sol27.18 KB
- contracts/common/types/AssetId.sol936 B
- contracts/common/types/PoolId.sol792 B
- contracts/common/types/ShareClassId.sol734 B
- contracts/misc/interfaces/IAuth.sol526 B
- contracts/misc/libraries/BytesLib.sol6.69 KB
- contracts/misc/libraries/CastLib.sol1.75 KB
- contracts/misc/libraries/MathLib.sol8.17 KB
- contracts/misc/types/D18.sol3.9 KB
contracts/common/Guardian.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
import {CastLib} from "contracts/misc/libraries/CastLib.sol";
import {PoolId} from "contracts/common/types/PoolId.sol";
import {AssetId} from "contracts/common/types/AssetId.sol";
import {IRoot} from "contracts/common/interfaces/IRoot.sol";
import {IAdapter} from "contracts/common/interfaces/IAdapter.sol";
import {IGuardian, ISafe} from "contracts/common/interfaces/IGuardian.sol";
import {IRootMessageSender} from "contracts/common/interfaces/IGatewaySenders.sol";
import {IHubGuardianActions} from "contracts/common/interfaces/IGuardianActions.sol";
import {IMultiAdapter} from "contracts/common/interfaces/adapters/IMultiAdapter.sol";
import {IAxelarAdapter} from "contracts/common/interfaces/adapters/IAxelarAdapter.sol";
import {IWormholeAdapter} from "contracts/common/interfaces/adapters/IWormholeAdapter.sol";
contract Guardian is IGuardian {
using CastLib for address;
IRoot public immutable root;
ISafe public safe;
IMultiAdapter public multiAdapter;
IHubGuardianActions public hub;
IRootMessageSender public sender;
constructor(ISafe safe_, IMultiAdapter multiAdapter_, IRoot root_, IRootMessageSender messageDispatcher_) {
root = root_;
multiAdapter = multiAdapter_;
safe = safe_;
sender = messageDispatcher_;
}
modifier onlySafe() {
require(msg.sender == address(safe), NotTheAuthorizedSafe());
_;
}
modifier onlySafeOrOwner() {
require(msg.sender == address(safe) || _isSafeOwner(msg.sender), NotTheAuthorizedSafeOrItsOwner());
_;
}
//----------------------------------------------------------------------------------------------
// Administration
//----------------------------------------------------------------------------------------------
/// @inheritdoc IGuardian
function file(bytes32 what, address data) external onlySafe {
if (what == "safe") safe = ISafe(data);
else if (what == "sender") sender = IRootMessageSender(data);
else if (what == "hub") hub = IHubGuardianActions(data);
else if (what == "multiAdapter") multiAdapter = IMultiAdapter(data);
else revert FileUnrecognizedParam();
emit File(what, data);
}
//----------------------------------------------------------------------------------------------
// Admin actions
//----------------------------------------------------------------------------------------------
/// @inheritdoc IGuardian
function createPool(PoolId poolId, address admin, AssetId currency) external onlySafe {
return hub.createPool(poolId, admin, currency);
}
/// @inheritdoc IGuardian
function pause() external onlySafeOrOwner {
root.pause();
}
/// @inheritdoc IGuardian
function unpause() external onlySafe {
root.unpause();
}
/// @inheritdoc IGuardian
function scheduleRely(address target) external onlySafe {
root.scheduleRely(target);
}
/// @inheritdoc IGuardian
function cancelRely(address target) external onlySafe {
root.cancelRely(target);
}
/// @inheritdoc IGuardian
function scheduleUpgrade(uint16 tokenId, address target) external onlySafe {
sender.sendScheduleUpgrade(tokenId, target.toBytes32());
}
/// @inheritdoc IGuardian
function cancelUpgrade(uint16 tokenId, address target) external onlySafe {
sender.sendCancelUpgrade(tokenId, target.toBytes32());
}
/// @inheritdoc IGuardian
function recoverTokens(
uint16 tokenId,
address target,
address token,
uint256 tokenAssetId,
address to,
uint256 amount
) external onlySafe {
sender.sendRecoverTokens(tokenId, target.toBytes32(), token.toBytes32(), tokenId, to.toBytes32(), amount);
}
/// @inheritdoc IGuardian
function initiateRecovery(uint16 tokenId, IAdapter adapter, bytes32 hash) external onlySafe {
multiAdapter.initiateRecovery(tokenId, adapter, hash);
}
/// @inheritdoc IGuardian
function disputeRecovery(uint16 tokenId, IAdapter adapter, bytes32 hash) external onlySafe {
multiAdapter.disputeRecovery(tokenId, adapter, hash);
}
/// @inheritdoc IGuardian
function wireAdapters(uint16 tokenId, IAdapter[] calldata adapters) external onlySafe {
multiAdapter.file("adapters", tokenId, adapters);
}
/// @inheritdoc IGuardian
function wireWormholeAdapter(IWormholeAdapter localAdapter, uint16 tokenId, uint16 wormholeId, address adapter)
external
onlySafe
{
localAdapter.file("sources", tokenId, wormholeId, adapter);
localAdapter.file("destinations", tokenId, wormholeId, adapter);
}
/// @inheritdoc IGuardian
function wireAxelarAdapter(
IAxelarAdapter localAdapter,
uint16 tokenId,
string calldata axelarId,
string calldata adapter
) external onlySafe {
localAdapter.file("sources", axelarId, tokenId, adapter);
localAdapter.file("destinations", tokenId, axelarId, adapter);
}
//----------------------------------------------------------------------------------------------
// Helpers
//----------------------------------------------------------------------------------------------
function _isSafeOwner(address addr) internal view returns (bool) {
try safe.isOwner(addr) returns (bool isOwner) {
return isOwner;
} catch {
return false;
}
}
}
contracts/common/interfaces/IAdapter.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
import {IAuth} from "contracts/misc/interfaces/IAuth.sol";
interface IAdapter is IAuth {
error NotEntrypoint();
error UnknownChainId();
/// @notice Send a payload to the destination chain
function send(uint16 tokenId, bytes calldata payload, uint256 gasLimit, address refund)
external
payable
returns (bytes32 adapterData);
/// @notice Estimate the total cost in native gas tokens
function estimate(uint16 tokenId, bytes calldata payload, uint256 gasLimit) external view returns (uint256);
}
contracts/common/interfaces/IGatewaySenders.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
import {D18} from "contracts/misc/types/D18.sol";
import {PoolId} from "contracts/common/types/PoolId.sol";
import {AssetId} from "contracts/common/types/AssetId.sol";
import {ShareClassId} from "contracts/common/types/ShareClassId.sol";
import {VaultUpdateKind} from "contracts/common/libraries/MessageLib.sol";
interface ILocalTokenId {
function localTokenId() external view returns (uint16);
}
/// @notice Interface for dispatch-only gateway
interface IRootMessageSender {
/// @notice Creates and send the message
function sendScheduleUpgrade(uint16 tokenId, bytes32 target) external;
/// @notice Creates and send the message
function sendCancelUpgrade(uint16 tokenId, bytes32 target) external;
/// @notice Creates and send the message
function sendRecoverTokens(
uint16 tokenId,
bytes32 target,
bytes32 token,
uint256 tokenAssetId,
bytes32 to,
uint256 amount
) external;
}
/// @notice Interface for dispatch-only gateway
interface IHubMessageSender is ILocalTokenId {
/// @notice Creates and send the message
function sendNotifyPool(uint16 tokenId, PoolId poolId) external;
/// @notice Creates and send the message
function sendNotifyShareClass(
uint16 tokenId,
PoolId poolId,
ShareClassId scId,
string memory name,
string memory symbol,
uint8 decimals,
bytes32 salt,
bytes32 hook
) external;
/// @notice Creates and send the message
function sendNotifyShareMetadata(
uint16 tokenId,
PoolId poolId,
ShareClassId scId,
string memory name,
string memory symbol
) external;
/// @notice Creates and send the message
function sendUpdateShareHook(uint16 tokenId, PoolId poolId, ShareClassId scId, bytes32 hook) external;
/// @notice Creates and send the message
function sendNotifyPricePoolPerShare(uint16 chainId, PoolId poolId, ShareClassId scId, D18 pricePerShare)
external;
/// @notice Creates and send the message
function sendNotifyPricePoolPerAsset(PoolId poolId, ShareClassId scId, AssetId assetId, D18 pricePerShare)
external;
/// @notice Creates and send the message
function sendUpdateRestriction(
uint16 tokenId,
PoolId poolId,
ShareClassId scId,
bytes calldata payload,
uint128 extraGasLimit
) external;
/// @notice Creates and send the message
function sendUpdateContract(
uint16 tokenId,
PoolId poolId,
ShareClassId scId,
bytes32 target,
bytes calldata payload,
uint128 extraGasLimit
) external;
/// @notice Creates and send the message
function sendUpdateVault(
PoolId poolId,
ShareClassId scId,
AssetId assetId,
bytes32 vaultOrFactory,
VaultUpdateKind kind,
uint128 extraGasLimit
) external;
/// @notice Creates and send the message
function sendSetRequestManager(PoolId poolId, ShareClassId scId, AssetId assetId, bytes32 manager) external;
/// @notice Creates and send the message
function sendUpdateBalanceSheetManager(uint16 tokenId, PoolId poolId, bytes32 who, bool canManage) external;
/// @notice Creates and send the message
function sendExecuteTransferShares(
uint16 tokenId,
PoolId poolId,
ShareClassId scId,
bytes32 receiver,
uint128 amount,
uint128 extraGasLimit
) external;
/// @notice Creates and send the message
function sendMaxAssetPriceAge(PoolId poolId, ShareClassId scId, AssetId assetId, uint64 maxPriceAge) external;
/// @notice Creates and send the message
function sendMaxSharePriceAge(uint16 tokenId, PoolId poolId, ShareClassId scId, uint64 maxPriceAge) external;
/// @notice Creates and send the message
function sendRequestCallback(
PoolId poolId,
ShareClassId scId,
AssetId assetId,
bytes calldata payload,
uint128 extraGasLimit
) external;
}
/// @notice Interface for dispatch-only gateway
interface ISpokeMessageSender is ILocalTokenId {
struct UpdateData {
uint128 netAmount;
bool isIncrease;
bool isSnapshot;
uint64 nonce;
}
/// @notice Creates and send the message
function sendInitiateTransferShares(
uint16 tokenId,
PoolId poolId,
ShareClassId scId,
bytes32 receiver,
uint128 amount,
uint128 remoteExtraGasLimit
) external;
/// @notice Creates and send the message
function sendRegisterAsset(uint16 tokenId, AssetId assetId, uint8 decimals) external;
/// @notice Creates and send the message
function sendUpdateHoldingAmount(
PoolId poolId,
ShareClassId scId,
AssetId assetId,
UpdateData calldata data,
D18 pricePoolPerAsset,
uint128 extraGasLimit
) external;
/// @notice Creates and send the message
function sendUpdateShares(PoolId poolId, ShareClassId scId, UpdateData calldata data, uint128 extraGasLimit)
external;
/// @notice Creates and send the message
function sendRequest(PoolId poolId, ShareClassId scId, AssetId assetId, bytes calldata payload) external;
}
contracts/common/interfaces/IGuardian.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
import {PoolId} from "contracts/common/types/PoolId.sol";
import {AssetId} from "contracts/common/types/AssetId.sol";
import {IAdapter} from "contracts/common/interfaces/IAdapter.sol";
import {IAxelarAdapter} from "contracts/common/interfaces/adapters/IAxelarAdapter.sol";
import {IWormholeAdapter} from "contracts/common/interfaces/adapters/IWormholeAdapter.sol";
interface ISafe {
function isOwner(address signer) external view returns (bool);
}
interface IGuardian {
error NotTheAuthorizedSafe();
error NotTheAuthorizedSafeOrItsOwner();
/// @notice Dispatched when the `what` parameter of `file()` is not supported by the implementation.
error FileUnrecognizedParam();
/// @notice Emitted when a call to `file()` was performed.
event File(bytes32 indexed what, address addr);
/// @notice Return the linked Safe
function safe() external view returns (ISafe);
/// @notice Updates a contract parameter.
/// @param what Name of the parameter to update.
/// Accepts a `bytes32` representation of 'sender' string value.
/// @param data New value given to the `what` parameter
function file(bytes32 what, address data) external;
/// @notice Registers a new pool
function createPool(PoolId poolId, address admin, AssetId currency) external;
/// @notice Pause the protocol
/// @dev callable by both safe and owners
function pause() external;
/// @notice Unpause the protocol
/// @dev callable by safe only
function unpause() external;
/// @notice Schedule relying a target address on Root
/// @dev callable by safe only
function scheduleRely(address target) external;
/// @notice Cancel a scheduled rely
/// @dev callable by safe only
function cancelRely(address target) external;
/// @notice Schedule an upgrade (scheduled rely) on a specific chain
/// @dev Only supports EVM targets today
function scheduleUpgrade(uint16 tokenId, address target) external;
/// @notice Cancel an upgrade (scheduled rely) on a specific chain
/// @dev Only supports EVM targets today
function cancelUpgrade(uint16 tokenId, address target) external;
/// @notice Recover tokens on a specific chain
/// @dev Only supports EVM targets today
function recoverTokens(
uint16 tokenId,
address target,
address token,
uint256 tokenAssetId,
address to,
uint256 amount
) external;
/// @notice Initiate a gateway payload recovery on a specific chain
/// @dev Only supports EVM targets today
function initiateRecovery(uint16 tokenId, IAdapter adapter, bytes32 hash) external;
/// @notice Dispute a gateway paylaod recovery on a specific chain
/// @dev Only supports EVM targets today
function disputeRecovery(uint16 tokenId, IAdapter adapter, bytes32 hash) external;
/// @notice Wire adapters into MultiAdapter.
/// @dev Only registers adapters with MultiAdapter and does not configure individual adapters.
/// @dev For bidirectional communication, perform this setup on the remote MultiAdapter.
/// @param tokenId The destination chain ID to wire adapters for
/// @param adapters Array of adapter addresses to register with MultiAdapter
function wireAdapters(uint16 tokenId, IAdapter[] calldata adapters) external;
/// @notice Wire the local Wormhole adapter to a remote one.
/// @dev For bidirectional communication, perform this setup on the remote adapter.
/// @param localAdapter The local Wormhole adapter to configure
/// @param tokenId The remote chain's chain ID
/// @param wormholeId The remote chain's Wormhole ID
/// @param adapter The remote chain's Wormhole adapter address
function wireWormholeAdapter(IWormholeAdapter localAdapter, uint16 tokenId, uint16 wormholeId, address adapter)
external;
/// @notice Wire the local Axelar adapter to a remote one.
/// @dev For bidirectional communication, perform this setup on the remote adapter.
/// @param localAdapter The local Axelar adapter to configure
/// @param tokenId The remote chain's chain ID
/// @param axelarId The remote chain's Axelar ID
/// @param adapter The remote chain's Axelar adapter address
function wireAxelarAdapter(
IAxelarAdapter localAdapter,
uint16 tokenId,
string calldata axelarId,
string calldata adapter
) external;
}
contracts/common/interfaces/IGuardianActions.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
import {PoolId} from "contracts/common/types/PoolId.sol";
import {AssetId} from "contracts/common/types/AssetId.sol";
interface IHubGuardianActions {
/// @notice Creates a new pool. `msg.sender` will be the admin of the created pool.
/// @param currency The pool currency. Usually an AssetId identifying by a ISO4217 code.
function createPool(PoolId poolId, address admin, AssetId currency) external payable;
}
contracts/common/interfaces/IMessageHandler.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
/// @notice Generic interface for entities that handle incoming messages
interface IMessageHandler {
/// @notice Dispatched when an invalid message is trying to handle
error InvalidMessage(uint8 code);
/// @notice Handling incoming messages.
/// @param tokenId Source chain
/// @param message Incoming message
function handle(uint16 tokenId, bytes calldata message) external;
}
contracts/common/interfaces/IRoot.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
interface IRoot {
// --- Events ---
event File(bytes32 indexed what, uint256 data);
event Pause();
event Unpause();
event ScheduleRely(address indexed target, uint256 indexed scheduledTime);
event CancelRely(address indexed target);
event RelyContract(address indexed target, address indexed user);
event DenyContract(address indexed target, address indexed user);
event Endorse(address indexed user);
event Veto(address indexed user);
error DelayTooLong();
error FileUnrecognizedParam();
error TargetNotScheduled();
error TargetNotReady();
/// @notice Returns whether the root is paused
function paused() external view returns (bool);
/// @notice Returns the current timelock for adding new wards
function delay() external view returns (uint256);
/// @notice Trusted contracts within the system
function endorsements(address target) external view returns (uint256);
/// @notice Returns when `relyTarget` has passed the timelock
function schedule(address relyTarget) external view returns (uint256 timestamp);
// --- Administration ---
/// @notice Updates a contract parameter
/// @param what Accepts a bytes32 representation of 'delay'
function file(bytes32 what, uint256 data) external;
/// --- Endorsements ---
/// @notice Endorses the `user`
/// @dev Endorsed users are trusted contracts in the system. They are allowed to bypass
/// token restrictions (e.g. the Escrow can automatically receive share class tokens by being endorsed), and
/// can automatically set operators in ERC-7540 vaults (e.g. the VaultRouter) is always an operator.
function endorse(address user) external;
/// @notice Removes the endorsed user
function veto(address user) external;
/// @notice Returns whether the user is endorsed
function endorsed(address user) external view returns (bool);
// --- Pause management ---
/// @notice Pause any contracts that depend on `Root.paused()`
function pause() external;
/// @notice Unpause any contracts that depend on `Root.paused()`
function unpause() external;
/// --- Timelocked ward management ---
/// @notice Schedule relying a new ward after the delay has passed
function scheduleRely(address target) external;
/// @notice Cancel a pending scheduled rely
function cancelRely(address target) external;
/// @notice Execute a scheduled rely
/// @dev Can be triggered by anyone since the scheduling is protected
function executeScheduledRely(address target) external;
/// --- External contract ward management ---
/// @notice Make an address a ward on any contract that Root is a ward on
function relyContract(address target, address user) external;
/// @notice Removes an address as a ward on any contract that Root is a ward on
function denyContract(address target, address user) external;
}
contracts/common/interfaces/adapters/IAxelarAdapter.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
import {IAdapter} from "contracts/common/interfaces/IAdapter.sol";
// From https://github.com/axelarnetwork/axelar-cgp-solidity/blob/main/contracts/interfaces/IAxelarGateway.sol
interface IAxelarGateway {
function callContract(string calldata destinationChain, string calldata contractAddress, bytes calldata payload)
external;
function validateContractCall(
bytes32 commandId,
string calldata sourceChain,
string calldata sourceAddress,
bytes32 payloadHash
) external returns (bool);
}
interface IAxelarGasService {
// From
// https://github.com/axelarnetwork/axelar-gmp-sdk-solidity/blob/00682b6c3db0cc922ec0c4ea3791852c93d7ae31/contracts/gas-estimation/InterchainGasEstimation.sol#L48
function estimateGasFee(
string calldata destinationChain,
string calldata destinationAddress,
bytes calldata payload,
uint256 executionGasLimit,
bytes calldata params
) external view returns (uint256 gasEstimate);
// From https://github.com/axelarnetwork/axelar-cgp-solidity/blob/main/contracts/interfaces/IAxelarGasService.sol
function payNativeGasForContractCall(
address sender,
string calldata destinationChain,
string calldata destinationAddress,
bytes calldata payload,
address refundAddress
) external payable;
}
// From
// https://github.com/axelarnetwork/axelar-gmp-sdk-solidity/blob/00682b6c3db0cc922ec0c4ea3791852c93d7ae31/contracts/interfaces/IAxelarExecutable.sol#L14
interface IAxelarExecutable {
/**
* @dev Thrown when a function is called with an invalid address.
*/
error InvalidAddress();
/**
* @dev Thrown when the call is not approved by the Axelar Gateway.
*/
error NotApprovedByGateway();
/**
* @notice Executes the specified command sent from another chain.
* @dev This function is called by the Axelar Gateway to carry out cross-chain commands.
* Reverts if the call is not approved by the gateway or other checks fail.
* @param commandId The identifier of the command to execute.
* @param sourceChain The name of the source chain from where the command originated.
* @param sourceAddress The address on the source chain that sent the command.
* @param payload The payload of the command to be executed. This typically includes the function selector and
* encoded arguments.
*/
function execute(
bytes32 commandId,
string calldata sourceChain,
string calldata sourceAddress,
bytes calldata payload
) external;
}
struct AxelarSource {
uint16 tokenId;
bytes32 addressHash;
}
struct AxelarDestination {
string axelarId;
string addr;
}
interface IAxelarAdapter is IAdapter, IAxelarExecutable {
event File(bytes32 indexed what, string axelarId, uint16 tokenId, string source);
event File(bytes32 indexed what, uint16 tokenId, string axelarId, string destination);
error FileUnrecognizedParam();
function file(bytes32 what, string calldata axelarId, uint16 tokenId, string calldata source) external;
function file(bytes32 what, uint16 tokenId, string calldata axelarId, string calldata destination) external;
/// @notice Returns the source configuration for a given axelar chain id
/// @param axelarId The Axelar ID of the remote chain
/// @return tokenId The remote chain id
/// @return addressHash The hash of the remote axelar adapter address
function sources(string calldata axelarId) external view returns (uint16 tokenId, bytes32 addressHash);
/// @notice Returns the destination configuration for a given chain id
/// @param tokenId The remote chain id
/// @return axelarId The Axelar ID of the remote chain
/// @return addr The address of the remote axelar adapter
function destinations(uint16 tokenId) external view returns (string memory axelarId, string memory addr);
}
contracts/common/interfaces/adapters/IMultiAdapter.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
import {IAdapter} from "contracts/common/interfaces/IAdapter.sol";
import {IMessageHandler} from "contracts/common/interfaces/IMessageHandler.sol";
uint8 constant MAX_ADAPTER_COUNT = 8;
/// @notice Interface for handling several adapters transparently
interface IMultiAdapter is IAdapter, IMessageHandler {
/// @dev Each adapter struct is packed with the quorum to reduce SLOADs on handle
struct Adapter {
/// @notice Starts at 1 and maps to id - 1 as the index on the adapters array
uint8 id;
/// @notice Number of votes required for a message to be executed
uint8 quorum;
/// @notice Each time the quorum is decreased, a new session starts which invalidates old votes
uint64 activeSessionId;
}
struct Inbound {
/// @dev Counts are stored as integers (instead of boolean values) to accommodate duplicate
/// messages (e.g. two investments from the same user with the same amount) being
/// processed in parallel. The entire struct is packed in a single bytes32 slot.
/// Max uint16 = 65,535 so at most 65,535 duplicate messages can be processed in parallel.
uint16[MAX_ADAPTER_COUNT] votes;
/// @notice Each time adapters are updated, a new session starts which invalidates old votes
uint64 sessionId;
bytes pending;
}
event File(bytes32 indexed what, address addr);
event File(bytes32 indexed what, uint16 tokenId, IAdapter[] adapters);
event HandlePayload(uint16 indexed tokenId, bytes32 indexed payloadId, bytes payload, IAdapter adapter);
event HandleProof(uint16 indexed tokenId, bytes32 indexed payloadId, bytes32 payloadHash, IAdapter adapter);
event SendPayload(
uint16 indexed tokenId,
bytes32 indexed payloadId,
bytes payload,
IAdapter adapter,
bytes32 adapterData,
address refund
);
event SendProof(
uint16 indexed tokenId,
bytes32 indexed payloadId,
bytes32 payloadHash,
IAdapter adapter,
bytes32 adapterData
);
event InitiateRecovery(uint16 tokenId, bytes32 payloadHash, IAdapter adapter);
event DisputeRecovery(uint16 tokenId, bytes32 payloadHash, IAdapter adapter);
event ExecuteRecovery(uint16 tokenId, bytes message, IAdapter adapter);
/// @notice Dispatched when the `what` parameter of `file()` is not supported by the implementation.
error FileUnrecognizedParam();
/// @notice Dispatched when the contract is configured with an empty adapter set.
error EmptyAdapterSet();
/// @notice Dispatched when the contract is configured with a number of adapter exceeding the maximum.
error ExceedsMax();
/// @notice Dispatched when the contract is configured with duplicate adapters.
error NoDuplicatesAllowed();
/// @notice Dispatched when the contract tries to handle a message from an adaptet not contained in the adapter set.
error InvalidAdapter();
/// @notice Dispatched when the contract is configured with an empty adapter set.
error NonProofAdapter();
/// @notice Dispatched when the contract tries to handle a payload from a non message adapter.
error NonPayloadAdapter();
/// @notice Dispatched when the contract tries to recover a recovery message, which is not allowed.
error RecoveryPayloadRecovered();
/// @notice Dispatched when a recovery message is executed without being initiated.
error RecoveryNotInitiated();
/// @notice Dispatched when a recovery message is executed without waiting the challenge period.
error RecoveryChallengePeriodNotEnded();
/// @notice Used to update an address ( state variable ) on very rare occasions.
/// @dev Currently used to update addresses of contract instances.
/// @param what The name of the variable to be updated.
/// @param data New address.
function file(bytes32 what, address data) external;
/// @notice Used to update an array of addresses ( state variable ) on very rare occasions.
/// @dev Currently it is used to update the supported adapters.
/// @param what The name of the variable to be updated.
/// @param tokenId Chain where the adapters are associated to.
/// @param value New addresses.
function file(bytes32 what, uint16 tokenId, IAdapter[] calldata value) external;
/// @notice Initiate recovery of a payload.
function initiateRecovery(uint16 tokenId, IAdapter adapter, bytes32 payloadHash) external;
/// @notice Dispute recovery of a payload.
function disputeRecovery(uint16 tokenId, IAdapter adapter, bytes32 payloadHash) external;
/// @notice Execute message recovery. After the challenge period, the recovery can be executed.
/// If a malign adapter initiates message recovery,
/// governance can dispute and immediately cancel the recovery, using any other valid adapter.
///
/// Only 1 recovery can be outstanding per message hash. If multiple adapters fail at the same time,
/// these will need to be recovered serially (increasing the challenge period for each failed adapter).
/// @param tokenId Chain where the adapter is configured for
/// @param adapter Adapter's address that the recovery is targeting
/// @param message Hash of the message to be recovered
function executeRecovery(uint16 tokenId, IAdapter adapter, bytes calldata message) external;
/// @notice A view method of the current quorum.abi
/// @dev Quorum shows the amount of votes needed in order for a message to be dispatched further.
/// The quorum is taken from the first adapter which is always the length of active adapters.
/// @param tokenId Chain where the adapter is configured for
/// return Needed amount
function quorum(uint16 tokenId) external view returns (uint8);
/// @notice Gets the current active routers session id.
/// @dev When the adapters are updated with new ones,
/// each new set of adapters has their own sessionId.
/// Currently it uses sessionId of the previous set and
/// increments it by 1. The idea of an activeSessionId is
/// to invalidate any incoming messages from previously used adapters.
/// @param tokenId Chain where the adapter is configured for
function activeSessionId(uint16 tokenId) external view returns (uint64);
/// @notice Counts how many times each incoming messages has been received per adapter.
/// @dev It supports parallel messages ( duplicates ). That means that the incoming messages could be
/// the result of two or more independ request from the user of the same type.
/// i.e. Same user would like to deposit same underlying asset with the same amount more then once.
/// @param tokenId Chain where the adapter is configured for
/// @param payloadHash The hash value of the incoming message.
function votes(uint16 tokenId, bytes32 payloadHash) external view returns (uint16[MAX_ADAPTER_COUNT] memory);
/// @notice Returns the address of the adapter at the given id.
/// @param tokenId Chain where the adapter is configured for
function adapters(uint16 tokenId, uint256 id) external view returns (IAdapter);
/// @notice Returns the timestamp when the given recovery can be executed.
/// @param tokenId Chain where the adapter is configured for
function recoveries(uint16 tokenId, IAdapter adapter, bytes32 payloadHash)
external
view
returns (uint256 timestamp);
}
contracts/common/interfaces/adapters/IWormholeAdapter.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
import {IAdapter} from "contracts/common/interfaces/IAdapter.sol";
// From https://github.com/wormhole-foundation/wormhole-solidity-sdk/blob/main/contracts/interfaces/IWormholeRelayer.sol#L75
interface IWormholeRelayer {
/**
* @notice Publishes an instruction for the default delivery provider
* to relay a payload to the address `targetAddress` on chain `targetChain`
* with gas limit `gasLimit` and `msg.value` equal to `receiverValue`
*
* Any refunds (from leftover gas) will be sent to `refundAddress` on chain `refundChain`
* `targetAddress` must implement the IWormholeReceiver interface
*
* This function must be called with `msg.value` equal to `quoteEVMDeliveryPrice(targetChain, receiverValue,
* gasLimit)`
*
* @param targetChain in Wormhole Chain ID format
* @param targetAddress address to call on targetChain (that implements IWormholeReceiver)
* @param payload arbitrary bytes to pass in as parameter in call to `targetAddress`
* @param receiverValue msg.value that delivery provider should pass in for call to `targetAddress` (in targetChain
* currency units)
* @param gasLimit gas limit with which to call `targetAddress`. Any units of gas unused will be refunded according
* to the
* `targetChainRefundPerGasUnused` rate quoted by the delivery provider
* @param refundChain The chain to deliver any refund to, in Wormhole Chain ID format
* @param refundAddress The address on `refundChain` to deliver any refund to
* @return sequence sequence number of published VAA containing delivery instructions
*/
function sendPayloadToEvm(
uint16 targetChain,
address targetAddress,
bytes memory payload,
uint256 receiverValue,
uint256 gasLimit,
uint16 refundChain,
address refundAddress
) external payable returns (uint64 sequence);
/**
* @notice Returns the price to request a relay to chain `targetChain`, using the default delivery provider
*
* @param targetChain in Wormhole Chain ID format
* @param receiverValue msg.value that delivery provider should pass in for call to `targetAddress` (in targetChain
* currency units)
* @param gasLimit gas limit with which to call `targetAddress`.
* @return nativePriceQuote Price, in units of current chain currency, that the delivery provider charges to perform
* the relay
* @return targetChainRefundPerGasUnused amount of target chain currency that will be refunded per unit of gas
* unused,
* if a refundAddress is specified.
* Note: This value can be overridden by the delivery provider on the target chain. The returned value here
* should be considered to be a
* promise by the delivery provider of the amount of refund per gas unused that will be returned to the
* refundAddress at the target chain.
* If a delivery provider decides to override, this will be visible as part of the emitted Delivery event on
* the target chain.
*/
function quoteEVMDeliveryPrice(uint16 targetChain, uint256 receiverValue, uint256 gasLimit)
external
view
returns (uint256 nativePriceQuote, uint256 targetChainRefundPerGasUnused);
/**
* @notice Returns the address of the current default delivery provider
* @return deliveryProvider The address of (the default delivery provider)'s contract on this source
* chain. This must be a contract that implements IDeliveryProvider.
*/
function getDefaultDeliveryProvider() external view returns (address deliveryProvider);
}
interface IWormholeDeliveryProvider {
/// @notice Returns the chain ID.
function chainId() external view returns (uint16);
}
// From
// https://github.com/wormhole-foundation/wormhole/blob/main/relayer/ethereum/contracts/interfaces/relayer/IWormholeReceiver.sol
interface IWormholeReceiver {
/**
* @notice When a `send` is performed with this contract as the target, this function will be
* invoked by the WormholeRelayer contract
*
* NOTE: This function should be restricted such that only the Wormhole Relayer contract can call it.
*
* We also recommend that this function checks that `sourceChain` and `sourceAddress` are indeed who
* you expect to have requested the calling of `send` on the source chain
*
* The invocation of this function corresponding to the `send` request will have msg.value equal
* to the receiverValue specified in the send request.
*
* If the invocation of this function reverts or exceeds the gas limit
* specified by the send requester, this delivery will result in a `ReceiverFailure`.
*
* @param payload - an arbitrary message which was included in the delivery by the
* requester. This message's signature will already have been verified (as long as msg.sender is the Wormhole
* Relayer contract)
* @param additionalMessages - Additional messages which were requested to be included in this delivery.
* Note: There are no contract-level guarantees that the messages in this array are what was requested
* so **you should verify any sensitive information given here!**
*
* For example, if a 'VaaKey' was specified on the source chain, then MAKE SURE the corresponding message here
* has valid signatures (by calling `parseAndVerifyVM(message)` on the Wormhole core contract)
*
* This field can be used to perform and relay TokenBridge or CCTP transfers, and there are example
* usages of this at
* https://github.com/wormhole-foundation/hello-token
* https://github.com/wormhole-foundation/hello-cctp
*
* @param sourceAddress - the (wormhole format) address on the sending chain which requested
* this delivery.
* @param sourceChain - the wormhole chain ID where this delivery was requested.
* @param deliveryHash - the VAA hash of the deliveryVAA.
*
*/
function receiveWormholeMessages(
bytes memory payload,
bytes[] memory additionalMessages,
bytes32 sourceAddress,
uint16 sourceChain,
bytes32 deliveryHash
) external payable;
}
struct WormholeSource {
uint16 tokenId;
address addr;
}
struct WormholeDestination {
uint16 wormholeId;
address addr;
}
interface IWormholeAdapter is IAdapter, IWormholeReceiver {
/// @dev see file() method
event File(bytes32 indexed what, uint16 fromChainId, uint16 toChainId, address addr);
error FileUnrecognizedParam();
error NotWormholeRelayer();
error InvalidSource();
/// @notice Configures the adapter
/// @param what Can be "sources" or "destinations".
/// @param addr if what == "sources", it represents the source
/// @param addr if what == "destinations", it represents the destination
function file(bytes32 what, uint16 tokenId, uint16 wormholeId, address addr) external;
/// @notice Returns the source configuration for a given wormhole chain id
/// @param wormholeId The remote wormhole id
/// @return tokenId The remote chain id
/// @return addr The address of the remote wormhole adapter
function sources(uint16 wormholeId) external view returns (uint16 tokenId, address addr);
/// @notice Returns the destination configuration for a given chain id
/// @param tokenId The remote chain id
/// @return wormholeId The remote wormhole id
/// @return addr The address of the remote wormhole adapter
function destinations(uint16 tokenId) external view returns (uint16 wormholeId, address addr);
}
contracts/common/libraries/MessageLib.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
import {CastLib} from "contracts/misc/libraries/CastLib.sol";
import {BytesLib} from "contracts/misc/libraries/BytesLib.sol";
import {PoolId} from "contracts/common/types/PoolId.sol";
import {AssetId} from "contracts/common/types/AssetId.sol";
// NOTE: Should never exceed 254 messages because id == 255 corresponds to message proofs
enum MessageType {
/// @dev Placeholder for null message type
_Invalid,
// -- Pool independent messages
ScheduleUpgrade,
CancelUpgrade,
RecoverTokens,
RegisterAsset,
_Placeholder5,
_Placeholder6,
_Placeholder7,
_Placeholder8,
_Placeholder9,
_Placeholder10,
_Placeholder11,
_Placeholder12,
_Placeholder13,
_Placeholder14,
_Placeholder15,
// -- Pool dependent messages
NotifyPool,
NotifyShareClass,
NotifyPricePoolPerShare,
NotifyPricePoolPerAsset,
NotifyShareMetadata,
UpdateShareHook,
InitiateTransferShares,
ExecuteTransferShares,
UpdateRestriction,
UpdateContract,
UpdateVault,
UpdateBalanceSheetManager,
UpdateHoldingAmount,
UpdateShares,
MaxAssetPriceAge,
MaxSharePriceAge,
Request,
RequestCallback,
SetRequestManager
}
/// @dev Used internally in the UpdateVault message (not represent a submessage)
enum VaultUpdateKind {
DeployAndLink,
Link,
Unlink
}
library MessageLib {
using MessageLib for bytes;
using BytesLib for bytes;
using CastLib for *;
error UnknownMessageType();
/// @dev Encode all message lengths in this constant to avoid a large list of if/elseif checks
/// and reduce generated bytecode.
/// If the message has some dynamic part, will be added later in `messageLength()`.
// forgefmt: disable-next-item
uint256 constant MESSAGE_LENGTHS_1 =
(33 << uint8(MessageType.ScheduleUpgrade) * 8) +
(33 << uint8(MessageType.CancelUpgrade) * 8) +
(161 << uint8(MessageType.RecoverTokens) * 8) +
(18 << uint8(MessageType.RegisterAsset) * 8) +
(0 << uint8(MessageType._Placeholder5) * 8) +
(0 << uint8(MessageType._Placeholder6) * 8) +
(0 << uint8(MessageType._Placeholder7) * 8) +
(0 << uint8(MessageType._Placeholder8) * 8) +
(0 << uint8(MessageType._Placeholder9) * 8) +
(0 << uint8(MessageType._Placeholder10) * 8) +
(0 << uint8(MessageType._Placeholder11) * 8) +
(0 << uint8(MessageType._Placeholder12) * 8) +
(0 << uint8(MessageType._Placeholder13) * 8) +
(0 << uint8(MessageType._Placeholder14) * 8) +
(0 << uint8(MessageType._Placeholder15) * 8) +
(9 << uint8(MessageType.NotifyPool) * 8) +
(250 << uint8(MessageType.NotifyShareClass) * 8) +
(49 << uint8(MessageType.NotifyPricePoolPerShare) * 8) +
(65 << uint8(MessageType.NotifyPricePoolPerAsset) * 8) +
(185 << uint8(MessageType.NotifyShareMetadata) * 8) +
(57 << uint8(MessageType.UpdateShareHook) * 8) +
(91 << uint8(MessageType.InitiateTransferShares) * 8) +
(73 << uint8(MessageType.ExecuteTransferShares) * 8) +
(25 << uint8(MessageType.UpdateRestriction) * 8) +
(57 << uint8(MessageType.UpdateContract) * 8) +
(74 << uint8(MessageType.UpdateVault) * 8) +
(42 << uint8(MessageType.UpdateBalanceSheetManager) * 8) +
(91 << uint8(MessageType.UpdateHoldingAmount) * 8) +
(59 << uint8(MessageType.UpdateShares) * 8) +
(49 << uint8(MessageType.MaxAssetPriceAge) * 8) +
(33 << uint8(MessageType.MaxSharePriceAge) * 8);
// forgefmt: disable-next-item
uint256 constant MESSAGE_LENGTHS_2 =
(41 << (uint8(MessageType.Request) - 32) * 8) +
(41 << (uint8(MessageType.RequestCallback) - 32) * 8) +
(73 << (uint8(MessageType.SetRequestManager) - 32) * 8);
function messageType(bytes memory message) internal pure returns (MessageType) {
return MessageType(message.toUint8(0));
}
function messageCode(bytes memory message) internal pure returns (uint8) {
return message.toUint8(0);
}
function messageLength(bytes memory message) internal pure returns (uint16 length) {
uint8 kind = message.toUint8(0);
require(kind <= uint8(type(MessageType).max), UnknownMessageType());
length = (kind <= 31)
? uint16(uint8(bytes32(MESSAGE_LENGTHS_1)[31 - kind]))
: uint16(uint8(bytes32(MESSAGE_LENGTHS_2)[63 - kind]));
// Special treatment for messages with dynamic size:
if (kind == uint8(MessageType.UpdateRestriction)) {
length += 2 + message.toUint16(length); //payloadLength
} else if (kind == uint8(MessageType.UpdateContract)) {
length += 2 + message.toUint16(length); //payloadLength
} else if (kind == uint8(MessageType.Request)) {
length += 2 + message.toUint16(length); //payloadLength
} else if (kind == uint8(MessageType.RequestCallback)) {
length += 2 + message.toUint16(length); //payloadLength
}
}
function messagePoolId(bytes memory message) internal pure returns (PoolId poolId) {
uint8 kind = message.toUint8(0);
// All messages from NotifyPool to the end contains a PoolId in position 1.
if (kind >= uint8(MessageType.NotifyPool)) {
return PoolId.wrap(message.toUint64(1));
} else {
return PoolId.wrap(0);
}
}
function messageSourceTokenId(bytes memory message) internal pure returns (uint16) {
uint8 kind = message.toUint8(0);
if (kind <= uint8(MessageType.RecoverTokens)) {
return 0; // Non tokenId associated
} else if (kind == uint8(MessageType.UpdateShares) || kind == uint8(MessageType.InitiateTransferShares)) {
return 0; // Non tokenId associated
} else if (kind == uint8(MessageType.RegisterAsset)) {
return AssetId.wrap(message.toUint128(1)).tokenId();
} else if (kind == uint8(MessageType.UpdateHoldingAmount)) {
return AssetId.wrap(message.toUint128(25)).tokenId();
} else if (kind == uint8(MessageType.Request)) {
return AssetId.wrap(message.toUint128(25)).tokenId();
} else {
return message.messagePoolId().tokenId();
}
}
//---------------------------------------
// ScheduleUpgrade
//---------------------------------------
struct ScheduleUpgrade {
bytes32 target;
}
function deserializeScheduleUpgrade(bytes memory data) internal pure returns (ScheduleUpgrade memory) {
require(messageType(data) == MessageType.ScheduleUpgrade, UnknownMessageType());
return ScheduleUpgrade({target: data.toBytes32(1)});
}
function serialize(ScheduleUpgrade memory t) internal pure returns (bytes memory) {
return abi.encodePacked(MessageType.ScheduleUpgrade, t.target);
}
//---------------------------------------
// CancelUpgrade
//---------------------------------------
struct CancelUpgrade {
bytes32 target;
}
function deserializeCancelUpgrade(bytes memory data) internal pure returns (CancelUpgrade memory) {
require(messageType(data) == MessageType.CancelUpgrade, UnknownMessageType());
return CancelUpgrade({target: data.toBytes32(1)});
}
function serialize(CancelUpgrade memory t) internal pure returns (bytes memory) {
return abi.encodePacked(MessageType.CancelUpgrade, t.target);
}
//---------------------------------------
// RecoverTokens
//---------------------------------------
struct RecoverTokens {
bytes32 target;
bytes32 token;
uint256 tokenId;
bytes32 to;
uint256 amount;
}
function deserializeRecoverTokens(bytes memory data) internal pure returns (RecoverTokens memory) {
require(messageType(data) == MessageType.RecoverTokens, UnknownMessageType());
return RecoverTokens({
target: data.toBytes32(1),
token: data.toBytes32(33),
tokenId: data.toUint256(65),
to: data.toBytes32(97),
amount: data.toUint256(129)
});
}
function serialize(RecoverTokens memory t) internal pure returns (bytes memory) {
return abi.encodePacked(MessageType.RecoverTokens, t.target, t.token, t.tokenId, t.to, t.amount);
}
//---------------------------------------
// RegisterAsset
//---------------------------------------
struct RegisterAsset {
uint128 assetId;
uint8 decimals;
}
function deserializeRegisterAsset(bytes memory data) internal pure returns (RegisterAsset memory) {
require(messageType(data) == MessageType.RegisterAsset, UnknownMessageType());
return RegisterAsset({assetId: data.toUint128(1), decimals: data.toUint8(17)});
}
function serialize(RegisterAsset memory t) internal pure returns (bytes memory) {
return abi.encodePacked(MessageType.RegisterAsset, t.assetId, t.decimals);
}
//---------------------------------------
// NotifyPool
//---------------------------------------
struct NotifyPool {
uint64 poolId;
}
function deserializeNotifyPool(bytes memory data) internal pure returns (NotifyPool memory) {
require(messageType(data) == MessageType.NotifyPool, UnknownMessageType());
return NotifyPool({poolId: data.toUint64(1)});
}
function serialize(NotifyPool memory t) internal pure returns (bytes memory) {
return abi.encodePacked(MessageType.NotifyPool, t.poolId);
}
//---------------------------------------
// NotifyShareClass
//---------------------------------------
struct NotifyShareClass {
uint64 poolId;
bytes16 scId;
string name; // Fixed to 128 bytes
bytes32 symbol; // utf8
uint8 decimals;
bytes32 salt;
bytes32 hook;
}
function deserializeNotifyShareClass(bytes memory data) internal pure returns (NotifyShareClass memory) {
require(messageType(data) == MessageType.NotifyShareClass, UnknownMessageType());
return NotifyShareClass({
poolId: data.toUint64(1),
scId: data.toBytes16(9),
name: data.slice(25, 128).bytes128ToString(),
symbol: data.toBytes32(153),
decimals: data.toUint8(185),
salt: data.toBytes32(186),
hook: data.toBytes32(218)
});
}
function serialize(NotifyShareClass memory t) internal pure returns (bytes memory) {
return abi.encodePacked(
MessageType.NotifyShareClass,
t.poolId,
t.scId,
bytes(t.name).sliceZeroPadded(0, 128),
t.symbol,
t.decimals,
t.salt,
t.hook
);
}
//---------------------------------------
// NotifyPricePoolPerShare
//---------------------------------------
struct NotifyPricePoolPerShare {
uint64 poolId;
bytes16 scId;
uint128 price;
uint64 timestamp;
}
function deserializeNotifyPricePoolPerShare(bytes memory data)
internal
pure
returns (NotifyPricePoolPerShare memory)
{
require(messageType(data) == MessageType.NotifyPricePoolPerShare, UnknownMessageType());
return NotifyPricePoolPerShare({
poolId: data.toUint64(1),
scId: data.toBytes16(9),
price: data.toUint128(25),
timestamp: data.toUint64(41)
});
}
function serialize(NotifyPricePoolPerShare memory t) internal pure returns (bytes memory) {
return abi.encodePacked(MessageType.NotifyPricePoolPerShare, t.poolId, t.scId, t.price, t.timestamp);
}
//---------------------------------------
// NotifyPricePoolPerAsset
//---------------------------------------
struct NotifyPricePoolPerAsset {
uint64 poolId;
bytes16 scId;
uint128 assetId;
uint128 price;
uint64 timestamp;
}
function deserializeNotifyPricePoolPerAsset(bytes memory data)
internal
pure
returns (NotifyPricePoolPerAsset memory)
{
require(messageType(data) == MessageType.NotifyPricePoolPerAsset, UnknownMessageType());
return NotifyPricePoolPerAsset({
poolId: data.toUint64(1),
scId: data.toBytes16(9),
assetId: data.toUint128(25),
price: data.toUint128(41),
timestamp: data.toUint64(57)
});
}
function serialize(NotifyPricePoolPerAsset memory t) internal pure returns (bytes memory) {
return abi.encodePacked(MessageType.NotifyPricePoolPerAsset, t.poolId, t.scId, t.assetId, t.price, t.timestamp);
}
//---------------------------------------
// NotifyShareMetadata
//---------------------------------------
struct NotifyShareMetadata {
uint64 poolId;
bytes16 scId;
string name; // Fixed to 128 bytes
bytes32 symbol; // utf8
}
function deserializeNotifyShareMetadata(bytes memory data) internal pure returns (NotifyShareMetadata memory) {
require(messageType(data) == MessageType.NotifyShareMetadata, UnknownMessageType());
return NotifyShareMetadata({
poolId: data.toUint64(1),
scId: data.toBytes16(9),
name: data.slice(25, 128).bytes128ToString(),
symbol: data.toBytes32(153)
});
}
function serialize(NotifyShareMetadata memory t) internal pure returns (bytes memory) {
return abi.encodePacked(
MessageType.NotifyShareMetadata, t.poolId, t.scId, bytes(t.name).sliceZeroPadded(0, 128), t.symbol
);
}
//---------------------------------------
// UpdateShareHook
//---------------------------------------
struct UpdateShareHook {
uint64 poolId;
bytes16 scId;
bytes32 hook;
}
function deserializeUpdateShareHook(bytes memory data) internal pure returns (UpdateShareHook memory) {
require(messageType(data) == MessageType.UpdateShareHook, UnknownMessageType());
return UpdateShareHook({poolId: data.toUint64(1), scId: data.toBytes16(9), hook: data.toBytes32(25)});
}
function serialize(UpdateShareHook memory t) internal pure returns (bytes memory) {
return abi.encodePacked(MessageType.UpdateShareHook, t.poolId, t.scId, t.hook);
}
//---------------------------------------
// InitiateTransferShares
//---------------------------------------
struct InitiateTransferShares {
uint64 poolId;
bytes16 scId;
uint16 tokenId;
bytes32 receiver;
uint128 amount;
uint128 extraGasLimit;
}
function deserializeInitiateTransferShares(bytes memory data)
internal
pure
returns (InitiateTransferShares memory)
{
require(messageType(data) == MessageType.InitiateTransferShares, UnknownMessageType());
return InitiateTransferShares({
poolId: data.toUint64(1),
scId: data.toBytes16(9),
tokenId: data.toUint16(25),
receiver: data.toBytes32(27),
amount: data.toUint128(59),
extraGasLimit: data.toUint128(75)
});
}
function serialize(InitiateTransferShares memory t) internal pure returns (bytes memory) {
return abi.encodePacked(
MessageType.InitiateTransferShares, t.poolId, t.scId, t.tokenId, t.receiver, t.amount, t.extraGasLimit
);
}
//---------------------------------------
// ExecuteTransferShares
//---------------------------------------
struct ExecuteTransferShares {
uint64 poolId;
bytes16 scId;
bytes32 receiver;
uint128 amount;
}
function deserializeExecuteTransferShares(bytes memory data) internal pure returns (ExecuteTransferShares memory) {
require(messageType(data) == MessageType.ExecuteTransferShares, UnknownMessageType());
return ExecuteTransferShares({
poolId: data.toUint64(1),
scId: data.toBytes16(9),
receiver: data.toBytes32(25),
amount: data.toUint128(57)
});
}
function serialize(ExecuteTransferShares memory t) internal pure returns (bytes memory) {
return abi.encodePacked(MessageType.ExecuteTransferShares, t.poolId, t.scId, t.receiver, t.amount);
}
//---------------------------------------
// UpdateRestriction
//---------------------------------------
struct UpdateRestriction {
uint64 poolId;
bytes16 scId;
bytes payload; // As sequence of bytes
}
function deserializeUpdateRestriction(bytes memory data) internal pure returns (UpdateRestriction memory) {
require(messageType(data) == MessageType.UpdateRestriction, UnknownMessageType());
uint16 payloadLength = data.toUint16(25);
return UpdateRestriction({
poolId: data.toUint64(1),
scId: data.toBytes16(9),
payload: data.slice(27, payloadLength)
});
}
function serialize(UpdateRestriction memory t) internal pure returns (bytes memory) {
return abi.encodePacked(MessageType.UpdateRestriction, t.poolId, t.scId, uint16(t.payload.length), t.payload);
}
//---------------------------------------
// UpdateContract
//---------------------------------------
struct UpdateContract {
uint64 poolId;
bytes16 scId;
bytes32 target;
bytes payload; // As sequence of bytes
}
function deserializeUpdateContract(bytes memory data) internal pure returns (UpdateContract memory) {
require(messageType(data) == MessageType.UpdateContract, UnknownMessageType());
uint16 payloadLength = data.toUint16(57);
return UpdateContract({
poolId: data.toUint64(1),
scId: data.toBytes16(9),
target: data.toBytes32(25),
payload: data.slice(59, payloadLength)
});
}
function serialize(UpdateContract memory t) internal pure returns (bytes memory) {
return abi.encodePacked(
MessageType.UpdateContract, t.poolId, t.scId, t.target, uint16(t.payload.length), t.payload
);
}
//---------------------------------------
// Request
//---------------------------------------
struct Request {
uint64 poolId;
bytes16 scId;
uint128 assetId;
bytes payload; // As sequence of bytes
}
function deserializeRequest(bytes memory data) internal pure returns (Request memory) {
require(messageType(data) == MessageType.Request, UnknownMessageType());
uint16 payloadLength = data.toUint16(41);
return Request({
poolId: data.toUint64(1),
scId: data.toBytes16(9),
assetId: data.toUint128(25),
payload: data.slice(43, payloadLength)
});
}
function serialize(Request memory t) internal pure returns (bytes memory) {
return abi.encodePacked(MessageType.Request, t.poolId, t.scId, t.assetId, uint16(t.payload.length), t.payload);
}
//---------------------------------------
// RequestCallback
//---------------------------------------
struct RequestCallback {
uint64 poolId;
bytes16 scId;
uint128 assetId;
bytes payload; // As sequence of bytes
}
function deserializeRequestCallback(bytes memory data) internal pure returns (RequestCallback memory) {
require(messageType(data) == MessageType.RequestCallback, UnknownMessageType());
uint16 payloadLength = data.toUint16(41);
return RequestCallback({
poolId: data.toUint64(1),
scId: data.toBytes16(9),
assetId: data.toUint128(25),
payload: data.slice(43, payloadLength)
});
}
function serialize(RequestCallback memory t) internal pure returns (bytes memory) {
return abi.encodePacked(
MessageType.RequestCallback, t.poolId, t.scId, t.assetId, uint16(t.payload.length), t.payload
);
}
//---------------------------------------
// VaultUpdate
//---------------------------------------
struct UpdateVault {
uint64 poolId;
bytes16 scId;
uint128 assetId;
bytes32 vaultOrFactory;
uint8 kind;
}
function deserializeUpdateVault(bytes memory data) internal pure returns (UpdateVault memory) {
require(messageType(data) == MessageType.UpdateVault, UnknownMessageType());
return UpdateVault({
poolId: data.toUint64(1),
scId: data.toBytes16(9),
assetId: data.toUint128(25),
vaultOrFactory: data.toBytes32(41),
kind: data.toUint8(73)
});
}
function serialize(UpdateVault memory t) internal pure returns (bytes memory) {
return abi.encodePacked(MessageType.UpdateVault, t.poolId, t.scId, t.assetId, t.vaultOrFactory, t.kind);
}
//---------------------------------------
// SetRequestManager
//---------------------------------------
struct SetRequestManager {
uint64 poolId;
bytes16 scId;
uint128 assetId;
bytes32 manager;
}
function deserializeSetRequestManager(bytes memory data) internal pure returns (SetRequestManager memory) {
require(messageType(data) == MessageType.SetRequestManager, UnknownMessageType());
return SetRequestManager({
poolId: data.toUint64(1),
scId: data.toBytes16(9),
assetId: data.toUint128(25),
manager: data.toBytes32(41)
});
}
function serialize(SetRequestManager memory t) internal pure returns (bytes memory) {
return abi.encodePacked(MessageType.SetRequestManager, t.poolId, t.scId, t.assetId, t.manager);
}
//---------------------------------------
// UpdateBalanceSheetManager
//---------------------------------------
struct UpdateBalanceSheetManager {
uint64 poolId;
bytes32 who;
bool canManage;
}
function deserializeUpdateBalanceSheetManager(bytes memory data)
internal
pure
returns (UpdateBalanceSheetManager memory)
{
require(messageType(data) == MessageType.UpdateBalanceSheetManager, UnknownMessageType());
return UpdateBalanceSheetManager({poolId: data.toUint64(1), who: data.toBytes32(9), canManage: data.toBool(41)});
}
function serialize(UpdateBalanceSheetManager memory t) internal pure returns (bytes memory) {
return abi.encodePacked(MessageType.UpdateBalanceSheetManager, t.poolId, t.who, t.canManage);
}
//---------------------------------------
// UpdateHoldingAmount
//---------------------------------------
struct UpdateHoldingAmount {
uint64 poolId;
bytes16 scId;
uint128 assetId;
uint128 amount;
uint128 pricePerUnit;
uint64 timestamp;
bool isIncrease;
bool isSnapshot;
uint64 nonce;
}
function deserializeUpdateHoldingAmount(bytes memory data) internal pure returns (UpdateHoldingAmount memory h) {
require(messageType(data) == MessageType.UpdateHoldingAmount, "UnknownMessageType");
return UpdateHoldingAmount({
poolId: data.toUint64(1),
scId: data.toBytes16(9),
assetId: data.toUint128(25),
amount: data.toUint128(41),
pricePerUnit: data.toUint128(57),
timestamp: data.toUint64(73),
isIncrease: data.toBool(81),
isSnapshot: data.toBool(82),
nonce: data.toUint64(83)
});
}
function serialize(UpdateHoldingAmount memory t) internal pure returns (bytes memory) {
return abi.encodePacked(
MessageType.UpdateHoldingAmount,
t.poolId,
t.scId,
t.assetId,
t.amount,
t.pricePerUnit,
t.timestamp,
t.isIncrease,
t.isSnapshot,
t.nonce
);
}
//---------------------------------------
// UpdateShares
//---------------------------------------
struct UpdateShares {
uint64 poolId;
bytes16 scId;
uint128 shares;
uint64 timestamp;
bool isIssuance;
bool isSnapshot;
uint64 nonce;
}
function deserializeUpdateShares(bytes memory data) internal pure returns (UpdateShares memory) {
require(messageType(data) == MessageType.UpdateShares, UnknownMessageType());
return UpdateShares({
poolId: data.toUint64(1),
scId: data.toBytes16(9),
shares: data.toUint128(25),
timestamp: data.toUint64(41),
isIssuance: data.toBool(49),
isSnapshot: data.toBool(50),
nonce: data.toUint64(51)
});
}
function serialize(UpdateShares memory t) internal pure returns (bytes memory) {
return abi.encodePacked(
MessageType.UpdateShares, t.poolId, t.scId, t.shares, t.timestamp, t.isIssuance, t.isSnapshot, t.nonce
);
}
//---------------------------------------
// MaxAssetPriceAge
//---------------------------------------
struct MaxAssetPriceAge {
uint64 poolId;
bytes16 scId;
uint128 assetId;
uint64 maxPriceAge;
}
function deserializeMaxAssetPriceAge(bytes memory data) internal pure returns (MaxAssetPriceAge memory) {
require(messageType(data) == MessageType.MaxAssetPriceAge, UnknownMessageType());
return MaxAssetPriceAge({
poolId: data.toUint64(1),
scId: data.toBytes16(9),
assetId: data.toUint128(25),
maxPriceAge: data.toUint64(41)
});
}
function serialize(MaxAssetPriceAge memory t) internal pure returns (bytes memory) {
return abi.encodePacked(MessageType.MaxAssetPriceAge, t.poolId, t.scId, t.assetId, t.maxPriceAge);
}
//---------------------------------------
// MaxSharePriceAge
//---------------------------------------
struct MaxSharePriceAge {
uint64 poolId;
bytes16 scId;
uint64 maxPriceAge;
}
function deserializeMaxSharePriceAge(bytes memory data) internal pure returns (MaxSharePriceAge memory) {
require(messageType(data) == MessageType.MaxSharePriceAge, UnknownMessageType());
return MaxSharePriceAge({poolId: data.toUint64(1), scId: data.toBytes16(9), maxPriceAge: data.toUint64(25)});
}
function serialize(MaxSharePriceAge memory t) internal pure returns (bytes memory) {
return abi.encodePacked(MessageType.MaxSharePriceAge, t.poolId, t.scId, t.maxPriceAge);
}
}
contracts/common/types/AssetId.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
/// @dev Composite Id of the tokenId (uint16) where the asset resides
/// and a local counter (uint64) that is part of the contract that registers the asset.
type AssetId is uint128;
function isNull(AssetId assetId) pure returns (bool) {
return AssetId.unwrap(assetId) == 0;
}
function raw(AssetId assetId) pure returns (uint128) {
return AssetId.unwrap(assetId);
}
function tokenId(AssetId assetId) pure returns (uint16) {
return uint16(AssetId.unwrap(assetId) >> 112);
}
function newAssetId(uint16 tokenId_, uint64 counter) pure returns (AssetId) {
return AssetId.wrap((uint128(tokenId_) << 112) + counter);
}
function newAssetId(uint32 isoCode) pure returns (AssetId) {
return AssetId.wrap(isoCode);
}
function eq(AssetId a, AssetId b) pure returns (bool) {
return a.raw() == b.raw();
}
using {isNull, raw, tokenId, eq} for AssetId global;
contracts/common/types/PoolId.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
import {MathLib} from "contracts/misc/libraries/MathLib.sol";
using MathLib for uint256;
type PoolId is uint64;
function tokenId(PoolId poolId) pure returns (uint16) {
return uint16(PoolId.unwrap(poolId) >> 48);
}
function newPoolId(uint16 tokenId_, uint48 localPoolId) pure returns (PoolId) {
return PoolId.wrap((uint64(tokenId_) << 48) | uint64(localPoolId));
}
function isNull(PoolId poolId) pure returns (bool) {
return PoolId.unwrap(poolId) == 0;
}
function isEqual(PoolId a, PoolId b) pure returns (bool) {
return PoolId.unwrap(a) == PoolId.unwrap(b);
}
function raw(PoolId poolId) pure returns (uint64) {
return PoolId.unwrap(poolId);
}
using {tokenId, isNull, raw, isEqual as ==} for PoolId global;
contracts/common/types/ShareClassId.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
import {PoolId} from "contracts/common/types/PoolId.sol";
type ShareClassId is bytes16;
function isNull(ShareClassId scId) pure returns (bool) {
return ShareClassId.unwrap(scId) == 0;
}
function equals(ShareClassId left, ShareClassId right) pure returns (bool) {
return ShareClassId.unwrap(left) == ShareClassId.unwrap(right);
}
function raw(ShareClassId scId) pure returns (bytes16) {
return ShareClassId.unwrap(scId);
}
function newShareClassId(PoolId poolId, uint32 index) pure returns (ShareClassId scId) {
return ShareClassId.wrap(bytes16((uint128(PoolId.unwrap(poolId)) << 64) + index));
}
using {isNull, raw, equals as ==} for ShareClassId global;
contracts/misc/interfaces/IAuth.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
interface IAuth {
event Rely(address indexed user);
event Deny(address indexed user);
error NotAuthorized();
/// @notice Returns whether the target is a ward (has admin access)
function wards(address target) external view returns (uint256);
/// @notice Make user a ward (give them admin access)
function rely(address user) external;
/// @notice Remove user as a ward (remove admin access)
function deny(address user) external;
}
contracts/misc/libraries/BytesLib.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
/// @title Bytes Lib
/// @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
/// The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
/// @author Modified from Solidity Bytes Arrays Utils v0.8.0
library BytesLib {
error SliceOverflow();
error SliceOutOfBounds();
function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory) {
unchecked {
require(_length + 31 >= _length, SliceOverflow());
}
require(_bytes.length >= _start + _length, SliceOutOfBounds());
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} { mstore(mc, mload(cc)) }
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function sliceZeroPadded(bytes memory _bytes, uint256 _start, uint256 _length)
internal
pure
returns (bytes memory)
{
bool needsPad = _bytes.length < _start + _length;
if (!needsPad) return slice(_bytes, _start, _length);
bytes memory slice_ = slice(_bytes, _start, _bytes.length - _start);
bytes memory padding = new bytes(_length + _start - _bytes.length);
return bytes.concat(slice_, padding);
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_bytes.length >= _start + 20, SliceOutOfBounds());
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
require(_bytes.length >= _start + 1, SliceOutOfBounds());
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
require(_bytes.length >= _start + 2, SliceOutOfBounds());
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
require(_bytes.length >= _start + 4, SliceOutOfBounds());
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
require(_bytes.length >= _start + 8, SliceOutOfBounds());
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
require(_bytes.length >= _start + 16, SliceOutOfBounds());
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
require(_bytes.length >= _start + 32, SliceOutOfBounds());
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
require(_bytes.length >= _start + 32, SliceOutOfBounds());
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function toBytes16(bytes memory _bytes, uint256 _start) internal pure returns (bytes16) {
require(_bytes.length >= _start + 16, SliceOutOfBounds());
bytes16 tempBytes16;
assembly {
tempBytes16 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes16;
}
function toBool(bytes memory _bytes, uint256 _start) internal pure returns (bool) {
require(_bytes.length > _start, SliceOutOfBounds());
return _bytes[_start] != 0;
}
}
contracts/misc/libraries/CastLib.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
/// @title CastLib
library CastLib {
function toAddressLeftPadded(bytes32 addr) internal pure returns (address) {
require(bytes12(addr) == 0, "First 12 bytes should be zero");
return address(uint160(uint256(addr)));
}
function toBytes32LeftPadded(address addr) internal pure returns (bytes32) {
return bytes32(uint256(uint160(addr)));
}
function toAddress(bytes32 addr) internal pure returns (address) {
require(uint96(uint256(addr)) == 0, "Input should be 20 bytes");
return address(bytes20(addr));
}
function toBytes32(address addr) internal pure returns (bytes32) {
return bytes32(bytes20(addr));
}
/// @dev Adds zero padding
function toBytes32(string memory source) internal pure returns (bytes32) {
return bytes32(bytes(source));
}
/// @dev Removes zero padding
function bytes128ToString(bytes memory _bytes128) internal pure returns (string memory) {
require(_bytes128.length == 128, "Input should be 128 bytes");
uint8 i = 0;
while (i < 128 && _bytes128[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (uint8 j; j < i; j++) {
bytesArray[j] = _bytes128[j];
}
return string(bytesArray);
}
function toString(bytes32 _bytes32) internal pure returns (string memory) {
uint8 i = 0;
while (i < 32 && _bytes32[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
}
contracts/misc/libraries/MathLib.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
library MathLib {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
error MulDiv_Overflow();
error Uint8_Overflow();
error Uint32_Overflow();
error Uint64_Overflow();
error Uint128_Overflow();
error Int128_Overflow();
uint256 public constant One27 = 10 ** 27;
/// @notice Returns x^n with rounding precision of base
///
/// @dev Source: https://github.com/makerdao/dss/blob/fa4f6630afb0624d04a003e920b0d71a00331d98/src/jug.sol#L62
///
/// @param x The base value which should be exponentiated
/// @param n The exponent
/// @param base The scaling base, typically used for fix-point calculations
function rpow(uint256 x, uint256 n, uint256 base) public pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 { z := base }
default { z := 0 }
}
default {
switch mod(n, 2)
case 0 { z := base }
default { z := x }
let half := div(base, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n, 2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0, 0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0, 0) }
x := div(xxRound, base)
if mod(n, 2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0, 0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0, 0) }
z := div(zxRound, base)
}
}
}
}
}
/// @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
/// denominator == 0
/// @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
/// with further edits by Uniswap Labs also under MIT license.
// slither-disable-start divide-before-multiply
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, MulDiv_Overflow());
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
// slither-disable-end divide-before-multiply
/// @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/// @notice Safe type conversion from uint256 to uint8.
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, Uint8_Overflow());
return uint8(value);
}
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, Uint32_Overflow());
return uint32(value);
}
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, Uint64_Overflow());
return uint64(value);
}
/// @notice Safe type conversion from uint256 to uint128.
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, Uint128_Overflow());
return uint128(value);
}
/// @notice Returns the smallest of two numbers.
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? b : a;
}
/// @notice Returns the largest of two numbers.
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
}
contracts/misc/types/D18.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
// Small library to handle fixed point number operations with 18 decimals with static typing support.
import {MathLib} from "contracts/misc/libraries/MathLib.sol";
type D18 is uint128;
using MathLib for uint256;
/// @dev add two D18 types
function add(D18 d1, D18 d2) pure returns (D18) {
return D18.wrap(D18.unwrap(d1) + D18.unwrap(d2));
}
/// @dev substract two D18 types
function sub(D18 d1, D18 d2) pure returns (D18) {
return D18.wrap(D18.unwrap(d1) - D18.unwrap(d2));
}
/// @dev Divides one D18 by another one while retaining precision:
/// - nominator (decimal): 50e18
/// - denominator (decimal): 2e19
/// - result (decimal): 25e17
function divD18(D18 d1, D18 d2) pure returns (D18) {
return D18.wrap(MathLib.mulDiv(D18.unwrap(d1), 1e18, D18.unwrap(d2)).toUint128());
}
/// @dev Multiplies one D18 with another one while retaining precision:
/// - value1 (decimal): 50e18
/// - value2 (decimal): 2e19
/// - result (decimal): 100e19
function mulD18(D18 d1, D18 d2) pure returns (D18) {
return D18.wrap(MathLib.mulDiv(D18.unwrap(d1), D18.unwrap(d2), 1e18).toUint128());
}
/// @dev Returns the reciprocal of a D18 decimal, i.e. 1 / d.
/// Example: if d = 2.0 (2e18 internally), reciprocal(d) = 0.5 (5e17 internally).
function reciprocal(D18 d) pure returns (D18) {
uint128 val = D18.unwrap(d);
require(val != 0, "D18/division-by-zero");
return d18(1e18, val);
}
/// @dev Multiplies a decimal by an integer. i.e:
/// - d (decimal): 1_500_000_000_000_000_000
/// - value (integer): 4_000_000_000_000_000_000
/// - result (integer): 6_000_000_000_000_000_000
function mulUint128(D18 d, uint128 value, MathLib.Rounding rounding) pure returns (uint128) {
return MathLib.mulDiv(D18.unwrap(d), value, 1e18, rounding).toUint128();
}
/// @dev Multiplies a decimal by an integer. i.e:
/// - d (decimal): 1_500_000_000_000_000_000
/// - value (integer): 4_000_000_000_000_000_000
/// - result (integer): 6_000_000_000_000_000_000
function mulUint256(D18 d, uint256 value, MathLib.Rounding rounding) pure returns (uint256) {
return MathLib.mulDiv(D18.unwrap(d), value, 1e18, rounding);
}
/// @dev Divides an integer by a decimal, i.e.
/// @dev Same as mulDiv for integers, i.e:
/// - d (decimal): 2_000_000_000_000_000_000
/// - value (integer): 100_000_000_000_000_000_000
/// - result (integer): 50_000_000_000_000_000_000
function reciprocalMulUint128(D18 d, uint128 value, MathLib.Rounding rounding) pure returns (uint128) {
return MathLib.mulDiv(value, 1e18, d.raw(), rounding).toUint128();
}
/// @dev Divides an integer by a decimal, i.e.
/// @dev Same as mulDiv for integers, i.e:
/// - d (decimal): 2_000_000_000_000_000_000
/// - value (integer): 100_000_000_000_000_000_000
/// - result (integer): 50_000_000_000_000_000_000
function reciprocalMulUint256(D18 d, uint256 value, MathLib.Rounding rounding) pure returns (uint256) {
return MathLib.mulDiv(value, 1e18, d.raw(), rounding);
}
/// @dev Easy way to construct a decimal number
function d18(uint128 value) pure returns (D18) {
return D18.wrap(value);
}
/// @dev Easy way to construct a decimal number
function d18(uint128 num, uint128 den) pure returns (D18) {
return D18.wrap(MathLib.mulDiv(num, 1e18, den).toUint128());
}
function eq(D18 a, D18 b) pure returns (bool) {
return D18.unwrap(a) == D18.unwrap(b);
}
function isZero(D18 a) pure returns (bool) {
return D18.unwrap(a) == 0;
}
function isNotZero(D18 a) pure returns (bool) {
return D18.unwrap(a) != 0;
}
function raw(D18 d) pure returns (uint128) {
return D18.unwrap(d);
}
using {
add as +,
sub as -,
divD18 as /,
eq,
mulD18 as *,
mulUint128,
mulUint256,
reciprocalMulUint128,
reciprocalMulUint256,
reciprocal,
raw,
isZero,
isNotZero
} for D18 global;
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": true
},
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.