Verified contractExactBUSL-1.1
MasterDeployer
Address0x27d18d4d55ce5ad855cf0f80c1e2a52f5aa90a9d
- Balance
0 ETH
- Transactions
8
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,493,476
- Creation transaction
- 0xf41ae2abfa…51410cfbe6
26 files
- src/tokenized-vaults/MasterDeployer.solmain30.27 KB
- lib/open-zeppelin/interfaces/draft-IERC1822.sol879 B
- lib/open-zeppelin/proxy/ERC1967/ERC1967Proxy.sol1.29 KB
- lib/open-zeppelin/proxy/ERC1967/ERC1967Upgrade.sol6.37 KB
- lib/open-zeppelin/proxy/Proxy.sol3.25 KB
- lib/open-zeppelin/proxy/beacon/IBeacon.sol450 B
- lib/open-zeppelin/proxy/transparent/TransparentUpgradeableProxy.sol5.55 KB
- lib/open-zeppelin/token/ERC20/IERC20.sol2.74 KB
- lib/open-zeppelin/token/ERC20/extensions/IERC20Metadata.sol683 B
- lib/open-zeppelin/utils/Address.sol9.37 KB
- lib/open-zeppelin/utils/StorageSlot.sol4.11 KB
- src/core/BaseReentrancy.sol2.75 KB
- src/core/Ownable2StepsGuarded.sol2.02 KB
- src/core/OwnableGuarded.sol4.55 KB
- src/core/ProxyAdminOwnable2Steps.sol2.84 KB
- src/core/ResourceBasedTimelockedCall.sol3.95 KB
- src/core/interfaces/IConfigurableMintableToken.sol199 B
- src/core/interfaces/IFeeCollectorsAware.sol382 B
- src/core/interfaces/IKycRegistry.sol1.82 KB
- src/core/interfaces/IOperableResource.sol213 B
- src/core/interfaces/IOwnable.sol203 B
- src/core/interfaces/IOwnable2StepsGuarded.sol260 B
- src/core/interfaces/IResourceBasedTimelockedCall.sol1.15 KB
- src/core/interfaces/ITransferPolicy.sol1.01 KB
- src/tokenized-vaults/ITokenizedVault.sol1.16 KB
- src/tokenized-vaults/IWhitelistsDeployer.sol1.88 KB
src/tokenized-vaults/MasterDeployer.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import {IERC20Metadata} from "lib/open-zeppelin/token/ERC20/extensions/IERC20Metadata.sol";
import {IConfigurableMintableToken} from "../core/interfaces/IConfigurableMintableToken.sol";
import {ITransferPolicy, ITransferPolicyGated} from "../core/interfaces/ITransferPolicy.sol";
import {IKycRegistry} from "../core/interfaces/IKycRegistry.sol";
import {ITokenizedVault} from "./ITokenizedVault.sol";
import {IWhitelistsDeployer} from "./IWhitelistsDeployer.sol";
import {IFeeCollectorsAware} from "../core/interfaces/IFeeCollectorsAware.sol";
import {IOwnable} from "../core/interfaces/IOwnable.sol";
import {IOwnable2StepsGuarded} from "../core/interfaces/IOwnable2StepsGuarded.sol";
import {Ownable2StepsGuarded} from "../core/Ownable2StepsGuarded.sol";
import {ProxyAdminOwnable2Steps, TransparentUpgradeableProxy} from "../core/ProxyAdminOwnable2Steps.sol";
import {ResourceBasedTimelockedCall} from "../core/ResourceBasedTimelockedCall.sol";
/**
* @title Master Deployer of Tokenized Vaults
*/
contract MasterDeployer is Ownable2StepsGuarded {
error LayerZeroEndpointNotAvailable();
error LayerZeroEndpointAlreadySet();
error InvalidErc20();
error ZeroAddressError();
error DeployerNotWhitelisted();
error DeployerAlreadyWhitelisted();
error TokenImplementationNotSet();
error VaultImplementationNotSet();
error KycRegistryNotSet();
error TransferPolicyNotSet();
error AddressAlreadyTaken();
error InvalidTokenDecimals();
error ProxyAdminDeploymentFailed();
error ProxyDeploymentFailed();
error DeploymentAlreadyExecuted();
error DeploymentSpecRequired();
error WhitelistsDeployerRequired();
error OwnershipExpected();
error OwnershipAcceptanceFailed();
error DeployerAlreadySet();
bytes32 private constant _VAULT_PROXYADMIN_PREFIX = bytes32("VaultProxyAdmin.");
bytes32 private constant _VAULT_PROXY_PREFIX = bytes32("VaultProxy.");
bytes32 private constant _TOKEN_PROXYADMIN_PREFIX = bytes32("TokenProxyAdmin.");
bytes32 private constant _TOKEN_PROXY_PREFIX = bytes32("TokenProxy.");
bytes32 private constant _PLATFORM_VENDOR_PREFIX = bytes32("Upshift.");
/// @dev The two flags are independent. `kycRequired` keeps its meaning from earlier factories: it deploys a
/// senders whitelist owned by `vaultProxyOwner`. `kycPolicyRequired` sets `kycRegistryAddress` as the transfer
/// policy of the LP token, so the token implementation must implement `ITransferPolicyGated`. With
/// `kycPolicyRequired` false, the deployment is the same as with earlier factories.
struct Spec {
address referenceAsset;
bool kycRequired;
bool kycPolicyRequired;
uint8 lpTokenDecimals;
string lpTokenSymbol;
string lpTokenName;
string orgName;
string entropyA;
string entropyB;
string entropyC;
string entropyD;
address tokenProxyOwner;
address tokenProxyAdminOwner;
address vaultProxyOwner;
address vaultProxyAdminOwner;
address operatorAddress;
IFeeCollectorsAware.CollectorDefinition[] feeCollectors;
IFeeCollectorsAware.CollectorDefinition[] performanceFeeCollectors;
uint256 maxDepositAmount;
uint256 maxWithdrawalAmount;
uint256 instantRedemptionFee;
uint256 lagDuration;
uint256 withdrawalFee;
uint256 watermarkTimeWindow;
uint256 maxChangePercent;
uint256 managementFeePercent;
uint256 performanceFeeRate;
}
struct DeploymentRequest {
bytes32 adminSaltVault;
bytes32 proxySaltVault;
bytes32 adminSaltToken;
bytes32 proxySaltToken;
uint256 totalFeeCollectors;
uint256 totalPerformanceFeeCollectors;
uint256 maxDepositAmount;
uint256 maxWithdrawalAmount;
uint256 instantRedemptionFee;
uint256 lagDuration;
uint256 withdrawalFee;
uint256 watermarkTimeWindow;
uint256 maxChangePercent;
uint256 managementFeePercent;
uint256 performanceFeeRate;
bytes tokenInitData;
bytes vaultInitData;
address tokenProxyOwner;
address tokenProxyAdminOwner;
address vaultProxyOwner;
address vaultProxyAdminOwner;
address operatorAddress;
address vaultReferenceAsset;
bool kycRequired;
bool kycPolicyRequired;
// Saved at `submitSpec`, so a later owner change can't alter the policy of a pending deployment
address kycRegistryAddress;
}
struct DeploymentRecord {
address tokenProxy;
address tokenProxyAdmin;
address tokenImplAddress;
address vaultProxy;
address vaultProxyAdmin;
address vaultImplAddress;
address assetsWhitelistAddress;
address sendersWhitelistAddress;
address scheduledCallerAddress;
}
uint256 private _nextId;
/// @notice The address of the LayerZero endpoint
address public lzEndpointAddress;
/// @notice The address of the LP token implementation
address public tokenImplementationAddress;
/// @notice The address of the vault implementation
address public vaultImplementationAddress;
/// @notice The KYC registry set as the transfer policy of every KYC vault's LP token
address public kycRegistryAddress;
/// @notice The address of the whitelists deployer
address public whitelistsDeployerAddress;
/// @notice Indicates if a given address is allowed to run a new deployment
mapping(address => bool) public whitelistedDeployers;
/// @notice Gets the deployment details of the ID specified
mapping(uint256 => DeploymentRecord) public deploymentRecords;
mapping(uint256 => DeploymentRequest) private _deploymentRequests;
mapping(uint256 => mapping(uint256 => address)) private _feeCollectorAddresses;
mapping(uint256 => mapping(uint256 => uint256)) private _feeCollectorPercent;
mapping(uint256 => mapping(uint256 => address)) private _performanceFeeCollectorAddresses;
mapping(uint256 => mapping(uint256 => uint256)) private _performanceFeeCollectorPercent;
event DeploymentRequestAccepted(uint256 indexed deploymentId);
event DeploymentCompleted(uint256 indexed deploymentId);
event LpTokenDeployed(address indexed proxyAddr, address indexed proxyAdminAddr, address indexed implAddr);
event VaultDeployed(address indexed proxyAddr, address indexed proxyAdminAddr, address indexed implAddr);
event WhitelistsDeployerUpdated(address indexed prevAddress, address indexed newAddress);
event KycRegistryUpdated(address indexed prevAddress, address indexed newAddress);
/**
* @notice Constructor
* @param ownerAddr The initial owner of this contract
*/
constructor(address ownerAddr) {
if (ownerAddr == address(0)) revert ZeroAddressError();
_owner = ownerAddr;
whitelistedDeployers[ownerAddr] = true;
}
modifier onlyDeployer() {
if (!whitelistedDeployers[msg.sender]) revert DeployerNotWhitelisted();
_;
}
/**
* @notice Grants permissions to the deployer address specified.
* @param addr The address of the deployer.
*/
function grantDeployer(address addr) external nonReentrant onlyOwner {
if (addr == address(0)) revert ZeroAddressError();
if (whitelistedDeployers[addr]) revert DeployerAlreadyWhitelisted();
whitelistedDeployers[addr] = true;
}
/**
* @notice Revokes permissions from the deployer address specified.
* @param addr The address of the deployer.
*/
function revokeDeployer(address addr) external nonReentrant onlyOwner {
if (!whitelistedDeployers[addr]) revert DeployerNotWhitelisted();
whitelistedDeployers[addr] = false;
}
/**
* @notice Sets the address of the token implementation.
* @param addr The new address.
*/
function setTokenImplementation(address addr) external nonReentrant onlyOwner {
if (addr == address(0)) revert ZeroAddressError();
tokenImplementationAddress = addr;
}
/**
* @notice Sets the address of the vault implementation.
* @param addr The new address.
*/
function setVaultImplementation(address addr) external nonReentrant onlyOwner {
if (addr == address(0)) revert ZeroAddressError();
vaultImplementationAddress = addr;
}
/**
* @notice Sets the KYC registry applied to the LP token of KYC vaults.
* @dev Owner-only so a whitelisted deployer can't choose the policy a KYC vault starts with. The token owner named
* in the spec can still change the policy after deployment.
* Pending deployments keep the registry they were submitted with.
* @param addr The new address.
*/
function setKycRegistry(address addr) external nonReentrant onlyOwner {
if (addr == address(0)) revert ZeroAddressError();
// Rejects an EOA or a contract without `checkTransfer`. `statusOf` returns data, so a contract that only has
// a fallback (e.g. a Safe) fails to decode it and is rejected too.
ITransferPolicy(addr).checkTransfer(address(0), address(0), 0);
IKycRegistry(addr).statusOf(address(0));
emit KycRegistryUpdated(kycRegistryAddress, addr);
kycRegistryAddress = addr;
}
/**
* @notice Sets the LayerZero endpoint for the current chain. The endpoint cannot be updated once it is defined.
* @param lzEndpointAddr The address of the LayerZero endpoint for the current chain.
*/
function setEndpoint(address lzEndpointAddr) external nonReentrant onlyOwner {
if (lzEndpointAddr == address(0)) revert ZeroAddressError();
if (lzEndpointAddress != address(0)) revert LayerZeroEndpointAlreadySet();
lzEndpointAddress = lzEndpointAddr;
}
/**
* @notice Sets the address of the new whitelists deployer.
* @dev This contract becomes the owner of the whitelists deployer specified. The ownership of the previous whitelist is transferred back to the message sender, if applicable.
* @param addr The address of the new whitelists deployer.
*/
function setWhitelistsDeployer(address addr) external nonReentrant onlyOwner {
if (addr == address(0)) revert ZeroAddressError();
if (addr == whitelistsDeployerAddress) revert DeployerAlreadySet();
if (IOwnable2StepsGuarded(addr).pendingOwner() != address(this)) revert OwnershipExpected();
IOwnable2StepsGuarded(addr).acceptOwnership();
if (IOwnable(addr).owner() != address(this)) revert OwnershipAcceptanceFailed();
// This is to prevent old deployer ownership to be silently orphaned on replacement
if (whitelistsDeployerAddress != address(0)) {
IOwnable2StepsGuarded(whitelistsDeployerAddress).transferOwnership(msg.sender);
}
emit WhitelistsDeployerUpdated(whitelistsDeployerAddress, addr);
whitelistsDeployerAddress = addr;
}
/**
* @notice Requests the execution of a brand new deployment.
* @dev Throws if the sender is not a whitelisted deployer.
* @param spec The deployment specification.
* @return uint256 Returns the ID of the newly created deployment request.
*/
function submitSpec(Spec calldata spec) external nonReentrant onlyDeployer returns (uint256) {
// Make sure the LayerZero endpoint was defined for the current chain
if (lzEndpointAddress == address(0)) revert LayerZeroEndpointNotAvailable();
// Make sure the implementations are available
if (tokenImplementationAddress == address(0)) revert TokenImplementationNotSet();
if (vaultImplementationAddress == address(0)) revert VaultImplementationNotSet();
// KYC policy specs need the registry and a token implementation with the policy hook
address registryAddr;
if (spec.kycPolicyRequired) {
registryAddr = kycRegistryAddress;
if (registryAddr == address(0)) revert KycRegistryNotSet();
// Rejects an EOA or a token without the hook (e.g. the bridgeable one)
ITransferPolicyGated(tokenImplementationAddress).transferPolicy();
}
// Check the decimals of the LP token
if ((spec.lpTokenDecimals < 6) || (spec.lpTokenDecimals > 18)) revert InvalidTokenDecimals();
// Compute the deployment hashes.
// The hashes below represent the salt(s) to be used when deploying the transparent proxies of the Vault and LP token.
(bytes32 tokenProxyHash, bytes32 tokenProxyAdminHash, bytes32 vaultProxyHash, bytes32 vaultProxyAdminHash) =
_buildHashes(spec);
// Acquire a new deployment ID
uint256 deploymentId = ++_nextId;
// Save the deployment request, for the sake of transparency.
_deploymentRequests[deploymentId] = DeploymentRequest({
adminSaltVault: vaultProxyAdminHash,
proxySaltVault: vaultProxyHash,
adminSaltToken: tokenProxyAdminHash,
proxySaltToken: tokenProxyHash,
tokenInitData: abi.encodeWithSignature(
"initialize(address,uint8,string,string)",
address(this),
spec.lpTokenDecimals,
spec.lpTokenSymbol,
spec.lpTokenName
),
vaultInitData: abi.encodeWithSignature("initialize(address)", address(this)),
tokenProxyOwner: spec.tokenProxyOwner,
tokenProxyAdminOwner: spec.tokenProxyAdminOwner,
vaultProxyOwner: spec.vaultProxyOwner,
vaultProxyAdminOwner: spec.vaultProxyAdminOwner,
totalFeeCollectors: spec.feeCollectors.length,
totalPerformanceFeeCollectors: spec.performanceFeeCollectors.length,
vaultReferenceAsset: spec.referenceAsset,
kycRequired: spec.kycRequired,
kycPolicyRequired: spec.kycPolicyRequired,
kycRegistryAddress: registryAddr,
operatorAddress: spec.operatorAddress,
maxDepositAmount: spec.maxDepositAmount,
maxWithdrawalAmount: spec.maxWithdrawalAmount,
instantRedemptionFee: spec.instantRedemptionFee,
lagDuration: spec.lagDuration,
withdrawalFee: spec.withdrawalFee,
watermarkTimeWindow: spec.watermarkTimeWindow,
maxChangePercent: spec.maxChangePercent,
managementFeePercent: spec.managementFeePercent,
performanceFeeRate: spec.performanceFeeRate
});
// Transform the fee collectors, due to the technical constraints of the EVM
_transformCollectors(deploymentId, spec);
// Log the respective event
emit DeploymentRequestAccepted(deploymentId);
// Revert if the reference asset is not compliant with the ERC20 standard
if (IERC20Metadata(spec.referenceAsset).decimals() < 6) revert InvalidErc20();
return deploymentId;
}
/**
* @notice Deploys a fresh ecosystem based on the request specified.
* @dev With `kycPolicyRequired`, the LP token gets the registry saved at `submitSpec` as its policy before
* ownership leaves this contract, so no wallet without KYC can get shares. Deposits from KYC'd wallets work at
* once, but redemptions revert until the registry owner exempts the vault (it holds the shares of queued
* redemptions). Exempt the vault before deposits open.
* @param deploymentId The ID of the deployment request.
*/
function deploy(uint256 deploymentId) external nonReentrant onlyDeployer {
// Cannot deploy without an existing Spec
if (_deploymentRequests[deploymentId].vaultProxyOwner == address(0)) revert DeploymentSpecRequired();
// Cannot re-deploy the same ID
if (deploymentRecords[deploymentId].vaultProxy != address(0)) revert DeploymentAlreadyExecuted();
// Make sure the whitelists deployer was set
if (whitelistsDeployerAddress == address(0)) revert WhitelistsDeployerRequired();
// Deploy the LP token
(address tokenAdminContractAddr, address tokenProxyContractAddr) = _deployToken(deploymentId);
// Deploy the vault
(address vaultAdminContractAddr, address vaultProxyContractAddr) = _deployVault(deploymentId);
// Deploy a new instance of the resource-based time-locked calls contract.
address vaultScheduledCallerAddr = address(new ResourceBasedTimelockedCall(vaultProxyContractAddr, 24 hours));
// Delegate the deployment of a new assets whitelist to the predefined deployer.
address assetsWhitelistAddr = IWhitelistsDeployer(whitelistsDeployerAddress)
.deployAssetsWhitelistWithAsset(address(this), _deploymentRequests[deploymentId].vaultReferenceAsset);
// Deploy KYC, if needed
address sendersWhitelistAddr;
if (_deploymentRequests[deploymentId].kycRequired) {
sendersWhitelistAddr = IWhitelistsDeployer(whitelistsDeployerAddress)
.deploySendersWhitelist(_deploymentRequests[deploymentId].vaultProxyOwner);
}
// Track the newly created contract addresses
deploymentRecords[deploymentId] = DeploymentRecord({
tokenProxy: tokenProxyContractAddr,
tokenProxyAdmin: tokenAdminContractAddr,
tokenImplAddress: tokenImplementationAddress,
vaultProxy: vaultProxyContractAddr,
vaultProxyAdmin: vaultAdminContractAddr,
vaultImplAddress: vaultImplementationAddress,
assetsWhitelistAddress: assetsWhitelistAddr,
sendersWhitelistAddress: sendersWhitelistAddr,
scheduledCallerAddress: vaultScheduledCallerAddr
});
// Configure the LP token. The vault is the only actor authorized to mint and burn LP tokens.
address[] memory newMinters = new address[](1);
address[] memory newBurners = new address[](1);
newMinters[0] = vaultProxyContractAddr;
newBurners[0] = vaultProxyContractAddr;
IConfigurableMintableToken(tokenProxyContractAddr).configure(newMinters, newBurners);
// KYC policy specs: gate the LP token with the registry. The token implementation is read here, not at
// `submitSpec`, so check that the policy took effect.
if (_deploymentRequests[deploymentId].kycPolicyRequired) {
address registryAddr = _deploymentRequests[deploymentId].kycRegistryAddress;
ITransferPolicyGated(tokenProxyContractAddr).setTransferPolicy(registryAddr);
if (ITransferPolicyGated(tokenProxyContractAddr).transferPolicy() != registryAddr) {
revert TransferPolicyNotSet();
}
}
// Configure the vault
ITokenizedVault.ConfigInfo memory vaultConfig = ITokenizedVault.ConfigInfo({
maxDepositAmount: _deploymentRequests[deploymentId].maxDepositAmount,
maxWithdrawalAmount: _deploymentRequests[deploymentId].maxWithdrawalAmount,
instantRedemptionFee: _deploymentRequests[deploymentId].instantRedemptionFee,
lagDuration: _deploymentRequests[deploymentId].lagDuration,
withdrawalFee: _deploymentRequests[deploymentId].withdrawalFee,
watermarkTimeWindow: _deploymentRequests[deploymentId].watermarkTimeWindow,
maxChangePercent: _deploymentRequests[deploymentId].maxChangePercent,
managementFeePercent: _deploymentRequests[deploymentId].managementFeePercent,
performanceFeeRate: _deploymentRequests[deploymentId].performanceFeeRate,
operatorAddress: _deploymentRequests[deploymentId].operatorAddress,
referenceAsset: _deploymentRequests[deploymentId].vaultReferenceAsset,
futureOwnerAddress: _deploymentRequests[deploymentId].vaultProxyOwner,
lpTokenAddress: tokenProxyContractAddr,
assetsWhitelistAddress: assetsWhitelistAddr,
sendersWhitelistAddress: sendersWhitelistAddr,
scheduledCallerAddress: vaultScheduledCallerAddr
});
_setFeeCollectors(deploymentId, vaultProxyContractAddr);
_setPerformanceFeeCollectors(deploymentId, vaultProxyContractAddr);
ITokenizedVault(vaultProxyContractAddr).configure(vaultConfig);
// Run the respective ownership transfers
IOwnable(tokenProxyContractAddr).transferOwnership(_deploymentRequests[deploymentId].tokenProxyOwner); // LP Token
IOwnable(assetsWhitelistAddr).transferOwnership(_deploymentRequests[deploymentId].vaultProxyOwner); // Assets whitelist
emit DeploymentCompleted(deploymentId);
}
function _transformCollectors(uint256 deploymentId, Spec calldata spec) private {
// Transform the fee collectors, due to the technical constraints of the EVM
for (uint256 i; i < spec.feeCollectors.length; i++) {
_feeCollectorAddresses[deploymentId][i] = spec.feeCollectors[i].collectorAddress;
_feeCollectorPercent[deploymentId][i] = spec.feeCollectors[i].percentage;
}
for (uint256 i; i < spec.performanceFeeCollectors.length; i++) {
_performanceFeeCollectorAddresses[deploymentId][i] = spec.performanceFeeCollectors[i].collectorAddress;
_performanceFeeCollectorPercent[deploymentId][i] = spec.performanceFeeCollectors[i].percentage;
}
}
/**
* @dev Deploys the LP token
* @param deploymentId The deployment ID
* @return tokenAdminContractAddr The address of the proxy admin
* @return tokenProxyContractAddr The address of the transparent proxy
*/
function _deployToken(uint256 deploymentId)
private
returns (address tokenAdminContractAddr, address tokenProxyContractAddr)
{
// Deploy a fresh LP token
(tokenAdminContractAddr, tokenProxyContractAddr) = _deployTransparentProxy(
_deploymentRequests[deploymentId].adminSaltToken,
_deploymentRequests[deploymentId].proxySaltToken,
tokenImplementationAddress,
_deploymentRequests[deploymentId].tokenProxyAdminOwner,
_deploymentRequests[deploymentId].tokenInitData
);
emit LpTokenDeployed(tokenProxyContractAddr, tokenAdminContractAddr, tokenImplementationAddress);
}
/**
* @dev Deploys the Vault
* @param deploymentId The deployment ID
* @return vaultAdminContractAddr The address of the proxy admin
* @return vaultProxyContractAddr The address of the transparent proxy
*/
function _deployVault(uint256 deploymentId)
private
returns (address vaultAdminContractAddr, address vaultProxyContractAddr)
{
// Deploy a fresh Vault
(vaultAdminContractAddr, vaultProxyContractAddr) = _deployTransparentProxy(
_deploymentRequests[deploymentId].adminSaltVault,
_deploymentRequests[deploymentId].proxySaltVault,
vaultImplementationAddress,
_deploymentRequests[deploymentId].vaultProxyAdminOwner,
_deploymentRequests[deploymentId].vaultInitData
);
emit VaultDeployed(vaultProxyContractAddr, vaultAdminContractAddr, vaultImplementationAddress);
}
function _setPerformanceFeeCollectors(uint256 deploymentId, address vaultAddr) private {
uint256 t = _deploymentRequests[deploymentId].totalPerformanceFeeCollectors;
IFeeCollectorsAware.CollectorDefinition[] memory collectors = new IFeeCollectorsAware.CollectorDefinition[](t);
for (uint256 i; i < t; i++) {
collectors[i] = IFeeCollectorsAware.CollectorDefinition({
collectorAddress: _performanceFeeCollectorAddresses[deploymentId][i],
percentage: _performanceFeeCollectorPercent[deploymentId][i]
});
}
IFeeCollectorsAware(vaultAddr).updatePerformanceFeeCollectors(collectors);
}
function _setFeeCollectors(uint256 deploymentId, address vaultAddr) private {
uint256 t = _deploymentRequests[deploymentId].totalFeeCollectors;
IFeeCollectorsAware.CollectorDefinition[] memory collectors = new IFeeCollectorsAware.CollectorDefinition[](t);
for (uint256 i; i < t; i++) {
collectors[i] = IFeeCollectorsAware.CollectorDefinition({
collectorAddress: _feeCollectorAddresses[deploymentId][i],
percentage: _feeCollectorPercent[deploymentId][i]
});
}
IFeeCollectorsAware(vaultAddr).updateFeeCollectors(collectors);
}
function _deployTransparentProxy(
bytes32 adminSalt,
bytes32 proxySalt,
address implementationAddr,
address proxyOwnerAddr,
bytes memory initData
) private returns (address, address) {
// Get the predictable address of both the proxy and the proxy admin
(address adminContractAddr, address proxyContractAddr) =
_getDeploymentAddress(adminSalt, proxySalt, implementationAddr, initData);
// Make sure the contract addresses above were not taken
if ((adminContractAddr.code.length > 0) || (proxyContractAddr.code.length > 0)) revert AddressAlreadyTaken();
// Deploy the proxy admin
ProxyAdminOwnable2Steps adminInstance = (new ProxyAdminOwnable2Steps){salt: adminSalt}();
if (address(adminInstance) != adminContractAddr) revert ProxyAdminDeploymentFailed();
// Deploy the transparent proxy
TransparentUpgradeableProxy proxy =
(new TransparentUpgradeableProxy){salt: proxySalt}(implementationAddr, address(adminInstance), initData);
if (address(proxy) != proxyContractAddr) revert ProxyDeploymentFailed();
// Transfer ownership of the Proxy Admin
adminInstance.transferOwnership(proxyOwnerAddr);
return (adminContractAddr, proxyContractAddr);
}
/**
* @notice Calculates the deployment address of the proxy specified.
* @param adminSalt The salt of the Proxy Admin
* @param proxySalt The salt of the Transparent Proxy
* @param implementationAddr The implementation address
* @param initData The initialization data
* @return adminContractAddr The address of the proxy admin
* @return proxyContractAddr The address of the transparent proxy
*/
function _getDeploymentAddress(
bytes32 adminSalt,
bytes32 proxySalt,
address implementationAddr,
bytes memory initData
) internal view returns (address adminContractAddr, address proxyContractAddr) {
adminContractAddr = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
bytes1(0xff),
address(this),
adminSalt,
keccak256(type(ProxyAdminOwnable2Steps).creationCode)
)
)
)
)
);
proxyContractAddr = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
bytes1(0xff),
address(this),
proxySalt,
keccak256(
abi.encodePacked(
type(TransparentUpgradeableProxy).creationCode,
abi.encode(implementationAddr, adminContractAddr, initData)
)
)
)
)
)
)
);
}
/**
* @notice Builds the entropy of a given spec.
* @param spec The deployment spec.
* @return tokenProxyHash The hash of the Transparent Proxy of the LP token.
* @return tokenProxyAdminHash The hash of the ProxyAdmin of the LP token.
* @return vaultProxyHash The hash of the Transparent Proxy of the Vault.
* @return vaultProxyAdminHash The hash of the ProxyAdmin of the Vault.
*/
function _buildHashes(Spec calldata spec)
private
pure
returns (
bytes32 tokenProxyHash,
bytes32 tokenProxyAdminHash,
bytes32 vaultProxyHash,
bytes32 vaultProxyAdminHash
)
{
// Build the hash of the keywords
bytes32 keywordsHash = _efficientHash(
_efficientHash(bytes32(bytes(spec.entropyA)), bytes32(bytes(spec.entropyB))),
_efficientHash(bytes32(bytes(spec.entropyC)), bytes32(bytes(spec.entropyD)))
);
// Build the hash of the very basic ERC20
bytes32 tokenHash = _efficientHash(
_efficientHash(bytes32(bytes(spec.lpTokenSymbol)), bytes32(bytes(spec.lpTokenName))),
bytes32(uint256(spec.lpTokenDecimals))
);
// Build the hash for a given vendor, token and organization
bytes32 commonHash = _efficientHash(
_efficientHash(_PLATFORM_VENDOR_PREFIX, bytes32(bytes(spec.orgName))),
_efficientHash(tokenHash, keywordsHash)
);
// Build the hash of the token's Proxy
tokenProxyHash = _efficientHash(_TOKEN_PROXY_PREFIX, commonHash);
// Build the hash of the token's ProxyAdmin
tokenProxyAdminHash = _efficientHash(_TOKEN_PROXYADMIN_PREFIX, tokenProxyHash);
// Build the hash of the vault's Proxy
vaultProxyHash = _efficientHash(_VAULT_PROXY_PREFIX, tokenProxyHash);
// Build the hash of the vault's ProxyAdmin
vaultProxyAdminHash = _efficientHash(_VAULT_PROXYADMIN_PREFIX, vaultProxyHash);
}
/// @dev Computes a hash through the most efficient manner.
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
lib/open-zeppelin/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
lib/open-zeppelin/proxy/ERC1967/ERC1967Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)
pragma solidity ^0.8.0;
import "../Proxy.sol";
import "./ERC1967Upgrade.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy, ERC1967Upgrade {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializing the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) payable {
_upgradeToAndCall(_logic, _data, false);
}
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
return ERC1967Upgrade._getImplementation();
}
}
lib/open-zeppelin/proxy/ERC1967/ERC1967Upgrade.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeacon.sol";
import "../../interfaces/draft-IERC1822.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*/
abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
lib/open-zeppelin/proxy/Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)
pragma solidity ^0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overridden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overridden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}
lib/open-zeppelin/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
lib/open-zeppelin/proxy/transparent/TransparentUpgradeableProxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/transparent/TransparentUpgradeableProxy.sol)
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967Proxy.sol";
/**
* @dev This contract implements a proxy that is upgradeable by an admin.
*
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
* clashing], which can potentially be used in an attack, this contract uses the
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
* things that go hand in hand:
*
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
* that call matches one of the admin functions exposed by the proxy itself.
* 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
* implementation. If the admin tries to call a function on the implementation it will fail with an error that says
* "admin cannot fallback to proxy target".
*
* These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
* the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
* to sudden errors when trying to call a function from the proxy implementation.
*
* Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
* you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
*/
contract TransparentUpgradeableProxy is ERC1967Proxy {
/**
* @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
* optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
*/
constructor(address _logic, address admin_, bytes memory _data) payable ERC1967Proxy(_logic, _data) {
_changeAdmin(admin_);
}
/**
* @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
*/
modifier ifAdmin() {
if (msg.sender == _getAdmin()) {
_;
} else {
_fallback();
}
}
/**
* @dev Returns the current admin.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function admin() external payable ifAdmin returns (address admin_) {
_requireZeroValue();
admin_ = _getAdmin();
}
/**
* @dev Returns the current implementation.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function implementation() external payable ifAdmin returns (address implementation_) {
_requireZeroValue();
implementation_ = _implementation();
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
*/
function changeAdmin(address newAdmin) external payable virtual ifAdmin {
_requireZeroValue();
_changeAdmin(newAdmin);
}
/**
* @dev Upgrade the implementation of the proxy.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
*/
function upgradeTo(address newImplementation) external payable ifAdmin {
_requireZeroValue();
_upgradeToAndCall(newImplementation, bytes(""), false);
}
/**
* @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
* by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
* proxied contract.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeToAndCall(newImplementation, data, true);
}
/**
* @dev Returns the current admin.
*/
function _admin() internal view virtual returns (address) {
return _getAdmin();
}
/**
* @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
*/
function _beforeFallback() internal virtual override {
require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._beforeFallback();
}
/**
* @dev To keep this contract fully transparent, all `ifAdmin` functions must be payable. This helper is here to
* emulate some proxy functions being non-payable while still allowing value to pass through.
*/
function _requireZeroValue() private {
require(msg.value == 0);
}
}
lib/open-zeppelin/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` 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 amount) external returns (bool);
}
lib/open-zeppelin/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
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/open-zeppelin/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
lib/open-zeppelin/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.0;
/**
* @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 ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
* _Available since v4.9 for `string`, `bytes`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 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) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
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) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
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) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
src/core/BaseReentrancy.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
abstract contract BaseReentrancy {
// ----------------------------------------------------------------------------------------------------
// Constants
// ----------------------------------------------------------------------------------------------------
// 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;
// ----------------------------------------------------------------------------------------------------
// Errors
// ----------------------------------------------------------------------------------------------------
error ReentrantCall();
// ----------------------------------------------------------------------------------------------------
// Storage layout
// ----------------------------------------------------------------------------------------------------
uint256 private _status;
// ----------------------------------------------------------------------------------------------------
// Modifiers
// ----------------------------------------------------------------------------------------------------
/**
* @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() {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == _ENTERED) {
revert ReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
src/core/Ownable2StepsGuarded.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import {OwnableGuarded} from "./OwnableGuarded.sol";
abstract contract Ownable2StepsGuarded is OwnableGuarded {
error InvalidAddress();
error Unauthorized();
/// @dev The address of the pending owner, if any.
address internal _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @notice Starts the ownership transfer of this contract to the address specified.
* @dev The ownership transfer is time-locked. Calling this function cancels any previous scheduled requests.
* @param newOwner The address of the new owner.
*/
function transferOwnership(address newOwner) public virtual override nonReentrant onlyOwner {
_proposeOwnershipTransfer(newOwner);
}
/**
* @notice Accepts the ownership transfer initiated by the current owner of this contract.
*/
function acceptOwnership() public virtual nonReentrant {
if (_pendingOwner != msg.sender) revert Unauthorized();
_transferOwnership(msg.sender);
}
function _proposeOwnershipTransfer(address newOwner) internal {
if ((newOwner == address(0)) || (newOwner == address(this))) revert InvalidAddress();
_pendingOwner = newOwner;
emit OwnershipTransferStarted(_owner, newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @notice Gets the address of the pending owner, if any.
* @return Returns the address of the pending owner. Returns the zero address if there is no pending owner at all.
*/
function pendingOwner() external view returns (address) {
return _pendingOwner;
}
}
src/core/OwnableGuarded.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
abstract contract OwnableGuarded {
// ----------------------------------------------------------------------------------------------------
// Constants
// ----------------------------------------------------------------------------------------------------
// 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;
// ----------------------------------------------------------------------------------------------------
// Errors
// ----------------------------------------------------------------------------------------------------
error OwnerOnly();
error OwnerAddressRequired();
error ReentrancyGuardReentrantCall();
// ----------------------------------------------------------------------------------------------------
// Storage layout
// ----------------------------------------------------------------------------------------------------
uint256 private _status;
address internal _owner;
// ----------------------------------------------------------------------------------------------------
// Events
// ----------------------------------------------------------------------------------------------------
/**
* @notice Triggers when contract ownership changes.
* @param previousOwner The previous owner of the contract.
* @param newOwner The new owner of the contract.
*/
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// ----------------------------------------------------------------------------------------------------
// Modifiers
// ----------------------------------------------------------------------------------------------------
/**
* @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() {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
_;
// By storing the original value once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
if (msg.sender != _owner) revert OwnerOnly();
_;
}
// ----------------------------------------------------------------------------------------------------
// Functions
// ----------------------------------------------------------------------------------------------------
/**
* @notice Transfers ownership of the contract to the account specified.
* @param newOwner The address of the new owner.
*/
function transferOwnership(address newOwner) external virtual nonReentrant onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal virtual {
if (newOwner == address(0)) revert OwnerAddressRequired();
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @notice Gets the owner of the contract.
* @return address The address who owns the contract.
*/
function owner() external view virtual returns (address) {
return _owner;
}
}
src/core/ProxyAdminOwnable2Steps.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import {TransparentUpgradeableProxy} from "../../lib/open-zeppelin/proxy/transparent/TransparentUpgradeableProxy.sol";
import {Ownable2StepsGuarded} from "./Ownable2StepsGuarded.sol";
contract ProxyAdminOwnable2Steps is Ownable2StepsGuarded {
error FunctionNotAvailable();
constructor() {
_owner = msg.sender;
}
/**
* @dev Returns the current implementation of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyImplementation(TransparentUpgradeableProxy proxy) public view returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
if (!success) revert FunctionNotAvailable();
return abi.decode(returndata, (address));
}
/**
* @dev Returns the current admin of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyAdmin(TransparentUpgradeableProxy proxy) public view returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("admin()")) == 0xf851a440
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
if (!success) revert FunctionNotAvailable();
return abi.decode(returndata, (address));
}
/**
* @dev Changes the admin of `proxy` to `newAdmin`.
*
* Requirements:
*
* - This contract must be the current admin of `proxy`.
*/
function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) external nonReentrant onlyOwner {
proxy.changeAdmin(newAdmin);
}
/**
* @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgrade(TransparentUpgradeableProxy proxy, address implementation) external nonReentrant onlyOwner {
proxy.upgradeTo(implementation);
}
/**
* @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
* {TransparentUpgradeableProxy-upgradeToAndCall}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data)
external
payable
nonReentrant
onlyOwner
{
proxy.upgradeToAndCall{value: msg.value}(implementation, data);
}
}
src/core/ResourceBasedTimelockedCall.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import {IResourceBasedTimelockedCall} from "./interfaces/IResourceBasedTimelockedCall.sol";
import {IOperableResource} from "./interfaces/IOperableResource.sol";
import {BaseReentrancy} from "./BaseReentrancy.sol";
/**
* @title Allows a resource to schedule and consume time-locked hashes.
*/
contract ResourceBasedTimelockedCall is IResourceBasedTimelockedCall, BaseReentrancy {
/// @dev A reasonable time-window for manipulating the block timestamp as a miner.
uint256 internal constant _TIMESTAMP_MANIPULATION_WINDOW = 5 minutes;
/// @notice The address of the operable smart contract.
IOperableResource public immutable RESOURCE;
/// @notice The time-lock duration of the consumer.
uint256 public immutable TIMELOCK_DURATION;
/// @notice The time-lock info of a given hash.
mapping(bytes32 => TimelockedCallInfo) public queue;
/// @dev Throws if the sender is not the expected resource address.
modifier onlyResource() {
if (msg.sender != address(RESOURCE)) revert Unauthorized();
_;
}
constructor(address newResource, uint256 newTimeLockDuration) {
if (newTimeLockDuration < _TIMESTAMP_MANIPULATION_WINDOW) revert InvalidTimelockDuration();
RESOURCE = IOperableResource(newResource);
TIMELOCK_DURATION = newTimeLockDuration;
}
/**
* @notice Schedules a hash for further execution.
* @dev Throws if the sender is not the expected resource, nor the owner/operator of such resource.
* @param h Specifies the hash to schedule.
*/
function schedule(bytes32 h) external override nonReentrant {
if (h == bytes32(0)) revert HashRequired();
if (queue[h].createdBy != address(0)) revert HashAlreadyEnqueued();
queue[h] = TimelockedCallInfo({createdBy: msg.sender, targetEpoch: block.timestamp + TIMELOCK_DURATION});
emit HashScheduled(h, msg.sender);
// Validate the message sender
_enforceValidSender();
}
/**
* @notice Cancels an existing hash.
* @param h Specifies the hash to cancel.
*/
function cancel(bytes32 h) external nonReentrant {
if (queue[h].createdBy == address(0)) revert HashNotEnqueued();
delete queue[h];
emit HashCancelled(h, msg.sender);
// Validate the message sender
_enforceValidSender();
}
/**
* @notice Consumes the hash specified.
* @dev Throws if the sender is not the expected resource.
* @param h Specifies the hash to consume.
*/
function consume(bytes32 h) external override nonReentrant onlyResource {
if (queue[h].targetEpoch < 1) revert HashNotEnqueued();
if (block.timestamp < queue[h].targetEpoch) revert TimelockInPlace();
delete queue[h];
emit HashConsumed(h, msg.sender);
}
/**
* @notice Indicates if the hash specified was enqueued.
* @param h Specifies the hash to evaluate.
* @return bool Returns true if the hash specified was enqueued.
*/
function hashExists(bytes32 h) external view override returns (bool) {
return queue[h].targetEpoch > 0;
}
/**
* @notice Gets the details of the hash specified.
* @param h Specifies the hash to evaluate.
* @return TimelockedCallInfo Returns a struct containing the details.
*/
function getInfo(bytes32 h) external view override returns (TimelockedCallInfo memory) {
return queue[h];
}
/// @dev Throws if the sender is not the expected resource, nor the owner/operator of such resource.
function _enforceValidSender() private view {
address theOwner = RESOURCE.owner();
address theOperator = RESOURCE.operatorAddress();
if ((msg.sender != address(RESOURCE)) && (msg.sender != theOwner) && (msg.sender != theOperator)) {
revert Unauthorized();
}
}
}
src/core/interfaces/IConfigurableMintableToken.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
interface IConfigurableMintableToken {
function configure(address[] calldata newMinters, address[] calldata newBurners) external;
}
src/core/interfaces/IFeeCollectorsAware.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
interface IFeeCollectorsAware {
struct CollectorDefinition {
address collectorAddress;
uint256 percentage;
}
function updateFeeCollectors(CollectorDefinition[] calldata collectors) external;
function updatePerformanceFeeCollectors(CollectorDefinition[] calldata collectors) external;
}
src/core/interfaces/IKycRegistry.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
/// @title On-chain KYC records, one registry per chain.
interface IKycRegistry {
/// @notice A wallet's KYC record.
struct Record {
/// @dev Sticky; only the owner clears it.
bool blocked;
/// @dev Zero if never approved.
uint256 verifiedAt;
/// @dev Active strictly before this.
uint256 expiresAt;
/// @dev Records verified at or before this read Expired.
uint256 revokedAt;
}
/// @notice Active may enter and exit; Expired may only exit.
enum Status {
None,
Active,
Expired,
Blocked
}
/**
* @notice Writes a wallet's record. Writer only.
* @param wallet The wallet.
* @param verifiedAt When KYC was verified.
* @param expiresAt When the record expires.
*/
function approve(address wallet, uint256 verifiedAt, uint256 expiresAt) external;
/**
* @notice Expires a wallet's record now. The wallet itself, a writer or the owner.
* @param wallet The wallet.
*/
function revoke(address wallet) external;
/**
* @notice Blocks (writer or owner) or unblocks (owner only) a wallet.
* @param wallet The wallet.
* @param blocked Whether to block.
* @param reason Opaque reason code.
*/
function setBlocked(address wallet, bool blocked, bytes32 reason) external;
/**
* @notice Gets a wallet's raw record.
* @param wallet The wallet.
* @return The record.
*/
function getRecord(address wallet) external view returns (Record memory);
/**
* @notice Gets a wallet's status.
* @param wallet The wallet.
* @return The status.
*/
function statusOf(address wallet) external view returns (Status);
}
src/core/interfaces/IOperableResource.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
interface IOperableResource {
function owner() external view returns (address);
function operatorAddress() external view returns (address);
}
src/core/interfaces/IOwnable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
interface IOwnable {
function transferOwnership(address newOwnerAddr) external;
function owner() external view returns (address);
}
src/core/interfaces/IOwnable2StepsGuarded.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
interface IOwnable2StepsGuarded {
function transferOwnership(address newOwner) external;
function acceptOwnership() external;
function pendingOwner() external view returns (address);
}
src/core/interfaces/IResourceBasedTimelockedCall.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
interface IResourceBasedTimelockedCall {
error Unauthorized();
error HashRequired();
error HashAlreadyEnqueued();
error HashNotEnqueued();
error TimelockInPlace();
error InvalidTimelockDuration();
error InvalidResourceAddress();
struct TimelockedCallInfo {
uint256 targetEpoch; // The unix epoch at which the hash can be consumed
address createdBy; // The address of the scheduler
}
/// @notice Triggers when a hash is scheduled for further execution
event HashScheduled(bytes32 h, address postedBy);
/// @notice Triggers when a hash is consumed by the address specified.
event HashConsumed(bytes32 h, address consumerAddress);
/// @notice Triggers when a hash is cancelled.
event HashCancelled(bytes32 h, address consumerAddress);
function schedule(bytes32 h) external;
function cancel(bytes32 h) external;
function consume(bytes32 h) external;
function hashExists(bytes32 h) external view returns (bool);
function getInfo(bytes32 h) external view returns (TimelockedCallInfo memory);
}
src/core/interfaces/ITransferPolicy.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
/// @title Gates receipt token transfers.
interface ITransferPolicy {
/**
* @notice Reverts if the transfer isn't allowed. It skips a zero side, so `checkTransfer(0, a, 0)` checks only `a`.
* @dev `amount` lets a policy cap transfer sizes.
* @param from The sender, or zero for a mint.
* @param to The recipient, or zero for a burn.
* @param amount The number of tokens moved.
*/
function checkTransfer(address from, address to, uint256 amount) external view;
}
/// @title A receipt token gated by an `ITransferPolicy`.
interface ITransferPolicyGated {
/**
* @notice The policy gating transfers.
* @return The policy; zero when transfers are ungated.
*/
function transferPolicy() external view returns (address);
/**
* @notice Sets the policy; zero ungates transfers.
* @param policyAddr The policy.
*/
function setTransferPolicy(address policyAddr) external;
}
src/tokenized-vaults/ITokenizedVault.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
interface ITokenizedVault {
error HighWatermarkViolation();
error HighWatermarkDurationError();
error TokenDecimalsMismatch();
error InvalidLagDuration();
struct ConfigInfo {
uint256 maxDepositAmount;
uint256 maxWithdrawalAmount;
uint256 instantRedemptionFee;
uint256 lagDuration;
uint256 withdrawalFee;
uint256 watermarkTimeWindow;
uint256 maxChangePercent;
uint256 managementFeePercent;
uint256 performanceFeeRate;
address sendersWhitelistAddress;
address operatorAddress;
address scheduledCallerAddress;
address lpTokenAddress;
address referenceAsset;
address futureOwnerAddress;
address assetsWhitelistAddress;
}
/// @notice Triggers when the resource is configured.
event ContractConfigured();
/// @notice Triggers during an emergency withdrawal.
event OnEmergencyWithdraw(address receiverAddr);
function configure(ConfigInfo calldata newConfig) external;
function asset() external view returns (address);
}
src/tokenized-vaults/IWhitelistsDeployer.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
/**
* @title Defines the interface of a whitelists deployer.
* @notice Defines the interface of a whitelists deployer.
* @author August
*/
interface IWhitelistsDeployer {
/**
* @notice Triggers when a new assets whitelist is deployed
* @param assetsWhitelistAddr The address of the newly created whitelist
* @param deployedBy The address who deployed the whitelist
*/
event AssetsWhitelistDeployed(address indexed assetsWhitelistAddr, address indexed deployedBy);
/**
* @notice Triggers when a new senders whitelist is deployed
* @param sendersWhitelistAddr The address of the newly created whitelist
* @param deployedBy The address who deployed the whitelist
*/
event SendersWhitelistDeployed(address indexed sendersWhitelistAddr, address indexed deployedBy);
/**
* @notice Deploys a new Assets Whitelist
* @param ownerAddr The owner of the whitelist
* @param vaultAddr The vault address
* @return address The address of the newly deployed contract
*/
function deployAssetsWhitelist(address ownerAddr, address vaultAddr) external returns (address);
/**
* @notice Deploys a new Assets Whitelist for the reference asset specified
* @param ownerAddr The owner of the whitelist
* @param vaultReferenceAsset The reference asset of the vault
* @return address The address of the newly deployed contract
*/
function deployAssetsWhitelistWithAsset(address ownerAddr, address vaultReferenceAsset) external returns (address);
/**
* @notice Deploys a new Senders Whitelist
* @param ownerAddr The owner of the whitelist
* @return address The address of the newly deployed contract
*/
function deploySendersWhitelist(address ownerAddr) external returns (address);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"@layerzerolabs/=lib/layer-zero/",
"@openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"@oz/=lib/open-zeppelin/",
"node_modules/@chainlink/contracts-ccip/:@eth-optimism/contracts/=node_modules/@chainlink/contracts-ccip/node_modules/@eth-optimism/contracts/",
"node_modules/@chainlink/contracts-ccip/:@openzeppelin/contracts/=node_modules/@chainlink/contracts-ccip/node_modules/@openzeppelin/contracts/",
"@axelar-network/=node_modules/@axelar-network/",
"@chainlink/=node_modules/@chainlink/",
"@eth-optimism/=node_modules/@eth-optimism/",
"@openzeppelin/=node_modules/@openzeppelin/",
"hardhat-deploy/=node_modules/hardhat-deploy/",
"layer-zero/=lib/layer-zero/",
"layer-zerov2/=lib/layer-zerov2/",
"murky/=lib/murky/",
"open-zeppelin/=lib/open-zeppelin/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"solidity-bytes-utils/=node_modules/solidity-bytes-utils/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.