Verified contractPartialAGPL-3.0-only
BittyV1Vault
Address0x5e8a47f11873ed6e53d50bbb2ad7d705099a97a4
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.34
- Same code
Only this contract
Details
- Compiler
- solc 0.8.34+commit.80d5c536
- Language
- solidity
- Optimization
- Yes, 10,000 runs
- EVM version
- prague
- Via IR
- yes
- License
- AGPL-3.0-only
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,490,462
- Creation transaction
- 0x924af991a8…f953f4a248
- Libraries
- src/BittyV1Vault.sol:DeFiLogic0xe5f7…560634src/BittyV1Vault.sol:RiskLogic0x07ad…e4a5c9src/BittyV1Vault.sol:WhitelistLogic0x6031…445c76src/BittyV1Vault.sol:TokenAsGasLogic0xc9f9…09dad2
50 files
- src/BittyV1Vault.solmain13.45 KB
- lib/guard-contracts/src/interfaces/IBittyV1Guard.sol15.49 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol4.03 KB
- lib/openzeppelin-contracts-upgradeable/contracts/metatx/ERC2771ContextUpgradeable.sol3.62 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol8.91 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol6.59 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.19 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/MulticallUpgradeable.sol1.99 KB
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol880 B
- lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol1.72 KB
- lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol6.72 KB
- lib/openzeppelin-contracts/contracts/proxy/Proxy.sol2.67 KB
- lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol472 B
- lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol6.33 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol3.8 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol5.77 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol4.93 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.26 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol3.93 KB
- lib/openzeppelin-contracts/contracts/utils/Strings.sol3.1 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol869 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol15.12 KB
- lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol1.26 KB
- lib/protocol-contracts/src/interfaces/IBittyV1IntentProtocol.sol3.37 KB
- lib/protocol-contracts/src/interfaces/IBittyV1MarketTradeProtocol.sol1.36 KB
- lib/protocol-contracts/src/interfaces/IBittyV1Protocol.sol3.96 KB
- lib/protocol-contracts/src/interfaces/IBittyV1Yield.sol3.74 KB
- lib/solmate/src/tokens/ERC20.sol6.81 KB
- lib/solmate/src/tokens/WETH.sol1.03 KB
- lib/solmate/src/utils/SafeTransferLib.sol5.77 KB
- src/BittyV1AccountBase.sol6.37 KB
- src/BittyV1VaultBase.sol3.74 KB
- src/interfaces/IBittyV1DeFi.sol15.48 KB
- src/interfaces/IBittyV1Forwarder.sol1.65 KB
- src/interfaces/IBittyV1Owner.sol8.69 KB
- src/interfaces/IBittyV1Vault.sol15.83 KB
- src/logic/BittyStorage.sol7.86 KB
- src/logic/Constants.sol2.57 KB
- src/logic/DeFiLogic.sol24 KB
- src/logic/LockLib.sol8.03 KB
- src/logic/MarketTradeLogic.sol13.17 KB
- src/logic/PaymentCore.sol3.26 KB
- src/logic/PaymentLogic.sol6.84 KB
- src/logic/PriceLib.sol4.36 KB
- src/logic/RiskLogic.sol11.57 KB
- src/logic/TimelockLib.sol2.18 KB
- src/logic/TokenAsGasLogic.sol7.93 KB
- src/logic/WhitelistLogic.sol17.52 KB
src/BittyV1Vault.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {BittyV1VaultBase} from "./BittyV1VaultBase.sol";
import {IERC20} from "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import {DeFiLogic} from "./logic/DeFiLogic.sol";
import {MarketTradeLogic} from "./logic/MarketTradeLogic.sol";
import {PaymentLogic} from "./logic/PaymentLogic.sol";
import {WhitelistLogic} from "./logic/WhitelistLogic.sol";
import {TokenAsGasLogic} from "./logic/TokenAsGasLogic.sol";
import {RiskLogic} from "./logic/RiskLogic.sol";
import {LockLib} from "./logic/LockLib.sol";
import {BittyStorage, VaultStorage} from "./logic/BittyStorage.sol";
import {WETH} from "solmate/tokens/WETH.sol";
import {IERC721} from "openzeppelin-contracts/contracts/token/ERC721/IERC721.sol";
import {IBittyV1Owner} from "./interfaces/IBittyV1Owner.sol";
import {IBittyV1Forwarder} from "./interfaces/IBittyV1Forwarder.sol";
import {
IBittyV1Vault,
AddressZero,
ArrayLengthMismatch,
NotTrustedForwarder,
InvalidRelayedCalldata,
VaultLocked,
NoPendingOwnershipTransfer,
OwnershipNotRenounceable,
PendingChanges,
WhitelistEntryView
} from "./interfaces/IBittyV1Vault.sol";
/**
* @title BittyV1Vault
* @notice The main vault: owner payments + the owner's own DeFi (reached through fallback → shared
* {BittyV1VaultDeFiFacet}) + owner-driven UUPS upgrades to guard-registered, newer
* implementations (from {BittyV1VaultBase}): instant, and refused while the vault is locked. Payouts to arbitrary external addresses live only here and are
* owner-gated.
*/
contract BittyV1Vault is BittyV1VaultBase {
address public immutable DEFI_FACET;
constructor(address defiFacet) {
DEFI_FACET = defiFacet;
_disableInitializers();
}
function initialize(
address owner_,
address gasWrapped_,
bool restrictToOwnAllowList,
address activationAsset,
uint256 activationAmount,
bytes[] calldata calls
) external initializer {
if (owner_ == address(0) || gasWrapped_ == address(0)) revert AddressZero();
__Ownable_init(owner_);
PaymentLogic.initialize(gasWrapped_, restrictToOwnAllowList);
uint256 bal = address(this).balance;
if (bal > 0) WETH(payable(gasWrapped_)).deposit{value: bal}();
if (activationAsset != address(0) && activationAmount != 0) {
TokenAsGasLogic.payActivationFee(activationAsset, activationAmount);
}
if (restrictToOwnAllowList) {
if (activationAsset != address(0)) {
DeFiLogic.listInitialAsset(activationAsset);
}
DeFiLogic.listInitialAsset(gasWrapped_);
}
if (calls.length != 0) _runAsOwner(owner_, calls);
}
modifier notLocked() {
LockLib.requireNotLocked();
_;
}
function lockLevel() external view returns (uint8) {
return LockLib.level();
}
function emergencyLock() external onlyOwner {
_settleOwnership();
LockLib.emergencyLock();
}
function unlock() external onlyOwner {
LockLib.unlock();
}
function foreverLock(uint256 escapeRecipientId) external onlyOwner {
_settleOwnership();
WhitelistLogic.requireEscape(escapeRecipientId);
LockLib.foreverLock();
}
function _gasWrapped() private view returns (address) {
return BittyStorage.vault().gasWrapped;
}
function _payoutAsset(address asset) private view returns (address) {
return asset == address(0) ? _gasWrapped() : asset;
}
function transferOwnership(address newOwner) public override onlyOwner notLocked {
if (newOwner == address(0)) revert OwnershipNotRenounceable();
_settleOwnership();
VaultStorage storage $ = BittyStorage.vault();
uint64 timelock = RiskLogic.riskTimelock();
uint64 readyAt = uint64(block.timestamp) + timelock;
$.ownershipReadyAt = uint40(readyAt);
$.pendingOwner = newOwner;
emit IBittyV1Owner.OwnershipTransferQueued(newOwner, readyAt);
}
function cancelOwnershipTransfer() external onlyOwner {
_settleOwnership();
VaultStorage storage $ = BittyStorage.vault();
if ($.ownershipReadyAt == 0) revert NoPendingOwnershipTransfer();
address cancelled = $.pendingOwner;
$.ownershipReadyAt = 0;
$.pendingOwner = address(0);
emit IBittyV1Owner.OwnershipTransferCancelled(cancelled);
}
function settleOwnershipTransfer() external {
_settleOwnership();
}
function _settleOwnership() private {
VaultStorage storage $ = BittyStorage.vault();
uint256 readyAt = $.ownershipReadyAt;
if (readyAt == 0 || block.timestamp < readyAt) return;
address next = $.pendingOwner;
$.ownershipReadyAt = 0; // same slot as `vaultOwner`, so the handover is one warm write
$.pendingOwner = address(0);
_transferOwnership(next);
}
function _pendingOwnershipTransfer() private view returns (address target, uint64 readyAt) {
VaultStorage storage $ = BittyStorage.vault();
readyAt = $.ownershipReadyAt;
if (readyAt == 0 || block.timestamp >= readyAt) return (address(0), 0);
return ($.pendingOwner, readyAt);
}
receive() external payable {
address gasWrapped = _gasWrapped();
if (msg.value > 0 && msg.sender != gasWrapped) {
WETH(payable(gasWrapped)).deposit{value: msg.value}();
}
}
function wrapNative() external {
MarketTradeLogic.requireNotTrading(); // a sale for WETH would count the wrapped ETH as bought
address gasWrapped = _gasWrapped();
uint256 bal = address(this).balance;
if (bal > 0 && gasWrapped != address(0)) WETH(payable(gasWrapped)).deposit{value: bal}();
}
fallback() external payable {
if (msg.data.length < 24 && msg.sender == trustedForwarder()) revert InvalidRelayedCalldata();
address facet = DEFI_FACET;
assembly {
calldatacopy(0, 0, calldatasize())
let ok := delegatecall(gas(), facet, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch ok
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
function batchSend(
address recipient,
address[] calldata assets,
uint256[] calldata amounts,
address[][] calldata withdrawProtocols,
uint256[][] calldata withdrawAmounts
) external onlyOwner notLocked {
_pullFromPositions(assets, withdrawProtocols, withdrawAmounts);
PaymentLogic.batchSend(recipient, assets, amounts);
}
function send(
address recipient,
address asset,
uint256 amount,
address[] calldata withdrawProtocols,
uint256[] calldata withdrawAmounts
) external onlyOwner notLocked {
_pullOneFromPositions(asset, withdrawProtocols, withdrawAmounts);
PaymentLogic.send(recipient, asset, amount);
}
function addWhitelistedRecipient(address recipient) external onlyOwner notLocked returns (uint256) {
return WhitelistLogic.addWhitelistedRecipientOne(recipient);
}
function sendAndAddWhitelistedRecipient(
address recipient,
address asset,
uint256 amount,
address[] calldata withdrawProtocols,
uint256[] calldata withdrawAmounts
) external onlyOwner notLocked returns (uint256) {
_pullOneFromPositions(asset, withdrawProtocols, withdrawAmounts);
PaymentLogic.send(recipient, asset, amount);
return WhitelistLogic.addWhitelistedRecipientOne(recipient);
}
function batchSendAndAddWhitelistedRecipient(
address recipient,
address[] calldata assets,
uint256[] calldata amounts,
address[][] calldata withdrawProtocols,
uint256[][] calldata withdrawAmounts
) external onlyOwner notLocked returns (uint256) {
_pullFromPositions(assets, withdrawProtocols, withdrawAmounts);
PaymentLogic.batchSend(recipient, assets, amounts);
return WhitelistLogic.addWhitelistedRecipientOne(recipient);
}
function removeWhitelistedRecipients(uint256[] calldata ids) external onlyOwner notLocked {
WhitelistLogic.removeWhitelistedRecipients(ids);
}
function sendToWhitelistedRecipient(
uint256 id,
address asset,
uint256 amount,
address[] calldata withdrawProtocols,
uint256[] calldata withdrawAmounts
) external onlyOwner {
_pullOneFromPositions(asset, withdrawProtocols, withdrawAmounts);
WhitelistLogic.sendToWhitelistedRecipientOne(id, asset, amount);
}
function updateRisk(IBittyV1Owner.RiskSettings calldata settings) external onlyOwner {
RiskLogic.updateRisk(settings);
}
function setTokenAsGas(address[] calldata assets, uint64 dailyLimit) external onlyOwner notLocked {
TokenAsGasLogic.setTokenAsGas(assets, dailyLimit);
}
function disableTokenAsGas() external onlyOwner notLocked {
TokenAsGasLogic.disableTokenAsGas();
}
function payRelayerFee(address asset, uint256 amount) external {
if (msg.sender != trustedForwarder() || IBittyV1Forwarder(msg.sender).chargingVault() != address(this)) {
revert NotTrustedForwarder();
}
if (LockLib.lockedForever()) revert VaultLocked();
TokenAsGasLogic.payRelayerFee(asset, amount);
}
/**
* An NFT cannot be valued, so it cannot be metered like a regular send: it leaves only to a
* whitelisted recipient the owner can pay right now, the same way out as any asset beyond the
* send allowance. Allowed under either lock for the same reason payouts to such a recipient are.
*/
function retrieve721(address contractAddress, uint256 tokenId, uint256 recipientId) external onlyOwner {
address to = WhitelistLogic.payableRecipient(recipientId);
IERC721(contractAddress).safeTransferFrom(address(this), to, tokenId);
emit IBittyV1Owner.Retrieved721(contractAddress, tokenId, to);
}
function _pullFromPositions(
address[] calldata assets,
address[][] calldata withdrawProtocols,
uint256[][] calldata withdrawAmounts
) private {
if (withdrawProtocols.length == 0 && withdrawAmounts.length == 0) {
return;
}
uint256 n = assets.length;
if (withdrawProtocols.length != n || withdrawAmounts.length != n) revert ArrayLengthMismatch();
for (uint256 i = 0; i < n; i++) {
_pullOneFromPositions(assets[i], withdrawProtocols[i], withdrawAmounts[i]);
}
}
function _pullOneFromPositions(
address asset,
address[] calldata withdrawProtocols,
uint256[] calldata withdrawAmounts
) private {
if (withdrawProtocols.length != withdrawAmounts.length) {
revert ArrayLengthMismatch();
}
if (withdrawProtocols.length != 0) MarketTradeLogic.requireNotTrading();
address payoutAsset = _payoutAsset(asset);
for (uint256 i = 0; i < withdrawProtocols.length; i++) {
if (withdrawProtocols[i] != address(0) && withdrawAmounts[i] > 0) {
DeFiLogic.withdraw(withdrawProtocols[i], payoutAsset, withdrawAmounts[i], address(this));
}
}
}
function pendingChanges() external view returns (PendingChanges memory p) {
p = RiskLogic.pendingChanges();
(p.newOwner, p.newOwnerReadyAt) = _pendingOwnershipTransfer();
(p.newAssetManager, p.newAssetManagerAt, p.newAssetManagerPerms) = DeFiLogic._pendingAssetManagerGrant();
}
function riskSettings()
external
view
returns (uint64 timelock, uint64 sendDailyAllowance, uint64 dailyLossAllowance)
{
return RiskLogic.riskSettings();
}
function getWhitelistedRecipients(uint256[] calldata ids) external view returns (address[] memory recipients) {
return WhitelistLogic.getWhitelistedRecipients(ids);
}
function getWhitelistedRecipientRemovals(uint256[] calldata ids) external view returns (uint64[] memory) {
return WhitelistLogic.getWhitelistedRecipientRemovals(ids);
}
function getWhitelist(uint256 fromId, uint256 count)
external
view
returns (uint256 lastId, WhitelistEntryView[] memory entries)
{
return WhitelistLogic.getWhitelist(fromId, count);
}
function tokenAsGasConfig() external view returns (address[] memory assets, uint256 dailyLimit) {
return (TokenAsGasLogic.getTokenAsGasAssets(), TokenAsGasLogic.gasBudgetDailyLimit());
}
function gasBudgetRemaining() external view returns (uint256) {
if (LockLib.lockedForever()) return 0;
return TokenAsGasLogic.gasBudgetRemaining();
}
function relayerFeeValue(address asset, uint256 amount) external view returns (uint256) {
return TokenAsGasLogic.relayerFeeValue(asset, amount);
}
function isStableCoinAllowed(address asset) external view returns (bool) {
return DeFiLogic.stableCoinAllowed(asset);
}
function gasWrappedAddress() external view returns (address) {
return _gasWrapped();
}
}
lib/guard-contracts/src/interfaces/IBittyV1Guard.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
error NotDeployer();
error LengthMismatch();
error NotRegisteredProtocol(address protocolAddress);
error NotRegisteredImplementation(address implementation);
error CategoryZero();
error AddressZero();
error InvalidPriceFeed(address asset);
uint8 constant ASSET_STABLE_COIN = 1;
uint8 constant ASSET_CRYPTO = 2;
uint8 constant ASSET_AMM_LIQUID = 4;
uint8 constant PROTOCOL_STAKING = 1;
uint8 constant PROTOCOL_LENDING = 2;
uint8 constant PROTOCOL_MARKET_TRADE = 3;
uint8 constant PROTOCOL_INTENT = 4;
uint8 constant IMPLEMENTATION_VAULT = 1;
bytes32 constant CFG_OWNER = keccak256("bitty.owner");
bytes32 constant CFG_GAS_WRAPPED = keccak256("bitty.gasWrapped");
/**
* @dev An asset's Chainlink price feed. `decimals` is the feed's and `assetDecimals` the asset's own,
* both read when the feed is set so a reader never has to ask for either again; `assetDecimals`
* is 0 when the asset answers no `decimals()` — a placeholder such as BTC behind WBTC / BTC, which
* is only ever a quote. A feed quoted in another asset rather than in USD (LDO / ETH) names that
* asset as `quote`, whose own feed prices the hop to USD; everything but `quote` shares the first
* slot, so a USD feed's reader never touches the second.
*/
struct PriceFeed {
address feed;
uint32 maxAge;
uint8 decimals;
uint8 assetDecimals;
bool hasQuote;
address quote;
}
/**
* @dev Everything one market trade reads from the guard, in one call. See {IBittyV1Guard-marketTradeInfo}.
*/
struct MarketTradeInfo {
uint8 protocolCategory;
bool protocolDeprecated;
uint8 sellCategory;
uint8 buyCategory;
PriceFeed sellFeed;
PriceFeed sellQuoteFeed;
PriceFeed buyFeed;
PriceFeed buyQuoteFeed;
address sequencerUptimeFeed;
}
interface IBittyV1Guard {
event AssetAdded(address indexed assetAddress, uint8 indexed category);
event AssetRemoved(address indexed assetAddress);
event ProtocolAdded(address indexed protocolAddress, uint8 indexed category);
event ProtocolDeprecated(address indexed protocolAddress);
event ImplementationRegistered(address indexed implementation);
event ImplementationUnregistered(address indexed implementation);
event ConfigSet(bytes32 indexed key, address value);
event ConfigUintSet(bytes32 indexed key, uint256 value);
event PriceFeedSet(address indexed asset, address feed, uint32 maxAge, uint8 decimals, address quote);
event SequencerUptimeFeedSet(address feed);
/**
* @notice Add registered assets to Bitty.
* @dev Each asset carries a category, the same way a protocol does. The guard does not interpret
* the value beyond rejecting zero; what each number means is a convention shared with the
* consumers that read it back from {assetCategory}.
* @param assetAddresses The addresses of the assets.
* @param categories The category of each asset, positionally matched.
*/
function addAssets(address[] memory assetAddresses, uint8[] memory categories) external;
/**
* @notice Remove a registered asset from Bitty.
* @dev A removed asset can only be sold instead of being bought. It leaves the registry, so
* {isAssetRegistered} and {assetCategory} answer false and 0 and nothing can buy it, but the
* category it had is kept as its {removedAssetCategory}, which {marketTradeInfo} reports for
* the SOLD leg only, so vaults holding it can still sell it at market.
*
* The kept category drops {ASSET_STABLE_COIN}: an asset taken out of use is usually one that
* can no longer be trusted at its peg, so it is priced by its feed rather than counted as a
* dollar. Its price feed is left in place; a removed stablecoin needs one set (see
* {setPriceFeeds}) before it can be sold at market. Adding the asset again restores it in
* full and clears the kept category.
*
* This sale is the only exit a forever-locked vault has when its escape destination (say,
* an exchange) does not take the asset. Clearing the asset's feed freezes it at market
* instead, and strands it in such vaults, so keep that for a token whose contract itself is
* no longer safe to call.
* @param assetAddresses The addresses of the assets.
*/
function removeAssets(address[] memory assetAddresses) external;
/**
* @notice The exit-only category of an asset {removeAssets} took out of the registry.
* @dev The category it had, without {ASSET_STABLE_COIN}; 0 for an asset that is registered or
* was never removed. Used for the sold leg of a market trade and nothing else.
* @param assetAddress The address of the asset.
* @return uint8 The kept category.
*/
function removedAssetCategory(address assetAddress) external view returns (uint8);
/**
* @notice Check if an asset is registered.
* @dev Check if an asset is registered.
* @param assetAddress The address of the asset.
* @return bool True if the asset is registered, false otherwise.
*/
function isAssetRegistered(address assetAddress) external view returns (bool);
/**
* @notice The category an asset was registered under.
* @param assetAddress The address of the asset.
* @return uint8 The category, or 0 for an address that was never registered or has been removed.
*/
function assetCategory(address assetAddress) external view returns (uint8);
/**
* @notice Add protocols to Bitty.
* @dev Add protocols to Bitty.
* @param protocolAddresses The addresses of the protocols.
*/
function addProtocols(address[] memory protocolAddresses, uint8[] memory categories) external;
/**
* @notice Deprecate protocols from Bitty.
* @dev Deprecate protocols from Bitty.
* @param protocolAddresses The addresses of the protocols.
*/
function deprecateProtocols(address[] memory protocolAddresses) external;
/**
* @notice Is this protocol registered and not deprecated?
* @dev Says nothing about WHICH category — read {protocolCategory} for that. The two questions
* are separate because callers ask them separately: the vault checks that a protocol is
* permitted at all, then that it is the category of protocol this particular call needs.
* @param protocolAddress The address of the protocol.
* @return bool True if registered.
*/
function isProtocolRegistered(address protocolAddress) external view returns (bool);
/**
* @notice Every ACTIVE protocol - registered and not deprecated, across all categories.
* @dev The one list this guard still returns. A vault needs it to answer "does this NFT belong to
* a protocol?", which it cannot work out from membership tests alone; assets have no such
* question, so they are not enumerable.
* @return addresses The active protocols.
*/
function getProtocols() external view returns (address[] memory addresses);
/**
* @notice Every DEPRECATED protocol.
* @dev The companion to {getProtocols}: a protocol is in exactly one of the two. Deprecated ones
* stay enumerable because deprecation is exit-only - vaults keep positions in them, and a
* caller identifying those positions still needs to see the protocol.
* @return addresses The deprecated protocols.
*/
function getDeprecatedProtocols() external view returns (address[] memory addresses);
/**
* @notice Is this protocol deprecated?
* @dev Deliberately separate from {isProtocolRegistered}: the two directions differ. Entering a
* deprecated protocol should fail, while exiting one must keep working, or positions would
* be stranded. Callers layer the rule they need rather than getting one baked in here.
* @param protocolAddress The address of the protocol.
* @return bool True if deprecated.
*/
function isProtocolDeprecated(address protocolAddress) external view returns (bool);
/**
* @notice The category a protocol declared when it was registered.
* @dev The ERC-165 id of one of the four Bitty protocol interfaces, or 0 for an address that was
* never registered. Recorded at registration rather than re-derived, so reading it costs a
* storage load instead of an ERC-165 probe.
* @param protocolAddress The address of the protocol.
* @return uint8 The category interface id, or 0.
*/
function protocolCategory(address protocolAddress) external view returns (uint8);
/**
* @notice Set the implementation for a category.
* @dev Set the implementation for a category.
* @param category The category of the implementation.
* @param implementation The address of the implementation.
*/
function setImplementation(address implementation, uint8 category) external;
/**
* @notice Retire implementations for a category.
* @dev Retire implementations for a category.
* @param category The category of the implementation.
* @param implementations The addresses of the implementations.
*/
function retireImplementations(address[] memory implementations, uint8 category) external;
/**
* @notice Is this implementation registered for a category?
* @dev Is this implementation registered for a category?
* @param category The category of the implementation.
* @param implementation The address of the implementation.
* @return bool True if the implementation is registered for the category.
*/
function isImplementationRegisteredFor(address implementation, uint8 category) external view returns (bool);
/**
* @notice Get the past implementations for a category.
* @dev Get the past implementations for a category.
* @param category The category of the implementation.
* @return addresses The past implementations.
*/
function getPastImplementations(uint8 category) external view returns (address[] memory);
/**
* @notice This guard's version, encoded major * 1e6 + minor * 1e3 + patch.
* @return uint256 The version.
*/
function guardVersion() external pure returns (uint256);
/**
* @notice This guard's version as "major.minor.patch".
* @return string The version name.
*/
function versionName() external pure returns (string memory);
/**
* @notice Get the latest implementation for a category.
* @dev Get the latest implementation for a category.
* @param category The category of the implementation.
* @return address The latest implementation.
*/
function latestImplementation(uint8 category) external view returns (address);
/**
* @notice Read a chain-specific config address by key.
* @dev Keyed by a caller-chosen `bytes32`, e.g. `keccak256("bitty.gasWrapped")`. This is how
* chain-varying addresses (the wrapped-gas token, the governance owner) are sourced from one
* place instead of being injected per deployment.
* @param key The config key.
* @return The configured address, or the zero address if never set.
*/
function getAddress(bytes32 key) external view returns (address);
/**
* @notice Set a chain-specific config address. Restricted to CONFIG_MANAGER_ROLE.
* @param key The config key.
* @param value The address to store under `key`.
*/
function setAddress(bytes32 key, address value) external;
/**
* @notice Read a chain-specific config integer by key.
* @dev The guard stores the raw value only — any ceiling or clamp is the reader's responsibility.
* @param key The config key, e.g. `keccak256("bitty.gas.feePerOp")`.
* @return The configured value, or 0 if never set.
*/
function getUint(bytes32 key) external view returns (uint256);
/**
* @notice Set a chain-specific config integer. Restricted to CONFIG_MANAGER_ROLE.
* @param key The config key.
* @param value The value to store under `key`.
*/
function setUint(bytes32 key, uint256 value) external;
/**
* @notice Set the Chainlink price feed each asset is valued by. Restricted to ASSET_MANAGER_ROLE,
* which keeps how an asset is valued with the role that decides which assets exist.
* @dev Each feed's `decimals()` and each asset's are read and stored here — the native asset,
* address 0, as 18. A zero feed clears the asset's entry, and
* an asset quoted in itself or with no staleness bound is refused.
* @param assets The assets to set feeds for.
* @param feeds The Chainlink feed proxy for each asset, or the zero address to clear it.
* @param maxAges The oldest answer, in seconds, each feed may give and still be trusted.
* @param quotes The asset each feed is quoted in, or the zero address for a USD feed.
*/
function setPriceFeeds(
address[] calldata assets,
address[] calldata feeds,
uint32[] calldata maxAges,
address[] calldata quotes
) external;
/**
* @notice The price feed set for an asset; all zero if none.
* @param asset The asset.
* @return The asset's price feed.
*/
function priceFeed(address asset) external view returns (PriceFeed memory);
/**
* @notice Set the chain's Chainlink L2 sequencer uptime feed. Restricted to CONFIG_MANAGER_ROLE.
* @param feed The uptime feed, or the zero address on a chain without one.
*/
function setSequencerUptimeFeed(address feed) external;
/**
* @notice The chain's Chainlink L2 sequencer uptime feed, or the zero address.
*/
function sequencerUptimeFeed() external view returns (address);
/**
* @notice What an unpriced market trade checks in the guard, in one call: the protocol's category
* and deprecation, and each token's category (0 is unregistered). The sold token's is
* its {removedAssetCategory} when the guard has removed it, so a removed asset can be
* sold but not bought.
* @param protocol The market-trade protocol.
* @param sellToken The token sold.
* @param buyToken The token bought.
*/
function marketTradeChecks(address protocol, address sellToken, address buyToken)
external
view
returns (uint8 protocolCategory, bool protocolDeprecated, uint8 sellCategory, uint8 buyCategory);
/**
* @notice Everything a priced market trade checks in the guard, in one call.
* @dev What {marketTradeChecks} answers, and also the feed of each token that is not a stablecoin,
* the feed of the asset that one is quoted in if it is quoted, and — when either token needed
* a feed — the sequencer uptime feed, except on Ethereum mainnet, which has no sequencer.
* Unset feeds come back zero; whether that is acceptable is the reader's call.
* @param protocol The market-trade protocol.
* @param sellToken The token sold.
* @param buyToken The token bought.
* @return info The trade's guard data.
*/
function marketTradeInfo(address protocol, address sellToken, address buyToken)
external
view
returns (MarketTradeInfo memory info);
}
lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable
struct OwnableStorage {
address _owner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;
function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
assembly {
$.slot := OwnableStorageLocation
}
}
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
function __Ownable_init(address initialOwner) internal onlyInitializing {
__Ownable_init_unchained(initialOwner);
}
function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
OwnableStorage storage $ = _getOwnableStorage();
return $._owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
OwnableStorage storage $ = _getOwnableStorage();
address oldOwner = $._owner;
$._owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin-contracts-upgradeable/contracts/metatx/ERC2771ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (metatx/ERC2771Context.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Context variant with ERC2771 support.
*
* WARNING: Avoid using this pattern in contracts that rely in a specific calldata length as they'll
* be affected by any forwarder whose `msg.data` is suffixed with the `from` address according to the ERC2771
* specification adding the address size in bytes (20) to the calldata size. An example of an unexpected
* behavior could be an unintended fallback (or another function) invocation while trying to invoke the `receive`
* function only accessible if `msg.data.length == 0`.
*
* WARNING: The usage of `delegatecall` in this contract is dangerous and may result in context corruption.
* Any forwarded request to this contract triggering a `delegatecall` to itself will result in an invalid {_msgSender}
* recovery.
*/
abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable _trustedForwarder;
/**
* @dev Initializes the contract with a trusted forwarder, which will be able to
* invoke functions on this contract on behalf of other accounts.
*
* NOTE: The trusted forwarder can be replaced by overriding {trustedForwarder}.
*/
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(address trustedForwarder_) {
_trustedForwarder = trustedForwarder_;
}
/**
* @dev Returns the address of the trusted forwarder.
*/
function trustedForwarder() public view virtual returns (address) {
return _trustedForwarder;
}
/**
* @dev Indicates whether any particular address is the trusted forwarder.
*/
function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
return forwarder == trustedForwarder();
}
/**
* @dev Override for `msg.sender`. Defaults to the original `msg.sender` whenever
* a call is not performed by the trusted forwarder or the calldata length is less than
* 20 bytes (an address length).
*/
function _msgSender() internal view virtual override returns (address) {
uint256 calldataLength = msg.data.length;
uint256 contextSuffixLength = _contextSuffixLength();
if (isTrustedForwarder(msg.sender) && calldataLength >= contextSuffixLength) {
return address(bytes20(msg.data[calldataLength - contextSuffixLength:]));
} else {
return super._msgSender();
}
}
/**
* @dev Override for `msg.data`. Defaults to the original `msg.data` whenever
* a call is not performed by the trusted forwarder or the calldata length is less than
* 20 bytes (an address length).
*/
function _msgData() internal view virtual override returns (bytes calldata) {
uint256 calldataLength = msg.data.length;
uint256 contextSuffixLength = _contextSuffixLength();
if (isTrustedForwarder(msg.sender) && calldataLength >= contextSuffixLength) {
return msg.data[:calldataLength - contextSuffixLength];
} else {
return super._msgData();
}
}
/**
* @dev ERC-2771 specifies the context as being a single address (20 bytes).
*/
function _contextSuffixLength() internal view virtual override returns (uint256) {
return 20;
}
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.20;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* 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. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC1967-compliant implementation pointing to self.
* See {_onlyProxy}.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/MulticallUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Multicall.sol)
pragma solidity ^0.8.20;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {ContextUpgradeable} from "./ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides a function to batch together multiple calls in a single external call.
*
* Consider any assumption about calldata validation performed by the sender may be violated if it's not especially
* careful about sending transactions invoking {multicall}. For example, a relay address that filters function
* selectors won't filter calls nested within a {multicall} operation.
*
* NOTE: Since 5.0.1 and 4.9.4, this contract identifies non-canonical contexts (i.e. `msg.sender` is not {_msgSender}).
* If a non-canonical context is identified, the following self `delegatecall` appends the last bytes of `msg.data`
* to the subcall. This makes it safe to use with {ERC2771Context}. Contexts that don't affect the resolution of
* {_msgSender} are not propagated to subcalls.
*/
abstract contract MulticallUpgradeable is Initializable, ContextUpgradeable {
function __Multicall_init() internal onlyInitializing {
}
function __Multicall_init_unchained() internal onlyInitializing {
}
/**
* @dev Receives and executes a batch of function calls on this contract.
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
bytes memory context = msg.sender == _msgSender()
? new bytes(0)
: msg.data[msg.data.length - _contextSuffixLength():];
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
results[i] = Address.functionDelegateCall(address(this), bytes.concat(data[i], context));
}
return results;
}
}
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.20;
/**
* @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/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)
pragma solidity ^0.8.20;
import {Proxy} from "../Proxy.sol";
import {ERC1967Utils} from "./ERC1967Utils.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 {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
* encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
*
* Requirements:
*
* - If `data` is empty, `msg.value` must be zero.
*/
constructor(address implementation, bytes memory _data) payable {
ERC1967Utils.upgradeToAndCall(implementation, _data);
}
/**
* @dev Returns the current implementation address.
*
* 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() internal view virtual override returns (address) {
return ERC1967Utils.getImplementation();
}
}
lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.20;
import {IBeacon} from "../beacon/IBeacon.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*/
library ERC1967Utils {
// We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
// This will be fixed in Solidity 0.8.21. At that point we should remove these events.
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @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 {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* 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 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 {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-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 the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @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 {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
lib/openzeppelin-contracts/contracts/proxy/Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)
pragma solidity ^0.8.20;
/**
* @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 {
_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();
}
}
lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @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.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.20;
import {IERC1822Proxiable} from "../../interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* 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. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC1967-compliant implementation pointing to self.
* See {_onlyProxy}.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @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 value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @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 or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* 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.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @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`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) 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 FailedInnerCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set 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(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*/
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
}
}
}
lib/openzeppelin-contracts/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
lib/protocol-contracts/src/interfaces/IBittyV1IntentProtocol.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {IBittyV1Protocol} from "./IBittyV1Protocol.sol";
error InvalidOrderId();
/**
* @title IBittyV1IntentProtocol
* @notice Generic interface for vault-custodian intent protocols (CoW Swap, etc.). Intent
* orders are gasless and off-chain: a host-authorised signer signs an order off-chain and posts it
* to the protocol's orderbook. The vault is the ERC-1271 signer and token custodian; it holds no
* on-chain order registry.
*
* At settlement the protocol calls the vault's isValidSignature(), which iterates the registered
* protocol clones and delegates to each clone's isValidSignature() until one returns the EIP-1271
* magic value. The clone validates the off-chain-signed order and defers the allow/auth decision
* to the vault.
*
* @dev Everything the vault needs from an intent protocol lives here, so the vault never has to know
* which one it is talking to - the same rule {IBittyV1Yield} follows for yield. Two things an
* intent protocol would otherwise need the VAULT to do against protocol-specific contracts are
* reshaped so the vault only ever calls its own clone:
*
* - Approval: the vault approves its sell token to {spender}, whatever that is for the protocol
* (CoW's vault relayer, for one).
* - Cancellation: {cancelOrders} records the cancel in the clone, and {isValidSignature} refuses a
* cancelled order from then on. Every settlement of every intent protocol reaches the order
* through the vault's isValidSignature and therefore through this clone, so this is a hard cancel
* for all of them without the vault calling a settlement contract. A protocol's own off-chain
* soft-cancel (CoW's orderbook) may still be used alongside it to drop the order from the book.
*/
interface IBittyV1IntentProtocol is IBittyV1Protocol {
/// @notice Orders cancelled by the vault. `orderIds` are as the protocol names its orders.
event OrdersCancelled(bytes[] orderIds);
/**
* @notice EIP-1271 — validate an off-chain-signed order for the vault that owns this protocol clone.
* @dev Returns the invalid value, never the magic value, for an order cancelled with {cancelOrders}.
* @param hash The hash of the order.
* @param signature The signature of the order.
* @return The magic value if the order is valid, otherwise the invalid value.
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4);
/**
* @notice The address the vault approves its sell tokens to, so the protocol can pull them at
* settlement.
*/
function spender() external view returns (address);
/**
* @notice Cancel orders. Owner (the vault) only; the vault decides who may ask it to.
* @dev Permanent: a cancelled order id is never valid again. Reverts with {InvalidOrderId} for an id
* the protocol could not have issued.
* @param orderIds The protocol's own order ids (CoW: the order UID).
*/
function cancelOrders(bytes[] calldata orderIds) external;
/// @notice Whether `orderId` was cancelled with {cancelOrders}.
function isOrderCancelled(bytes calldata orderId) external view returns (bool);
}
lib/protocol-contracts/src/interfaces/IBittyV1MarketTradeProtocol.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {IBittyV1Protocol} from "./IBittyV1Protocol.sol";
/**
* @title IBittyV1MarketTradeProtocol
* @notice Immediate (market) swaps: exact-in and exact-out, routed by the adapter. Stateless — the
* adapter holds no position between calls, so a single router adapter can serve every pool
* version at once.
*/
interface IBittyV1MarketTradeProtocol is IBittyV1Protocol {
/**
* @notice Exact-input swap (market sell): sell exactly `sellAmount`, receive ≥ `buyAmountMin`,
* delivered to `recipient`. Pass the vault itself as `recipient` for a normal swap, or a
* receiver to swap and pay it in one step.
* @dev data = abi.encode(sellToken, sellAmount, buyToken, buyAmountMin, path). Gated by the host.
*/
function swap(bytes memory data, address recipient) external payable;
/**
* @notice Exact-output swap (market buy): receive exactly `buyAmount`, spend ≤ `sellAmountMax`,
* delivered to `recipient`.
* @dev data = abi.encode(sellToken, sellAmountMax, buyToken, buyAmount, reversedPath). The path
* must be reversed (buyToken → … → sellToken) per Uniswap V3 exactOutput. Gated by the host.
*/
function swapExactOut(bytes memory data, address recipient) external;
}
lib/protocol-contracts/src/interfaces/IBittyV1Protocol.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
error InvalidAsset();
/**
* @title IBittyV1Protocol
* @notice Interface for all protocols.
* @dev A protocol does NOT declare its own category. The guard defines it, and consumers read it
* back from {IBittyV1Guard-protocolCategory}. Curation and classification are therefore the
* same act, by the same party, which is why an adapter is never asked to describe itself: a
* self-declared category would be one more thing to verify without being the one that counts.
*/
interface IBittyV1Protocol {
/**
* @notice Initialize the protocol.
* @param newOwner The address of the new owner.
* @dev Initialize the protocol.
*/
function initialize(address newOwner) external;
/**
* @notice The code lineage this adapter belongs to - which protocol it adapts, not which kind of
* protocol it is.
* @dev Guards in-place upgrades. The guard's category is curation and is deliberately coarse:
* Aave and Sky are both lending, and their storage layouts are identical, so repointing an
* Aave instance at the Sky adapter passes every category check and then silently reads
* Aave's cached aToken addresses as Sky's receipt tokens. Nothing reverts, because the
* layouts agree and only the meaning changed. An upgrade is therefore refused unless both
* sides report the same lineage.
* @dev Self-declared, unlike the category, and the difference is the point: the category decides
* WHETHER an adapter may be used at all and so belongs to whoever curates the registry,
* while lineage only answers whether two adapters the guard has ALREADY blessed are the
* same code line. A dishonest answer requires the guard to have blessed a dishonest
* adapter, so the guard remains the trust root either way.
* @return The lineage identifier, e.g. keccak256("bitty.adapter.aave.v3").
*/
function protocolLineage() external view returns (bytes32);
/**
* @notice This adapter's version within its {protocolLineage}, increasing with each release.
* @dev Upgrades are one-way: an instance may only be repointed at a STRICTLY higher version of
* its own lineage. Without this, every check still passes when repointing an instance back
* at the older adapter it was upgraded away from - so a fixed bug could be silently
* reintroduced, and the whole point of patching in place lost. Strictness also rejects
* repointing an instance at the version it already runs, which is only ever a wasted
* transaction.
* @dev A number rather than the free-form string this interface used to carry, because the vault
* has to ORDER two of these on chain and a string cannot be compared without parsing it.
* Semver is encoded as major * 1e6 + minor * 1e3 + patch, which keeps the ordering the
* comparison needs while still naming a release a human recognises: 1.0.0 is 1_000_000 and
* 1.1.2 is 1_001_002. Minor and patch are therefore capped at 999.
* @return The encoded version. See {versionName} for the readable form.
*/
function protocolVersion() external view returns (uint256);
/**
* @notice The human-readable version, e.g. "1.1.2". For display.
* @dev DERIVED from {protocolVersion} rather than declared alongside it. Two independently
* written fields would eventually disagree - someone bumps the number the vault compares
* and forgets the string the UI shows - and the disagreement would surface as a version
* that upgrades correctly while displaying the wrong release, which is worse than either
* being wrong on its own.
* @return The version as "major.minor.patch".
*/
function versionName() external view returns (string memory);
}
lib/protocol-contracts/src/interfaces/IBittyV1Yield.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
error ClaimNotSupported();
error WithdrawToNotSupported();
/**
* @title IBittyV1Yield
* @notice Putting an asset to work in a protocol and taking it back out again.
* @dev Deliberately says nothing about WHAT KIND of protocol it is. Lending and staking are different
* types - and there will be more - but a vault entering or exiting a position asks the same
* things of all of them, so the type belongs in the guard's category, which is curation, and not
* in this interface, which is capability. Everything the vault needs lives here, so it never has
* to ask what it is talking to.
* @dev Entering and exiting are ONE capability, not two. No adapter has ever taken an asset in
* without also handing it back - a one-way adapter would be a trap, not a protocol - so
* splitting the two only forced every caller to name which half it meant before it could ask.
*/
interface IBittyV1Yield {
/**
* @notice Deposit the asset into the protocol.
* @dev Not payable. Assets reach an adapter as ERC-20 transfers - native ETH is wrapped by the
* vault before it gets here - so no adapter has ever read msg.value and the vault has never
* attached any. Accepting value would only create a way for ETH to strand in an adapter with
* no path back out.
* @param asset The address of the asset to deposit.
* @param amount The amount of the asset to deposit.
*/
function deposit(address asset, uint256 amount) external;
/**
* @notice Withdraw the asset from the protocol, delivered to `recipient`.
* @dev Pass the vault as `recipient` for a normal withdrawal, or a receiver to pay it straight out
* of a position in a single step. Protocols that settle asynchronously support only the vault
* itself and revert otherwise, since there is nothing to deliver yet.
* @param asset The address of the asset.
* @param amount The amount of the asset to withdraw.
* @param recipient The address that receives the withdrawn asset.
* @return delivered The amount of `asset` delivered to `recipient`, 0 when settlement is deferred.
*/
function withdraw(address asset, uint256 amount, address recipient) external returns (uint256 delivered);
/**
* @notice What this vault holds in the protocol, valued in `asset`.
* @dev One name for what lending called a supplied balance and staking called a staked balance.
* They were always the same question, and two names forced every caller to know which kind
* of protocol it held before it could ask.
* @param asset The address of the asset.
* @return uint256 The balance, in `asset` terms.
*/
function getBalance(address asset) external view returns (uint256);
/**
* @notice Withdrawals requested but not yet claimed.
* @dev EMPTY for a protocol that settles synchronously, which is what makes this askable of any
* yield protocol rather than only of the asynchronous ones. A caller walks the ids and
* claims what has finalised; getting nothing back means there is nothing outstanding.
* @return uint256[] The outstanding withdrawal ids.
*/
function getPendingWithdrawalIds() external view returns (uint256[] memory);
/**
* @notice Claim withdrawals that have finalised.
* @dev Reverts with {ClaimNotSupported} on a protocol that settles synchronously - reachable only
* by calling it with ids that protocol could never have issued.
* @param ids The withdrawal ids to claim.
*/
function claimWithdrawals(uint256[] memory ids) external;
}
lib/solmate/src/tokens/ERC20.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/*//////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*//////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*//////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*//////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*//////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
address recoveredAddress = ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
),
v,
r,
s
);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*//////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
lib/solmate/src/tokens/WETH.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
import {ERC20} from "./ERC20.sol";
import {SafeTransferLib} from "../utils/SafeTransferLib.sol";
/// @notice Minimalist and modern Wrapped Ether implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/WETH.sol)
/// @author Inspired by WETH9 (https://github.com/dapphub/ds-weth/blob/master/src/weth9.sol)
contract WETH is ERC20("Wrapped Ether", "WETH", 18) {
using SafeTransferLib for address;
event Deposit(address indexed from, uint256 amount);
event Withdrawal(address indexed to, uint256 amount);
function deposit() public payable virtual {
_mint(msg.sender, msg.value);
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint256 amount) public virtual {
_burn(msg.sender, amount);
emit Withdrawal(msg.sender, amount);
msg.sender.safeTransferETH(amount);
}
receive() external payable virtual {
deposit();
}
}
lib/solmate/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
import {ERC20} from "../tokens/ERC20.sol";
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
library SafeTransferLib {
/*//////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Transfer the ETH and store if it succeeded or not.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
require(success, "ETH_TRANSFER_FAILED");
}
/*//////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "from" argument.
mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
// We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
success := call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data and token has code.
if and(iszero(and(eq(mload(0), 1), gt(returndatasize(), 31))), success) {
success := iszero(or(iszero(extcodesize(token)), returndatasize()))
}
}
require(success, "TRANSFER_FROM_FAILED");
}
function safeTransfer(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
success := call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data and token has code.
if and(iszero(and(eq(mload(0), 1), gt(returndatasize(), 31))), success) {
success := iszero(or(iszero(extcodesize(token)), returndatasize()))
}
}
require(success, "TRANSFER_FAILED");
}
function safeApprove(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
success := call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data and token has code.
if and(iszero(and(eq(mload(0), 1), gt(returndatasize(), 31))), success) {
success := iszero(or(iszero(extcodesize(token)), returndatasize()))
}
}
require(success, "APPROVE_FAILED");
}
}
src/BittyV1AccountBase.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {ContextUpgradeable} from "openzeppelin-contracts-upgradeable/utils/ContextUpgradeable.sol";
import {ERC2771ContextUpgradeable} from "openzeppelin-contracts-upgradeable/metatx/ERC2771ContextUpgradeable.sol";
import {OwnableUpgradeable} from "openzeppelin-contracts-upgradeable/access/OwnableUpgradeable.sol";
import {MulticallUpgradeable} from "openzeppelin-contracts-upgradeable/utils/MulticallUpgradeable.sol";
import {Address} from "openzeppelin-contracts/contracts/utils/Address.sol";
import {BITTY_FORWARDER} from "./logic/Constants.sol";
import {BittyStorage, VaultStorage} from "./logic/BittyStorage.sol";
/**
* @title BittyV1AccountBase
* @notice The shared context every account and the shared DeFi facet inherit: ERC-2771 relaying against
* the fixed Bitty forwarder, and the vault's authority. The owner is read from a FIXED ERC-7201
* slot ({BittyStorage}), which is what lets the delegatecalled facet's `_msgSender() == owner()`
* resolve to the vault's owner.
* @dev `owner()` is overridden here rather than on the vault, because a matured handover takes effect
* on a clock and both contracts have to agree about it — see the override below.
*
* Batching lives here, next to the context it depends on. {MulticallUpgradeable} self-delegatecalls each entry, so `msg.sender` and storage
* stay the caller's throughout and every call is authorised exactly as it would be alone —
* batching grants nothing. It also re-appends the ERC-2771 sender suffix to each sub-call, which
* a hand-rolled loop would drop, silently turning a relayed batch into calls attributed to the
* forwarder.
*
* The UPGRADEABLE variant specifically: the non-upgradeable {Multicall} pulls in plain `Context`
* and collides with `ContextUpgradeable` here, which is what dropped batching in the first place.
*/
abstract contract BittyV1AccountBase is ERC2771ContextUpgradeable, OwnableUpgradeable, MulticallUpgradeable {
/**
* @dev The activation window. While an account is being initialised, the address that initialised
* it (the factory) is honoured as a trusted forwarder, so the calls it hands over run with the
* OWNER's authority exactly as a relayed call would. TRANSIENT on purpose: the window opens
* inside `initialize` and is closed before it returns, and the slot is wiped at the end of the
* transaction regardless - so a factory upgrade can never impersonate the owner of a vault
* that already exists. Not an ERC-7201 slot, and never part of the storage layout.
*/
bytes32 private constant _ACTIVATOR_TSLOT = keccak256("bitty.account.activator.transient");
constructor() ERC2771ContextUpgradeable(address(0)) {}
function trustedForwarder() public view virtual override returns (address) {
return BITTY_FORWARDER;
}
/**
* @dev A contract that re-enters during the activation window is not the activator, so it gets no
* suffix and is attributed to itself.
*/
function isTrustedForwarder(address forwarder) public view virtual override returns (bool) {
if (forwarder == BITTY_FORWARDER) return true;
address activator;
bytes32 slot = _ACTIVATOR_TSLOT;
assembly {
activator := tload(slot)
}
return activator != address(0) && forwarder == activator;
}
/**
* @dev The owner is appended to each entry as the ERC-2771 suffix, which is what {_msgSender}
* reads while `msg.sender` (the activator) is trusted. Reverts bubble up, so an activation
* with a failing entry leaves no account behind.
*/
function _runAsOwner(address owner_, bytes[] calldata calls) internal {
bytes32 slot = _ACTIVATOR_TSLOT;
assembly {
tstore(slot, caller())
}
for (uint256 i; i < calls.length; ++i) {
Address.functionDelegateCall(address(this), bytes.concat(calls[i], bytes20(owner_)));
}
assembly {
tstore(slot, 0)
}
}
error PayRelayerFeeNotRelayable();
bytes4 private constant _PAY_RELAYER_FEE_SELECTOR = bytes4(keccak256("payRelayerFee(address,uint256)"));
function multicall(bytes[] calldata data)
external
virtual
override(MulticallUpgradeable)
returns (bytes[] memory results)
{
// Same ERC-2771 suffix handling as OZ's MulticallUpgradeable, with the payRelayerFee guard added.
bytes memory context =
msg.sender == _msgSender() ? new bytes(0) : msg.data[msg.data.length - _contextSuffixLength():];
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; ++i) {
if (data[i].length >= 4 && bytes4(data[i][:4]) == _PAY_RELAYER_FEE_SELECTOR) {
revert PayRelayerFeeNotRelayable();
}
results[i] = Address.functionDelegateCall(address(this), bytes.concat(data[i], context));
}
}
function owner() public view virtual override returns (address) {
VaultStorage storage $ = BittyStorage.vault();
uint256 readyAt = $.ownershipReadyAt;
if (readyAt != 0 && block.timestamp >= readyAt) return $.pendingOwner;
return $.vaultOwner;
}
function _transferOwnership(address newOwner) internal virtual override {
VaultStorage storage $ = BittyStorage.vault();
address previous = $.vaultOwner;
$.vaultOwner = newOwner;
emit OwnershipTransferred(previous, newOwner);
}
function _msgSender()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (address)
{
return ERC2771ContextUpgradeable._msgSender();
}
function _msgData()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (bytes calldata)
{
return ERC2771ContextUpgradeable._msgData();
}
function _contextSuffixLength()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (uint256)
{
return ERC2771ContextUpgradeable._contextSuffixLength();
}
}
src/BittyV1VaultBase.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {BittyV1AccountBase} from "./BittyV1AccountBase.sol";
import {OwnableUpgradeable} from "openzeppelin-contracts-upgradeable/access/OwnableUpgradeable.sol";
import {UUPSUpgradeable} from "openzeppelin-contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {OwnershipNotRenounceable, ImplementationNotRegistered, VaultNotNewer} from "./interfaces/IBittyV1Vault.sol";
import {BITTY_GUARD} from "./logic/Constants.sol";
import {LockLib} from "./logic/LockLib.sol";
import {IBittyV1Guard, IMPLEMENTATION_VAULT} from "guard-contracts/src/interfaces/IBittyV1Guard.sol";
import {Strings} from "openzeppelin-contracts/contracts/utils/Strings.sol";
/**
* @title BittyV1VaultBase
* @notice The main vault's base: ownership and owner-controlled UUPS upgrades. A handover runs on a
* clock — started in one call and complete when the vault's timelock expires, with no
* acceptance step — see {BittyV1Vault-transferOwnership} for why a wait beats a second
* signature against a key
* that has leaked, and {BittyV1Vault-owner} for how authority moves without a transaction.
* Ownership cannot be given up: a vault with nobody answering for it was replaced by
* {BittyV1Vault-foreverLock}, which freezes the same risk surface while leaving the owner
* able to use what is left.
*
* Upgrades are instant, and may only move forward. The target must be a guard-blessed
* implementation and the guard timelocks the blessing globally, so the delay belongs there
* rather than here: it is the code that has to prove itself, not the owner. A vault stays
* upgradeable for life, with no opt-out — except while it is locked: an emergency lock pauses
* upgrades until it is released, and a forever lock freezes the code for good.
*/
abstract contract BittyV1VaultBase is BittyV1AccountBase, UUPSUpgradeable {
// 1.2.1: cross-chain payees (addWhitelistedRecipientOn, bridgeToWhitelistedRecipient) and
// bridgeTo. The 1.2.0 implementation (0x71caa7162EA64072C0D9B7E271b4b42a76888be3) was built
// before them; this moves past it so a vault on it can upgrade.
uint256 private constant _VERSION = 1 * 1_000_000 + 2 * 1_000 + 1;
function vaultVersion() external pure virtual returns (uint256) {
return _VERSION;
}
function versionName() external pure returns (string memory) {
return string.concat(
Strings.toString(_VERSION / 1_000_000),
".",
Strings.toString((_VERSION / 1_000) % 1_000),
".",
Strings.toString(_VERSION % 1_000)
);
}
function upgrade(address newImpl) external {
upgradeToAndCall(newImpl, "");
}
function _authorizeUpgrade(address newImpl) internal view override {
_checkOwner();
LockLib.requireNotLocked();
if (!IBittyV1Guard(BITTY_GUARD).isImplementationRegisteredFor(newImpl, IMPLEMENTATION_VAULT)) {
revert ImplementationNotRegistered();
}
if (BittyV1VaultBase(payable(newImpl)).vaultVersion() <= this.vaultVersion()) revert VaultNotNewer();
}
function _msgSender() internal view override returns (address) {
return BittyV1AccountBase._msgSender();
}
function _msgData() internal view override returns (bytes calldata) {
return BittyV1AccountBase._msgData();
}
function _contextSuffixLength() internal view override returns (uint256) {
return BittyV1AccountBase._contextSuffixLength();
}
function renounceOwnership() public pure override {
revert OwnershipNotRenounceable();
}
}
src/interfaces/IBittyV1DeFi.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
error InvalidDepositableProtocol();
error InvalidWithdrawableProtocol();
error InvalidMarketTradeProtocol();
error InvalidIntentProtocol();
error ProtocolNotInstantiated();
error ProtocolLineageMismatch();
error ProtocolNotNewer();
error GrantTooLong();
error AssetManagerExpiryInPast();
error MarketTradeNotSupported();
error MarketTradePriceTooLow();
error DailyLossAllowanceExceeded();
error PriceFeedMissing(address asset);
error PriceStale(address asset);
error SequencerDown();
error BridgeNotEnabled();
error InvalidBridgeProtocol();
error AssetNotBridgeable();
error BridgeAmountMismatch();
error BridgeToSelf();
/**
* @dev The adapter call the vault makes, mirrored from protocol-store's IBittyV1BridgeProtocol until
* the vault's protocol-contracts pin carries it.
*/
interface IBittyV1BridgeAdapter {
function bridge(address token, uint256 amount, uint256 fee, bytes calldata data)
external
payable
returns (uint256 received);
function bridgeTo(
address token,
uint256 amount,
uint256 fee,
uint256 destinationChainId,
bytes32 recipient,
bytes calldata data
) external returns (uint256 received);
}
/**
* @title IBittyV1DeFi
* @notice The trading/yield surface. Named for the capability, not a caller: it is written once in
* {BittyV1VaultDeFiFacet} and reached through the vault's fallback. The facet authorises the
* vault's `owner()` and, for what its permissions name, the vault's asset manager
* ({IBittyV1Vault-setAssetManager}). Owner-only config (protocol add/remove) lives in {IBittyV1Owner}; the read functions
* (getBalances, protocol getters, …) live in {IBittyV1Vault}.
*/
interface IBittyV1DeFi {
/**
* @notice Put an asset into a depositable protocol.
* @dev One entry for every protocol the vault can deposit into. Supply and stake were the same
* call under two names, and the adapters expose it as {IBittyV1Yield-deposit}, so the
* vault does not distinguish the kinds - nor will it have to for kinds added later.
* @param depositProtocol The protocol to deposit into.
* @param assetAddress The address of the asset to deposit.
* @param amount The amount of the asset to deposit.
*/
function deposit(address depositProtocol, address assetAddress, uint256 amount) external;
/**
* @notice Withdraw assets from any protocol the vault holds a position in.
* @param withdrawProtocol The withdrawable protocol to withdraw assets from.
* @param assetAddress The address of the asset to withdraw.
* @param amount The amount of the asset to withdraw.
*/
function withdraw(address withdrawProtocol, address assetAddress, uint256 amount) external;
/**
* @notice Withdraw assets from multiple protocol positions in one call.
* @dev All arrays must have the same length. Use {withdraw} for a single position.
* @param withdrawProtocols The protocols to withdraw from.
* @param assetAddresses The assets to withdraw from each protocol.
* @param amounts The amounts to withdraw from each protocol.
*/
function withdraws(
address[] calldata withdrawProtocols,
address[] calldata assetAddresses,
uint256[] calldata amounts
) external;
/**
* @notice Claim one finalized withdrawal.
* @dev For protocols whose exit is asynchronous - a staking queue, a redemption delay - where
* {withdraw} only opens the request and the assets arrive on a later claim.
* @param withdrawProtocol The protocol to claim from.
* @param id A pending withdrawal id, as listed by {IBittyV1Vault-getPendingWithdrawalIds}.
*/
function claimWithdrawal(address withdrawProtocol, uint256 id) external;
/**
* @notice Claim several finalized withdrawals.
* @param withdrawProtocol The protocol to claim from.
* @param ids The pending withdrawal ids to claim.
*/
function claimWithdrawals(address withdrawProtocol, uint256[] memory ids) external;
/**
* @notice Approve a token to the intent protocol's spender - whatever the protocol pulls sell tokens
* through at settlement (CoW's vault relayer, for one), as its clone names it.
* @param intentProtocol The intent protocol to approve the spender for.
* @param token The token to approve.
*/
function approveIntentSpender(address intentProtocol, address token) external;
/**
* @notice Cancel an off-chain intent order. Recorded in the protocol's clone, which then refuses the
* order at settlement. Still allowed once the protocol is deprecated.
* @param intentProtocol The intent protocol the order was placed on.
* @param orderUid The protocol's own order id (CoW: the order UID).
*/
function cancelIntentOrder(address intentProtocol, bytes calldata orderUid) external;
/**
* @notice Cancel several off-chain intent orders on one protocol in one call.
* @param intentProtocol The intent protocol the orders were placed on.
* @param orderUids The protocol's own order ids.
*/
function cancelIntentOrders(address intentProtocol, bytes[] calldata orderUids) external;
event BridgeEnabledSet(bool enabled, uint64 effectiveAt);
event Bridged(
address indexed bridgeProtocol, address indexed asset, uint256 amount, uint256 fee, uint256 received, bytes data
);
event BridgedTo(
address indexed bridgeProtocol,
address indexed asset,
uint256 destinationChainId,
bytes32 indexed recipient,
uint256 amount,
uint256 fee,
uint256 received,
bytes data
);
event WhitelistedRecipientBridged(
uint256 indexed id,
address indexed bridgeProtocol,
address indexed asset,
uint256 destinationChainId,
bytes32 recipient,
uint256 amount,
uint256 fee,
uint256 received
);
/**
* @notice Turn the bridge function on or off, both {bridge} and {bridgeTo}. A vault starts with
* it on, like market trading: what a bridge to this vault's counterpart loses is bounded
* by the daily loss allowance, and what it moves stays under that counterpart, whose own
* limits still apply; a bridge to anyone else is a send, bounded by the send allowance.
* @dev Turning it back on waits out the risk timelock and is refused under a lock; a lock also
* drops a pending turn-on. Turning it off applies at once, locked or not.
*/
function setBridgeEnabled(bool enabled) external;
/**
* @return enabled Whether the vault can bridge now.
* @return enableAt When a pending turn-on takes effect, or 0 if none is waiting.
*/
function bridgeSettings() external view returns (bool enabled, uint64 enableAt);
/**
* @notice Bridge `amount` of `asset` to this vault's counterpart on another chain through
* `bridgeProtocol`. Owner only, never an asset manager; not under a lock; and only once
* the bridge function is on.
* @dev The vault does not read the bridge's request itself; the guard-registered adapter does,
* and it is the adapter that pins the recipient and bounds what the bridge may keep (see
* protocol-store's AcrossBridgeProtocol). The recipient is this vault's counterpart: between
* EVM chains its own address, which is the same on every EVM chain; to or from TRON, where
* the address differs, the vault its creation owner has there. There is no amount limit, as
* for a payout to a default whitelisted address. A bridge only moves money between a vault
* and its counterparts, so the set of them is as strong as the weakest.
*
* The counterpart belongs to whoever owns it on that chain. Ownership is per chain: after
* this vault is handed to a new key here (a rotation, a sale, the recovery from a stolen
* key), the same address elsewhere stays the old key's until it is handed over there too.
*
* `asset` is address(0) for the native coin, which the vault holds as its wrapped gas token
* and unwraps for the bridge. The asset (the wrapped gas token, for native) must carry the
* guard's bridgeable category, and the protocol the bridge category. Exactly `amount` leaves
* the vault, `fee` of it as Bitty's fee, capped by the adapter. What does not arrive on the
* other side (the fee and the bridge's cost) is charged to the daily loss allowance, valued
* at oracle price, so an asset without a price feed (or a stablecoin) cannot be bridged.
* @param bridgeProtocol The guard-registered bridge adapter.
* @param asset The asset to send, address(0) for the native coin.
* @param amount What leaves the vault, fee included.
* @param fee Bitty's fee out of `amount`.
* @param data The adapter's request (Across: abi.encode(AcrossQuote) from Across's quote, followed
* by the vault's creation owner to or from TRON).
*/
function bridge(address bridgeProtocol, address asset, uint256 amount, uint256 fee, bytes calldata data) external;
/**
* @notice Bridge `amount` of a stablecoin `asset` to `recipient` on another chain through
* `bridgeProtocol`: a send that crosses chains. Owner only, never an asset manager; not
* under a lock; and only once the bridge function is on.
* @dev The whole `amount`, fee included, is metered against the send allowance and its day,
* shared with {IBittyV1Vault-send}, exactly as a send of it would be; nothing is charged
* to the daily loss allowance. At a send allowance of 0 it is refused, as a send is. The
* asset must be a stablecoin even when the send allowance is {NO_LIMIT}, and carry the
* guard's bridgeable category; the native coin cannot go this way. The adapter pays
* `recipient` and no one else, and still holds the quote to its route (the token that
* arrives and the most the bridge may keep). Exactly `amount` leaves the vault. An unfilled
* deposit is refunded to this vault.
*
* `recipient` may not be this vault's own address: to this vault's counterpart, {bridge}
* is the way, metered only by the daily loss allowance; and the same address on TRON is
* not the counterpart, but an address no one holds.
*
* `recipient` is whatever address the owner names there. The vault cannot see the other
* chain: an address that is the owner's on this chain need not be on that one (a contract
* wallet deployed here only, say), and what is paid to it is gone.
* @param bridgeProtocol The guard-registered bridge adapter.
* @param asset The stablecoin to send.
* @param amount What leaves the vault, fee included.
* @param fee Bitty's fee out of `amount`.
* @param destinationChainId The chain `recipient` is on; the adapter refuses a quote for another.
* @param recipient Who is paid on the destination chain, as 32 bytes: a 20-byte address (EVM,
* or TRON without its 0x41 prefix) left-padded, a Solana address in full.
* @param data The adapter's request (Across: abi.encode(AcrossQuote) from Across's quote).
*/
function bridgeTo(
address bridgeProtocol,
address asset,
uint256 amount,
uint256 fee,
uint256 destinationChainId,
bytes32 recipient,
bytes calldata data
) external;
/**
* @notice Add a whitelisted recipient on one network, or on every EVM chain. Owner only; not
* under a lock.
*
* - One network (`chainId` its id, TRON 728126428): `recipient` there, paid only by
* {bridgeToWhitelistedRecipient} to that chain. No payout on this chain pays it, and
* it is not an escape recipient for {IBittyV1Owner-foreverLock}.
* - Every EVM chain (`chainId` = type(uint256).max): the same address on all of them.
* Paid here like an ordinary entry (and an escape recipient like one), and by
* {bridgeToWhitelistedRecipient} to any chain the guard marks as EVM
* (`getUint(keccak256(abi.encode(keccak256("bitty.chain.evm"), chainId))) == 1`) and
* a route reaches; never to one it does not mark, like TRON or Solana, which take a
* payee of their own.
* - This chain (`chainId` 0 or this chain's id): an ordinary entry, as
* {IBittyV1Owner-addWhitelistedRecipient} adds.
* @dev The same protection window, removal rules and lock rules as an entry here, and the same
* ids. The vault's own address is refused for another chain or every EVM chain. An address
* that is the owner's on one EVM chain need not be on another (a contract wallet deployed
* on one only), so every EVM chain is for an address that is the same everywhere, like a
* plain key's.
* @param chainId The network the recipient is on; type(uint256).max for every EVM chain.
* @param recipient Its address there as 32 bytes: a 20-byte address (EVM, or TRON without its
* 0x41 prefix) left-padded, a Solana address in full. Only one network's entry may be
* wider than 20 bytes ({RecipientNotAnAddress} otherwise).
* @return id The entry's id.
*/
function addWhitelistedRecipientOn(uint256 chainId, bytes32 recipient) external returns (uint256 id);
/**
* @notice Bridge `amount` of `asset` to whitelisted recipient `id` on `destinationChainId`
* through `bridgeProtocol`, with no amount limit, as a payout to a whitelisted recipient
* here. Owner only, never an asset manager; allowed under either lock, but only while
* the bridge function is on.
* @dev The entry must reach `destinationChainId` (be on it, or on every EVM chain with that one
* marked EVM in the guard; never this chain), the adapter must have a route there, and the
* entry be payable now (its window run, not voided by a lock, no
* removal landed). Nothing is metered: not the send allowance, not the loss allowance.
* Any ERC-20 with the guard's bridgeable category; not the native coin. The entry fixes the
* chain and the address, and the adapter is held to both and to its route. Exactly `amount`
* leaves the vault; an unfilled deposit is refunded to this vault.
* @param bridgeProtocol The guard-registered bridge adapter.
* @param id The whitelisted recipient, on another chain.
* @param asset The ERC-20 to send.
* @param amount What leaves the vault, fee included.
* @param fee Bitty's fee out of `amount`.
* @param destinationChainId Where the recipient is paid.
* @param data The adapter's request (Across: abi.encode(AcrossQuote) for that chain).
*/
function bridgeToWhitelistedRecipient(
address bridgeProtocol,
uint256 id,
address asset,
uint256 amount,
uint256 fee,
uint256 destinationChainId,
bytes calldata data
) external;
}
src/interfaces/IBittyV1Forwarder.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
/**
* @title IBittyV1Forwarder
* @notice The one thing an account needs to ask its forwarder: are you charging me, right now, in
* this call?
* @dev `payRelayerFee` moves the vault's gas budget and used to authorise on `msg.sender ==
* trustedForwarder()` alone. That is not the same question. The forwarder is the caller for
* every relayed user op too — a relayed call runs with the forwarder as `msg.sender` by
* design — so "the forwarder is calling" was true in a situation the charge was never meant
* for, and anything that could reach the account's own entry points through a relayed request
* could reach the charge: `multicall([payRelayerFee])`, signed by any key with no role
* anywhere, drained every vault's daily budget to the fee collector.
*
* {chargingVault} answers the right question. The forwarder opens a transient window around
* its own settlement step naming the vault it is about to charge, and the account checks it:
* inside a relayed request the window is shut, so a charge smuggled into relayed calldata
* reverts however deeply it is nested and whatever new path finds its way there.
*/
interface IBittyV1Forwarder {
/**
* @notice The vault this forwarder is settling a fee for in this call, or the zero address.
* @dev Transient: true only between the relayed work finishing and the charge returning. A read
* at any other moment, including from inside a relayed request, is zero.
*/
function chargingVault() external view returns (address);
}
src/interfaces/IBittyV1Owner.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {AutoYield, IBittyV1Vault} from "./IBittyV1Vault.sol";
/**
* @title IBittyV1Owner
* @notice The owner-only vault surface: configuration, the locks, sub-account guardrails, payment
* creation, and the whitelisted-recipient payout. Implemented by {BittyV1Vault}. Reads and
* permissionless calls live in {IBittyV1Vault}; trading and yield in {IBittyV1DeFi}.
*/
interface IBittyV1Owner {
/**
* The whole risk surface, in three numbers. `type(uint256).max` in any means "leave it alone",
* so the owner can set one without restating the others.
*
* Four numbers stood here: a protection window for new payees, a send cap, the period that cap
* ran over, and a timelock on changing any of it. Owners only ever had two questions, and the
* rest was one of them asked twice — a protection window and a change timelock are both "how
* long do I get to notice", and with one cap over a fixed day there is nothing for a separate
* period to vary.
*
* A vault created from 1.1.1 on starts open: no timelock, and no limit on either allowance
* (`type(uint64).max - 1`), so regular sends take any asset and amount and trades and bridges are
* not priced. The owner protects it by setting numbers, each a tightening, so at once. One never
* set reads, on a vault created before 1.1.1, as 1 day and, from 1.0.10, sends off and 1,000 for
* losses; before 1.0.10, 10,000 for each allowance.
*
* `timelock` is the single wait in front of everything deferred: a new whitelisted recipient, the
* removal of one the owner can already pay, an asset-manager grant, a handover of the
* vault, and any loosening of these numbers. 0, or 1 to 30 days; above 0, both allowances must be
* numbers, not no limit ({TimelockNeedsLimits}), so going back to no limit means lowering the
* timelock to 0 first, which waits out the timelock in force.
* `sendDailyAllowance` is the ceiling on what may leave through regular sends, in whole USD per
* day, from 0 to 1,000,000, or no limit; 0 turns regular sends off. Under a ceiling, regular sends
* are held to stablecoins, the only assets that can be metered without reading a price. More than
* this, and any other asset, leaves through a whitelisted recipient.
*
* `dailyLossAllowance` bounds what market trades and bridges lose, from 0 to 1,000,000 whole USD
* per day, or no limit; 0 turns both off. A trade is a way out of the vault too: a leaked key that
* sells into a pool it set up itself takes value without sending anything. So under a ceiling every
* market trade, the owner's or an asset manager's, is valued at oracle price (a stablecoin counts
* as a dollar), must come out within 5% of what it gave up, and what it came out short — price
* impact and fees included — is charged against this ceiling. Only assets with a price feed can be
* traded at market. A bridge is charged the same way for what does not arrive on the other side:
* the bridge's cost and Bitty's fee.
* The two ceilings are kept apart so that trading and bridging never use up what may be sent, and
* sending never uses up what they may lose.
*
* All three move under the ratchet: tightening applies at once, loosening waits out the timelock
* in force when it was asked for.
*/
struct RiskSettings {
uint256 timelock;
uint256 sendDailyAllowance;
uint256 dailyLossAllowance;
}
event WhitelistedRecipientSet(uint256 indexed id, address recipient);
/**
* @notice A whitelisted recipient on another chain, paid only by a bridge. See
* {IBittyV1DeFi-addWhitelistedRecipientOn}.
*/
event WhitelistedRecipientSetOn(uint256 indexed id, uint256 chainId, bytes32 recipient);
event WhitelistedRecipientsRemoved(uint256[] ids);
event WhitelistedRecipientRemovalQueued(uint256 indexed id, uint64 effectiveAt);
event AssetsUpdated(address[] addAssets, address[] removeAssets);
event ProtocolsUpdated(address[] addProtocols, address[] removeProtocols);
/**
* @notice The vault switched which allow list gates it: Bitty's catalogue (`ownAllowList` false) or
* its own list on top of it (true). Takes effect at once.
*/
event OwnAllowListSet(bool ownAllowList);
/**
* @notice The auto-yield route for `asset` now deposits into `protocol`; zero clears it.
*/
event AutoYieldingSet(address indexed asset, address protocol);
event RiskSettingsUpdated(RiskSettings riskSettings);
event WhitelistedRecipientPaid(uint256 indexed id, address recipient, address asset, uint256 amount);
event Retrieved721(address indexed contractAddress, uint256 indexed tokenId, address indexed to);
event TokenAsGasSet(bool enabled, address[] assets, uint64 dailyLimit);
event ActivationFeePaid(address indexed asset, uint256 amount);
event RelayerFeePaid(address indexed asset, uint256 amount, uint256 spentToday, uint256 remainingToday);
event LockLevelSet(uint8 level, uint64 closedEpoch);
event OwnershipTransferQueued(address indexed newOwner, uint64 readyAt);
event OwnershipTransferCancelled(address indexed newOwner);
/**
* @notice Update the assets.
* @param addAssets The assets to add.
* @param removeAssets The assets to remove.
*/
function updateAssets(address[] memory addAssets, address[] memory removeAssets) external;
/**
* @notice Update the protocols.
* @param addProtocols The protocols to add.
* @param removeProtocols The protocols to remove.
*/
function updateProtocols(address[] memory addProtocols, address[] memory removeProtocols) external;
/**
* @notice Set the token-as-gas settings.
* @param assets The assets that may pay for relayed gas: stablecoins and/or the vault's WETH.
* @param dailyLimit The daily limit for token-as-gas operations, in whole USD.
*/
function setTokenAsGas(address[] calldata assets, uint64 dailyLimit) external;
/**
* @notice Disable token-as-gas operations.
*/
function disableTokenAsGas() external;
/**
* @notice Set the auto yieldings.
* @param routes The auto yieldings to set.
*/
function setAutoYieldings(AutoYield[] calldata routes) external;
/**
* @notice Set any of the vault's wait, its regular-send daily allowance and its daily loss
* allowance.
* @dev Reverts {RiskTimelockTooLong} for a timelock above 30 days, and
* {RiskAllowanceOutOfRange} for an allowance above its ceiling. An allowance of
* `type(uint64).max - 1` is no limit: for sends, any asset, uncapped; for losses, trades and
* bridges unpriced. Under either lock only the
* daily loss allowance may change, and only downward; anything else
* reverts {VaultLocked}.
* @param riskSettings The three numbers, with `type(uint256).max` in any to leave it alone.
*/
function updateRisk(RiskSettings calldata riskSettings) external;
/**
* @notice Send an ERC-721 token to a whitelisted recipient. An NFT cannot be valued, so it cannot
* be metered by the send allowance; it leaves only the way unmetered value does. Allowed
* under either lock.
* @dev Reverts as a payout to the recipient would: {WhitelistedRecipientNotFound},
* {ProtectionPeriodNotEnded} before it matures, {VaultLocked} for one a lock voided.
* @param contractAddress The address of the ERC-721 contract.
* @param tokenId The token ID to send.
* @param recipientId The id of the whitelisted recipient to send it to.
*/
function retrieve721(address contractAddress, uint256 tokenId, uint256 recipientId) external;
/**
* @notice Send to a whitelisted recipient.
* @param id The id of the whitelisted recipient.
* @param asset The asset to send.
* @param amount The amount to send.
* @param withdrawProtocols The withdrawable protocols to use.
* @param withdrawAmounts The amounts to withdraw from the withdrawable protocols.
*/
function sendToWhitelistedRecipient(
uint256 id,
address asset,
uint256 amount,
address[] calldata withdrawProtocols,
uint256[] calldata withdrawAmounts
) external;
/**
* @notice Set the auto yielding for an asset.
* @param route The auto yielding route.
*/
function setAutoYielding(AutoYield calldata route) external;
}
src/interfaces/IBittyV1Vault.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
error AddressZero();
error NotRegistered();
error Deprecated();
error AmountIsZero();
error ArrayLengthMismatch();
error EmptyArray();
error TransferFailed();
error NotInitialized();
error AlreadyInitialized();
error InsufficientBalance();
error ReentrantCall();
error ProtectionPeriodNotEnded();
error RiskTimelockTooLong();
error RiskTimelockTooShort();
error TimelockNeedsLimits();
error RiskAllowanceOutOfRange();
error OwnershipNotRenounceable();
error NoPendingOwnershipTransfer();
error ImplementationNotRegistered();
error VaultNotNewer();
error NotTrustedForwarder();
error GasBudgetExceeded();
error GasBudgetTooHigh();
error InvalidRelayedCalldata();
error InvalidAsset();
error PaymentExceedsRiskCap();
error PaymentExceedsPeriodLimit();
error PaymentNotStableCoin();
error WhitelistedRecipientNotFound();
error WhitelistedRecipientWrongChain();
error WhitelistedRecipientIsVault();
error RecipientNotAnAddress();
error NoEscapeRecipient();
error VaultLocked();
struct AutoYield {
address asset;
address protocol;
}
/**
* @title IBittyV1Vault
* @dev There are 3 principles for Bitty Vault design:
* 1. Each operation that make vault risk more, need timelock.
* 2. Each operation that make vault risk less, take effect immediately.
* 3. Even the owner private key got compromised, the timelock will make the lost in control.
*/
struct PendingChanges {
uint8 lockLevel; // 0 unlocked, 1 emergency locked, 2 locked for ever.
address newOwner;
uint64 newOwnerReadyAt;
address newAssetManager;
uint64 newAssetManagerAt;
uint32 newAssetManagerPerms;
uint64 timelock;
uint64 timelockAt;
uint64 sendDailyAllowance;
uint64 sendDailyAllowanceAt;
uint64 dailyLossAllowance;
uint64 dailyLossAllowanceAt;
uint64 gasBudgetDaily;
uint64 gasBudgetDailyAt;
uint64 bridgeEnableAt;
}
uint8 constant WHITELIST_REMOVED = 0; // gone, or never issued
uint8 constant WHITELIST_PENDING = 1; // still waiting out the timelock it was added under
uint8 constant WHITELIST_PAYABLE = 2; // can be paid now, lock or no lock
uint8 constant WHITELIST_VOIDED = 3; // a lock landed before it matured, so it never will
uint8 constant WHITELIST_REMOVAL_QUEUED = 4; // payable until `removeAt`, then gone
/**
* One whitelisted recipient as the contract sees it, so a client reads the list - the vault's way
* out after a key leaks - straight from state instead of rebuilding it from events.
*/
struct WhitelistEntryView {
uint256 id;
/**
* Zero once removed.
*/
address recipient;
/**
* When it became, or becomes, payable; 0 if it was payable from the start.
*/
uint64 effectiveAt;
/**
* When a queued removal lands; 0 if none is waiting.
*/
uint64 removeAt;
/**
* One of the WHITELIST_* constants above, worked out with the same lock rules a payout uses.
*/
uint8 status;
/**
* The chain the recipient is on: 0 for this chain, type(uint256).max for every EVM chain,
* otherwise its chain id (TRON is 728126428, with the address as its 20 bytes).
*/
uint256 chainId;
/**
* The recipient's address on its chain as 32 bytes: a 20-byte address (EVM, TRON) left-padded,
* a Solana address in full. For a Solana entry {recipient} is only its low 20 bytes.
*/
bytes32 account;
}
interface IBittyV1Vault {
/**
* @notice Returns the vault lock level: 0 unlocked, 1 emergency locked, 2 locked forever.
*/
function lockLevel() external view returns (uint8);
/**
* @notice Returns all changes waiting to take effect.
*/
function pendingChanges() external view returns (PendingChanges memory changes);
/**
* @notice The whitelisted recipients, read from state: ids `fromId` up to `fromId + count`, cut
* off at the last id issued. `getWhitelist(1, type(uint256).max)` returns the whole list.
* @dev Ids are issued in order from 1 and never reused, so a removed entry stays in the range
* with {WHITELIST_REMOVED}. Each entry costs a few storage reads, which is why the range can
* be narrowed: a list an attacker has flooded can still be read a page at a time.
* @param fromId The first id to return.
* @param count How many ids to return at most.
* @return lastId The highest id ever issued: the end of the list.
* @return entries One per id in the range, in order.
*/
function getWhitelist(uint256 fromId, uint256 count)
external
view
returns (uint256 lastId, WhitelistEntryView[] memory entries);
/**
* @notice The vault's WETH address.
*/
function gasWrappedAddress() external view returns (address);
/**
* @notice Get the auto yieldings.
* @param assetAddresses The addresses of the assets to get the auto yieldings for.
* @return protocols The protocols for the assets.
*/
function getAutoYieldings(address[] calldata assetAddresses) external view returns (address[] memory protocols);
/**
* @notice Get the address, besides the owner, allowed to trigger an auto yield sweep.
* @return trigger The trigger, or the zero address if only the owner may sweep.
*/
function autoYieldTrigger() external view returns (address trigger);
/**
* @notice The vault's trading delegate, and anything queued behind the change timelock.
* @return manager The asset manager, or the zero address if the owner alone may trade.
* @return expiresAt When the grant lapses, or 0 if there is no manager.
* @return pendingManager A manager waiting out the timelock, or zero if nothing is queued.
* @return pendingAt When that queued grant takes effect; 0 = nothing queued.
* @return permissions The effective grant's permission mask, or 0 if no manager is active.
* @return pendingPermissions The queued grant's permission mask, or 0 if nothing is queued.
*/
function getAssetManagerSettings()
external
view
returns (
address manager,
uint64 expiresAt,
address pendingManager,
uint64 pendingAt,
uint32 permissions,
uint32 pendingPermissions
);
/**
* @notice Is this asset allowed?
* @param asset The address of the asset to check.
* @return isAllowed Whether the asset is allowed.
*/
function isAssetAllowed(address asset) external view returns (bool);
/**
* @notice Is this protocol enabled on the vault?
* @param protocol The address of the protocol to check.
* @return isAllowed Whether the protocol is allowed.
*/
function isProtocolAllowed(address protocol) external view returns (bool);
/**
* @notice Get the vault's three risk numbers.
* @return timelock The one wait in front of everything deferred.
* @return sendDailyAllowance What may leave per day through regular sends, in whole USD; 0 when the owner
* has turned regular sends off.
* @return dailyLossAllowance What market trades and bridges may lose against oracle value per
* day, in whole USD; 0 when the owner has turned them off.
*/
function riskSettings()
external
view
returns (uint64 timelock, uint64 sendDailyAllowance, uint64 dailyLossAllowance);
/**
* @notice Get what the vault holds in withdrawable protocols.
* @dev One getter for every protocol the vault can exit, whatever it does with the asset while
* it holds it - lending, staking, or anything later that speaks the same interface.
* @param withdrawProtocols The protocols to get the balances for, one per asset.
* @param assetAddresses The addresses of the assets to get the balances for.
* @return balances The balances.
*/
function getBalances(address[] calldata withdrawProtocols, address[] calldata assetAddresses)
external
view
returns (uint256[] memory balances);
/**
* @notice Get the withdrawals awaiting a claim.
* @dev Empty for protocols that settle {IBittyV1DeFi-withdraw} in the same call.
* @param withdrawProtocol The protocol to get the pending withdrawal ids for.
* @return ids The pending withdrawal ids.
*/
function getPendingWithdrawalIds(address withdrawProtocol) external view returns (uint256[] memory ids);
/**
* @notice Auto yield the assets.
* @param assets The addresses of the assets to auto yield.
* @param amounts How much of each to deposit, capped at its free balance.
*/
function autoYields(address[] calldata assets, uint256[] calldata amounts) external;
/**
* @notice Wrap any native ETH the vault holds into WETH. receive() auto-wraps incoming ETH, but ETH
* that arrived before the vault was deployed (e.g. a deposit to the counterfactual address) sits
* as raw native ETH the vault's WETH-denominated ETH accounting can't spend; this converts it.
* Permissionless — it only moves the vault's own ETH into its own WETH.
*/
function wrapNative() external;
/**
* @notice The trusted ERC-2771 forwarder for this vault.
* @dev The compile-time constant {BITTY_FORWARDER}: never zero, with no setter and nothing in
* storage, so neither an owner nor a compromised relayer can repoint it. Relaying cannot be
* switched off; what a relayed call may charge the vault is switched off with
* {disableTokenAsGas}. A new forwarder ships with a new vault implementation.
*/
function trustedForwarder() external view returns (address);
/**
* @notice What the forwarder may still reclaim from this vault today, as an 18-decimal
* USD value. Resets at 00:00 UTC.
* @dev Read before relaying: exceeding the ceiling reverts the whole relayed call, so the caller
* should fall back to paying its own gas rather than submit and lose it.
*/
function gasBudgetRemaining() external view returns (uint256);
/**
* @notice A relayer fee as the vault will count it against its ceilings: an 18-decimal USD value,
* rounded up. A stablecoin is a dollar; the vault's WETH is priced off the guard's feed.
* @dev Reverts where {payRelayerFee} would on price: a stale feed or a down L2 sequencer.
*/
function relayerFeeValue(address asset, uint256 amount) external view returns (uint256);
/**
* @notice The terms on which this vault will pay for relayed gas.
* @dev One call rather than three, since no caller wants a subset. Deliberately does NOT repeat
* {gasBudgetRemaining} — that is live state with its own getter, read on-chain by the
* forwarder — nor an `enabled` flag, which `dailyLimit` already carries.
* @return assets The assets the owner listed to pay for relayed gas. Activation lists nothing,
* and EMPTY means ANY may pay: every guard-registered stable coin and the vault's WETH.
* A non-empty list narrows that to the assets on it.
* @return dailyLimit Per-UTC-day ceiling in whole USD, as in force. ZERO means charging is off
* ({disableTokenAsGas}). Otherwise it is the owner's figure, or {SYSTEM_DAILY_MAX_GAS_BUDGET}
* while the owner has set none — so a vault charges for relayed gas from activation, up
* to that ceiling, until its owner narrows or disables it.
*/
function tokenAsGasConfig() external view returns (address[] memory assets, uint256 dailyLimit);
/**
* @notice Reimburse the trusted forwarder, in a stablecoin or the vault's WETH, for gas it fronted for this vault.
* @dev Callable by the forwarder and ONLY while it is settling a fee for this vault — it must be
* inside its own charge window (see {IBittyV1Forwarder}). Being the forwarder is not enough:
* every relayed call has the forwarder as `msg.sender`, so that test alone let a relayed
* `multicall([payRelayerFee])` signed by any key charge the budget.
*
* Not subject to the payment-risk controls: this is the vault settling its own gas bill, and
* an owner able to block it with sendDailyAllowance = 0 would just be relaying for free. The daily
* budget and per-charge ceiling are the controls that apply instead.
* @param asset The asset to use for the relayer fee.
* @param amount The amount to reclaim, in `asset` units. The payee is vault config, not an
* argument.
*/
function payRelayerFee(address asset, uint256 amount) external;
/**
* @notice Auto yield an asset.
* @param asset The address of the asset to auto yield.
* @param amount How much to deposit, capped at the free balance; the rest stays, e.g. as a fee float.
*/
function autoYield(address asset, uint256 amount) external;
/**
* @notice Name the address, besides the owner, that may trigger an auto yield sweep.
* @param trigger The trigger to name. The zero address clears it, leaving the owner alone.
*/
function setAutoYieldTrigger(address trigger) external;
/**
* @notice Name the address, besides the owner, that may trade this vault. Zero revokes.
* @dev The manager may do what its permissions name — supply and withdraw from lending, stake and
* unstake, trade at market, sign and cancel intent orders — but cannot change which assets or
* protocols are reachable, cannot re-route auto-yield, and cannot pay anyone, so daily DeFi
* work no longer needs the key that can move money out. Appointing or extending waits out the
* vault's change timelock; revoking and shortening apply at once. Under either lock the grant
* can not be changed and is kept but dormant: the manager can do nothing until an emergency
* lock is released, and nothing ever again under a forever lock.
* @param assetManager The trading delegate, or zero to revoke.
* @param expiresAt When the grant lapses: in the future and within {MAX_GRANT_DURATION}, since every
* grant expires. Ignored on a revoke.
* @param permissions What the grant covers, as the bit set in {Constants}. There is no
* "everything" and no default. Taking a position out needs the bit that put it in —
* {PERM_SUPPLY} for lending, {PERM_YIELD} for staking — and cancelling an intent order
* needs {PERM_INTENT}, so a grant to trade at market alone reaches no position.
*/
function setAssetManager(address assetManager, uint64 expiresAt, uint32 permissions) external;
/**
* @notice Emergency lock the vault.
*/
function emergencyLock() external;
/**
* @notice Unlock the vault.
*/
function unlock() external;
/**
* @notice Forever lock the vault.
* @dev Once engaged nothing can be added, so the only way money ever leaves again is a whitelisted
* recipient the owner already had. The owner names one, and the lock refuses with
* {NoEscapeRecipient} unless it can be paid right now: it exists, its window has run, no lock
* voided it and no removal of it has landed. The vault's own address is refused too, since
* paying it moves nothing. A removal still waiting is voided by the lock.
* @param escapeRecipientId A whitelisted recipient the vault can pay out to after the lock.
*/
function foreverLock(uint256 escapeRecipientId) external;
/**
* @notice Cancel the ownership transfer.
*/
function cancelOwnershipTransfer() external;
}
src/logic/BittyStorage.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {IBittyV1Vault} from "../interfaces/IBittyV1Vault.sol";
/**
* @title BittyStorage
* @notice ERC-7201 namespaced storage. Two independent contexts, each pinned to a fixed keccak-derived
* slot so the layout survives UUPS upgrades.
*
* @dev Slots derived as `keccak256(abi.encode(uint256(keccak256(id)) - 1)) & ~0xff`:
* - bitty.storage.vault.main → VAULT_SLOT
* - bitty.storage.vault.defi → DEFI_SLOT
*
* The ids carry NO version, and that is the point. An id is not a label for a release — it is the
* address of the data. `keccak256("bitty.storage.vault.main")` is what produces VAULT_SLOT, so
* changing a single character of it moves the root: an upgraded implementation would find
* untouched zeros at the new slot and report every vault as uninitialised, while the real state
* sat intact at the old one with nothing left that knew its number.
*
* So these three strings must survive every future version of this contract. v1.1, v2, whatever
* comes — same address, same data, same ids. The only reason to mint a new id is to open a
* deliberately separate region, which is a new deployment rather than an upgrade; migrating in
* place would mean carrying the second namespace ALONGSIDE the first and copying between them,
* never renaming this one.
*
* ── BEFORE SHIPPING AN UPGRADE, CHECK EVERY STRUCT IN THIS FILE ──────────────────────────────
*
* These rules bind from the first vault that holds somebody else's money, and NOT YET. There
* are no `__deprecated` placeholders in this file, and that is deliberate rather than an
* oversight: retired fields have been deleted outright while the only vaults in existence hold
* team funds that can be moved by hand. The cost is that a vault deployed on an earlier layout
* can no longer be upgraded onto this code — it would read the wrong slots, silently — which is
* a trade worth making exactly once, before launch.
*
* After that the rules below are absolute, and deleting from the middle of a struct stops being
* tidying and becomes the silent corruption described above. Do not read the absence of
* placeholders here as a precedent.
*
* An upgrade replaces the code and keeps the storage. Nothing on chain records what the old
* layout was, so the new implementation is simply believed: get a field's position wrong and it
* reads a neighbour's bytes as its own. No revert, no event, no way back except another upgrade —
* and by then the wrong values have already been written.
*
* Safe:
* - APPEND a field to the end of a struct. It lands on slots that were untouched zeros.
* - REMOVE the last field. Nothing below it shifts; the slot goes unread.
* - Rename a field or a Solidity identifier. Names are compile-time only.
*
* Never, on a struct that already holds live data:
* - Insert or reorder a field. Everything after it shifts by a slot.
* - Delete from the middle. Same shift, and silent.
* - Change a type where it alters packing (uint64 → uint128 can repack the whole slot, and a
* value type ↔ mapping is a different thing entirely).
*
* Which structs this applies to is the part that is easy to get wrong, so each is marked below.
* It is NOT only the three namespace roots: a struct used as a mapping VALUE is just as pinned,
* because its fields sit at consecutive slots from `keccak256(key . position)`. Those are the
* dangerous ones — nothing next to them says `$.slot :=` to remind you.
*
* The mapping values here are {Deferred} and {WhitelistEntry}: each is pinned as above, by
* being the value of a mapping in {VaultStorage}.
*/
struct TimelockedValue {
uint64 value;
uint64 pending;
uint64 pendingAt;
}
struct Deferred {
uint64 effectiveAt;
uint32 lockEpoch;
}
struct WhitelistEntry {
address recipient;
uint64 removeAt;
uint32 removeEpoch;
}
struct RiskConfig {
TimelockedValue timelock;
TimelockedValue sendDailyAllowance;
TimelockedValue dailyLossAllowance;
}
struct ProtocolInstance {
address clone;
uint32 version;
}
struct DeFiStorage {
mapping(bytes32 => ProtocolInstance) clonedProtocols;
mapping(address => address) autoYieldProtocols;
mapping(address => bool) assets;
mapping(address => bool) protocols;
address autoYieldTrigger;
address assetManager;
uint48 assetManagerExpiresAt;
uint32 assetManagerPerms;
bool hasPendingAssetManager;
address pendingAssetManager;
uint48 pendingAssetManagerAt;
uint48 pendingAssetManagerExpiresAt;
uint32 pendingAssetManagerPerms;
mapping(address => mapping(address => uint32)) receiptTokenApproved; // clone => asset => the {ProtocolInstance.version}
TimelockedValue bridgeDisabled;
}
struct VaultStorage {
address gasWrapped;
bool isInitialized;
bool ownAllowListActive;
/**
* Set by {PaymentLogic.initialize} on a vault created from 1.0.10 on: an allowance it has
* never set reads as the new-vault default (sends off, the default trade loss allowance) rather
* than as the ceiling, so neither has to be written at creation. False on every vault created before 1.0.10,
* whose unset allowances keep reading as the ceiling. Packed into the slot initialize writes
* anyway, in bytes no older version used.
*/
bool unsetRiskIsDefault;
bool unsetIsOpen; // set at initialize from 1.1.1: an unset timelock reads 0, an unset allowance no limit
mapping(uint256 => Deferred) whitelistedRecipientDeferred;
mapping(uint256 => WhitelistEntry) whitelistedRecipient;
RiskConfig riskConfig;
uint256 nextWhitelistedRecipientId;
uint64 ownerSendPeriodStart;
uint128 ownerSentInPeriod;
uint128 lossInPeriod;
uint64 lossPeriodStart;
TimelockedValue gasBudgetDaily;
TimelockedValue unusedMaxFeePerOp; // the per-op fee cap, removed in 1.1.1; kept for the layout
uint96 gasSpentToday;
uint64 gasBudgetDay;
bool tokenAsGasDisabled;
mapping(address => address) tokenAsGasAssets;
uint8 lockLevel; // 0 none, 1 emergency (releasable), 2 forever. See {LockLib}.
uint32 lockEpoch;
uint40 ownershipReadyAt;
address vaultOwner;
mapping(uint32 => uint64) lockEpochClosedAt;
address pendingOwner;
/**
* The chain a whitelisted recipient is on, by id; 0, as every entry made before 1.2.0 reads,
* for this chain. Another chain's recipient is paid only by a bridge
* ({IBittyV1DeFi-bridgeToWhitelistedRecipient}), never by a payout here.
*/
mapping(uint256 => uint256) whitelistedRecipientChain;
/**
* A whitelisted recipient's full 32-byte address on a chain whose addresses do not fit 20
* bytes (Solana), by id; zero for every other entry, whose address is its
* {WhitelistEntry.recipient}. Such an entry's {WhitelistEntry.recipient} holds the low 20
* bytes, so the list reads it as present.
*/
mapping(uint256 => bytes32) whitelistedRecipientAccount;
}
library BittyStorage {
bytes32 internal constant VAULT_SLOT = 0x17e3e73c9899a2a21e7ae5b2fc286a77d4903c0979f27baf0730ce5db138e400;
bytes32 internal constant DEFI_SLOT = 0xfcb7e45a818f0ecef03db92f5b6e7b2ed559effd8e9a1c8a33ce82a8fa3b9400;
function vault() internal pure returns (VaultStorage storage $) {
assembly {
$.slot := VAULT_SLOT
}
}
function defi() internal pure returns (DeFiStorage storage $) {
assembly {
$.slot := DEFI_SLOT
}
}
}
src/logic/Constants.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
address constant BITTY_GUARD = 0x000000000F5fcD35885BfE4c700042cE7cb39554;
address constant BITTY_FORWARDER = 0xD6013C5e339cd3546c0c7E86c306554a63FbAa6F;
// Vault owned by the Safe (0x5837C8F4963F694C59e53445C070acb266187bF1)
address constant BITTY_FEE_COLLECTOR = 0xF0E7f6998B362BD15CF819C7EBfcaCe8865FECA0;
address constant BITTY_VAULT_BOOTSTRAP = 0x06dBcce6A83230B1Ea281F449f960c8F7124cc72;
address constant BITTY_VAULT_FACTORY_BOOTSTRAP = 0x2287De18768eD5eC5F75Ed5d0B7e371809Fa653f;
uint64 constant MAX_RISK_TIMELOCK = 30 days;
// The shortest timelock above 0, and what an unset one reads as on a vault created before 1.1.1.
uint64 constant MIN_RISK_TIMELOCK = 1 days;
uint64 constant MAX_DAILY_ALLOWANCE = 1_000_000;
// What an unset allowance reads as on a vault created before 1.0.10.
uint64 constant LEGACY_DAILY_ALLOWANCE = 10_000;
// What a new vault starts with: a starting value, not a floor — the owner may lower it at once, to 0.
uint64 constant DEFAULT_DAILY_LOSS_ALLOWANCE = 1_000;
// How a timelock or an allowance of 0 is stored: a stored 0 already means "never set".
uint64 constant STORED_ZERO = type(uint64).max;
// An allowance of no limit: sends of any asset and amount, trades unpriced. Above every cap, so moving to it loosens.
uint64 constant NO_LIMIT = type(uint64).max - 1;
uint64 constant MAX_GRANT_DURATION = 365 days;
uint64 constant SYSTEM_DAILY_MAX_GAS_BUDGET = 100;
address constant SENTINEL = address(0x1);
uint256 constant SEQUENCER_GRACE_PERIOD = 1 hours; // L2 sequencer grace period
uint256 constant MAX_MARKET_TRADE_SLIPPAGE_BPS = 500; // 5%
uint32 constant PERM_YIELD = 1 << 0;
uint32 constant PERM_SUPPLY = 1 << 1;
uint32 constant PERM_MARKET_TRADE = 1 << 2;
uint32 constant PERM_INTENT = 1 << 3;
uint8 constant ASSET_BRIDGEABLE = 8;
uint8 constant PROTOCOL_BRIDGE = 5;
// A whitelisted recipient's chain meaning every EVM chain: the same address here and on any chain a
// bridge route in the guard reaches. See {IBittyV1DeFi-addWhitelistedRecipientOn}.
uint256 constant ANY_EVM_CHAIN = type(uint256).max;
// The guard config key that marks `chainId` as an EVM chain (value 1), where an {ANY_EVM_CHAIN}
// recipient's address is the same holder's: keccak256(abi.encode(EVM_CHAIN_KEY, chainId)). A
// chain the guard has not marked is not one, so a new EVM chain needs only the guard's word, and
// TRON or Solana, never marked, are never sent an EVM recipient's money.
bytes32 constant EVM_CHAIN_KEY = keccak256("bitty.chain.evm");
src/logic/DeFiLogic.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {ERC1967Proxy} from "openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol";
import {UUPSUpgradeable} from "openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol";
import {IBittyV1Guard, ASSET_STABLE_COIN, PROTOCOL_INTENT} from "guard-contracts/src/interfaces/IBittyV1Guard.sol";
import {IBittyV1Yield} from "protocol-contracts/src/interfaces/IBittyV1Yield.sol";
import {IBittyV1Protocol} from "protocol-contracts/src/interfaces/IBittyV1Protocol.sol";
import {IBittyV1IntentProtocol} from "protocol-contracts/src/interfaces/IBittyV1IntentProtocol.sol";
import {
InvalidDepositableProtocol,
InvalidWithdrawableProtocol,
InvalidIntentProtocol,
ProtocolNotInstantiated,
ProtocolLineageMismatch,
ProtocolNotNewer,
AssetManagerExpiryInPast,
GrantTooLong
} from "../interfaces/IBittyV1DeFi.sol";
import {SafeERC20} from "openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import {
AddressZero,
AmountIsZero,
NotInitialized,
ArrayLengthMismatch,
AutoYield,
NotRegistered,
Deprecated
} from "../interfaces/IBittyV1Vault.sol";
import {BittyStorage, DeFiStorage, ProtocolInstance} from "./BittyStorage.sol";
import {IBittyV1Owner} from "../interfaces/IBittyV1Owner.sol";
import {RiskLogic} from "./RiskLogic.sol";
import {LockLib} from "./LockLib.sol";
import {BITTY_GUARD, MAX_GRANT_DURATION} from "./Constants.sol";
/**
* @title DeFiLogic
* @notice The full DeFi surface — yield (deposit/withdraw/auto-yield), market making, market trading
* and intent orders
* — run in the vault's context. Operates on the co-located {DeFiStorage} at the ERC-7201
* DEFI_SLOT.
*
* @dev Guard-driven. The local allowlist is consulted only while it is active (the owner's switch,
* which takes effect at once, and is frozen under a lock): an asset/protocol must then be both guard-registered and locally
* allowed. This library stores the asset-manager grant and answers who holds it, but
* does not authorise calls — that is the facet's job ({BittyV1VaultDeFiFacet}).
*/
library DeFiLogic {
event AutoYieldTriggerSet(address indexed trigger);
event AssetManagerSet(address indexed assetManager, uint64 expiresAt);
event AssetManagerPending(address indexed assetManager, uint64 expiresAt, uint64 effectiveAt);
event AssetManagerPermissionsSet(address indexed assetManager, uint32 permissions);
using SafeERC20 for IERC20;
function listInitialAsset(address asset) external {
DeFiStorage storage $ = BittyStorage.defi();
if (asset == address(0) || $.assets[asset]) return;
(bool ok, bytes memory data) = BITTY_GUARD.staticcall(abi.encodeCall(IBittyV1Guard.isAssetRegistered, (asset)));
if (!ok || data.length < 32 || !abi.decode(data, (bool))) return;
$.assets[asset] = true;
}
function _onlyInitialized() internal view {
if (!BittyStorage.vault().isInitialized) revert NotInitialized();
}
function activateOwnAllowList() external {
_onlyInitialized();
BittyStorage.vault().ownAllowListActive = true;
emit IBittyV1Owner.OwnAllowListSet(true);
}
function deactivateOwnAllowList() external {
_onlyInitialized();
BittyStorage.vault().ownAllowListActive = false;
emit IBittyV1Owner.OwnAllowListSet(false);
}
function ownAllowListActive() external view returns (bool) {
return BittyStorage.vault().ownAllowListActive;
}
function setAutoYieldTrigger(address trigger) external {
DeFiStorage storage $ = BittyStorage.defi();
_onlyInitialized();
$.autoYieldTrigger = trigger;
emit AutoYieldTriggerSet(trigger);
}
function autoYieldTrigger() external view returns (address) {
return BittyStorage.defi().autoYieldTrigger;
}
/**
* @dev Every grant expires: `expiresAt` must be in the future (0 is in the past, so it is refused
* as one) and within {MAX_GRANT_DURATION}. A revoke ignores it.
*/
function setAssetManager(address assetManager, uint64 expiresAt, uint32 permissions) external {
DeFiStorage storage $ = BittyStorage.defi();
_onlyInitialized();
_settleAssetManager($);
if (assetManager == address(0)) {
delete $.assetManager;
delete $.assetManagerExpiresAt;
delete $.assetManagerPerms;
_clearPendingAssetManager($);
emit AssetManagerSet(address(0), 0);
return;
}
if (expiresAt <= block.timestamp) revert AssetManagerExpiryInPast();
if (expiresAt > block.timestamp + MAX_GRANT_DURATION) revert GrantTooLong();
bool sameManager = assetManager == $.assetManager;
bool noLaterExpiry = expiresAt <= $.assetManagerExpiresAt;
bool noNewPermission = permissions & ~$.assetManagerPerms == 0;
bool tightening = sameManager && noLaterExpiry && noNewPermission;
uint64 timelock = RiskLogic.effectiveTimelock(BittyStorage.vault());
if (tightening) {
$.assetManager = assetManager;
$.assetManagerExpiresAt = uint48(expiresAt);
$.assetManagerPerms = permissions;
_clearPendingAssetManager($);
emit AssetManagerSet(assetManager, expiresAt);
emit AssetManagerPermissionsSet(assetManager, permissions);
return;
}
$.pendingAssetManager = assetManager;
$.pendingAssetManagerExpiresAt = uint48(expiresAt);
$.pendingAssetManagerPerms = permissions;
$.pendingAssetManagerAt = uint48(uint64(block.timestamp) + timelock);
$.hasPendingAssetManager = true;
emit AssetManagerPending(assetManager, expiresAt, $.pendingAssetManagerAt);
}
function _settleAssetManager(DeFiStorage storage $) private {
if (!$.hasPendingAssetManager) return;
if (block.timestamp >= $.pendingAssetManagerAt) {
$.assetManager = $.pendingAssetManager;
$.assetManagerExpiresAt = $.pendingAssetManagerExpiresAt;
$.assetManagerPerms = $.pendingAssetManagerPerms;
_clearPendingAssetManager($);
}
}
function _clearPendingAssetManager(DeFiStorage storage $) private {
delete $.pendingAssetManager;
delete $.pendingAssetManagerExpiresAt;
delete $.pendingAssetManagerPerms;
delete $.pendingAssetManagerAt;
delete $.hasPendingAssetManager;
}
function _liveGrant(DeFiStorage storage $)
private
view
returns (address manager, uint64 expiresAt, uint32 permissions)
{
if ($.hasPendingAssetManager && block.timestamp >= $.pendingAssetManagerAt) {
return ($.pendingAssetManager, $.pendingAssetManagerExpiresAt, $.pendingAssetManagerPerms);
}
return ($.assetManager, $.assetManagerExpiresAt, $.assetManagerPerms);
}
function getAssetManagerSettings()
external
view
returns (
address manager,
uint64 expiresAt,
address pendingManager,
uint64 pendingAt,
uint32 permissions,
uint32 pendingPermissions
)
{
DeFiStorage storage $ = BittyStorage.defi();
(manager, expiresAt, permissions) = _liveGrant($);
if (block.timestamp >= expiresAt) permissions = 0; // no manager reads as expiry 0
pendingManager = $.pendingAssetManager;
pendingAt = $.pendingAssetManagerAt;
pendingPermissions = $.hasPendingAssetManager ? $.pendingAssetManagerPerms : 0;
}
function _pendingAssetManagerGrant() internal view returns (address manager, uint64 at, uint32 permissions) {
DeFiStorage storage $ = BittyStorage.defi();
if (!$.hasPendingAssetManager) return (address(0), 0, 0);
return ($.pendingAssetManager, $.pendingAssetManagerAt, $.pendingAssetManagerPerms);
}
/**
* @dev False for everyone while the vault is locked, under either lock: the grant is kept but
* dormant, so the owner alone acts on a locked vault, and an emergency lock's release wakes it.
*/
function assetManagerCan(address account, uint32 permissions) external view returns (bool) {
if (account == address(0) || LockLib.level() != 0) return false;
(address manager, uint64 expiresAt, uint32 granted) = _liveGrant(BittyStorage.defi());
if (account != manager) return false;
if (block.timestamp >= expiresAt) return false;
return granted & permissions == permissions;
}
function upgradeProtocol(address protocol, address newImplementation) external {
DeFiStorage storage $ = BittyStorage.defi();
_onlyInitialized();
address instance = _instanceOf($, protocol);
if (instance == address(0)) revert ProtocolNotInstantiated();
if (!IBittyV1Guard(BITTY_GUARD).isProtocolRegistered(newImplementation)) revert NotRegistered();
bytes32 lineage = IBittyV1Protocol(instance).protocolLineage();
if (lineage == bytes32(0) || IBittyV1Protocol(newImplementation).protocolLineage() != lineage) {
revert ProtocolLineageMismatch();
}
if (IBittyV1Protocol(newImplementation).protocolVersion() <= IBittyV1Protocol(instance).protocolVersion()) {
revert ProtocolNotNewer();
}
UUPSUpgradeable(instance).upgradeToAndCall(newImplementation, "");
++$.clonedProtocols[lineage].version;
}
function updateAssets(address[] calldata addAssets, address[] calldata removeAssets) external {
DeFiStorage storage $ = BittyStorage.defi();
_onlyInitialized();
IBittyV1Guard guard = IBittyV1Guard(BITTY_GUARD);
for (uint256 i; i < addAssets.length; ++i) {
if (!guard.isAssetRegistered(addAssets[i])) revert NotRegistered();
$.assets[addAssets[i]] = true;
}
for (uint256 i; i < removeAssets.length; ++i) {
$.assets[removeAssets[i]] = false;
}
emit IBittyV1Owner.AssetsUpdated(addAssets, removeAssets);
}
function updateProtocols(address[] calldata addProtocols, address[] calldata removeProtocols) external {
DeFiStorage storage $ = BittyStorage.defi();
_onlyInitialized();
IBittyV1Guard guard = IBittyV1Guard(BITTY_GUARD);
for (uint256 i; i < removeProtocols.length; ++i) {
$.protocols[removeProtocols[i]] = false;
}
for (uint256 i; i < addProtocols.length; ++i) {
if (!guard.isProtocolRegistered(addProtocols[i])) revert NotRegistered();
$.protocols[addProtocols[i]] = true;
// Intent protocols must be cloned eagerly so off-chain isValidSignature has a signer.
if (guard.protocolCategory(addProtocols[i]) == PROTOCOL_INTENT) {
_cloneProtocol($, addProtocols[i]);
}
}
emit IBittyV1Owner.ProtocolsUpdated(addProtocols, removeProtocols);
}
function assetAllowed(address asset) external view returns (bool) {
DeFiStorage storage $ = BittyStorage.defi();
if (!IBittyV1Guard(BITTY_GUARD).isAssetRegistered(asset)) return false;
return !BittyStorage.vault().ownAllowListActive || $.assets[asset];
}
function stableCoinAllowed(address asset) external view returns (bool) {
DeFiStorage storage $ = BittyStorage.defi();
if ((IBittyV1Guard(BITTY_GUARD).assetCategory(asset) & ASSET_STABLE_COIN) == 0) return false;
if (!IBittyV1Guard(BITTY_GUARD).isAssetRegistered(asset)) return false;
return !BittyStorage.vault().ownAllowListActive || $.assets[asset];
}
/**
* Registered is enough: deprecating a protocol takes it out of the guard's registered set, so a
* deprecated one already fails here and a second guard call to ask would only cost gas.
*/
function _depositProtocolOK(DeFiStorage storage $, address protocol) private view returns (bool) {
if (!IBittyV1Guard(BITTY_GUARD).isProtocolRegistered(protocol)) return false;
return !BittyStorage.vault().ownAllowListActive || $.protocols[protocol];
}
function _categoryProtocolOK(DeFiStorage storage $, uint8 category, address protocol) private view returns (bool) {
if (IBittyV1Guard(BITTY_GUARD).protocolCategory(protocol) != category) return false;
return !BittyStorage.vault().ownAllowListActive || $.protocols[protocol];
}
function isProtocolAllowed(address protocol) external view returns (bool) {
DeFiStorage storage $ = BittyStorage.defi();
if (!IBittyV1Guard(BITTY_GUARD).isProtocolRegistered(protocol)) return false;
return !BittyStorage.vault().ownAllowListActive || $.protocols[protocol];
}
function deposit(address depositProtocol, address assetAddress, uint256 amount) external {
_deposit(BittyStorage.defi(), depositProtocol, assetAddress, amount);
}
function _deposit(DeFiStorage storage $, address depositProtocol, address assetAddress, uint256 amount) private {
_onlyInitialized();
if (!_depositProtocolOK($, depositProtocol)) revert InvalidDepositableProtocol();
if (assetAddress == address(0)) revert AddressZero();
if (amount == 0) revert AmountIsZero();
address clone = _cloneProtocol($, depositProtocol);
if (IERC20(assetAddress).allowance(address(this), clone) < amount) {
IERC20(assetAddress).forceApprove(clone, type(uint256).max);
}
IBittyV1Yield(clone).deposit(assetAddress, amount);
}
function withdraw(address withdrawProtocol, address assetAddress, uint256 amount, address recipient)
external
returns (uint256 delivered)
{
return _withdraw(BittyStorage.defi(), withdrawProtocol, assetAddress, amount, recipient);
}
function withdraws(
address[] calldata withdrawProtocols,
address[] calldata assetAddresses,
uint256[] calldata amounts,
address recipient
) external {
uint256 n = withdrawProtocols.length;
if (assetAddresses.length != n || amounts.length != n) revert ArrayLengthMismatch();
DeFiStorage storage $ = BittyStorage.defi();
for (uint256 i; i < n; ++i) {
_withdraw($, withdrawProtocols[i], assetAddresses[i], amounts[i], recipient);
}
}
function _withdraw(
DeFiStorage storage $,
address withdrawProtocol,
address assetAddress,
uint256 amount,
address recipient
) private returns (uint256 delivered) {
_onlyInitialized();
if (assetAddress == address(0)) revert AddressZero();
if (amount == 0) revert AmountIsZero();
ProtocolInstance memory instance = _instance($, withdrawProtocol);
address clone = instance.clone;
if (clone == address(0)) revert InvalidWithdrawableProtocol();
_approveReceiptToken($, instance, assetAddress); // no balance check to save gas
return IBittyV1Yield(clone).withdraw(assetAddress, amount, recipient);
}
function getBalances(address[] calldata withdrawProtocols, address[] calldata assetAddresses)
external
view
returns (uint256[] memory balances)
{
if (withdrawProtocols.length != assetAddresses.length) revert ArrayLengthMismatch();
DeFiStorage storage $ = BittyStorage.defi();
balances = new uint256[](withdrawProtocols.length);
for (uint256 i; i < withdrawProtocols.length; ++i) {
balances[i] = _getBalance($, withdrawProtocols[i], assetAddresses[i]);
}
}
function _getBalance(DeFiStorage storage $, address withdrawProtocol, address assetAddress)
private
view
returns (uint256)
{
if (assetAddress == address(0)) revert AddressZero();
address clone = _instanceOf($, withdrawProtocol);
if (clone == address(0)) return 0;
return IBittyV1Yield(clone).getBalance(assetAddress);
}
function getPendingWithdrawalIds(address withdrawProtocol) external view returns (uint256[] memory) {
address clone = _instanceOf(BittyStorage.defi(), withdrawProtocol);
if (clone == address(0)) return new uint256[](0);
return IBittyV1Yield(clone).getPendingWithdrawalIds();
}
function claimWithdrawals(address withdrawProtocol, uint256[] memory ids) external {
if (ids.length == 0) return;
address clone = _instanceOf(BittyStorage.defi(), withdrawProtocol);
if (clone == address(0)) revert InvalidWithdrawableProtocol();
IBittyV1Yield(clone).claimWithdrawals(ids);
}
function claimWithdrawalOne(address withdrawProtocol, uint256 id) external {
address clone = _instanceOf(BittyStorage.defi(), withdrawProtocol);
if (clone == address(0)) revert InvalidWithdrawableProtocol();
uint256[] memory ids = new uint256[](1);
ids[0] = id;
IBittyV1Yield(clone).claimWithdrawals(ids);
}
function setAutoYieldingOne(AutoYield calldata route) external {
_setAutoYielding(BittyStorage.defi(), route.asset, route.protocol);
}
function setAutoYieldings(AutoYield[] calldata routes) external {
DeFiStorage storage $ = BittyStorage.defi();
for (uint256 i; i < routes.length; ++i) {
_setAutoYielding($, routes[i].asset, routes[i].protocol);
}
}
function _setAutoYielding(DeFiStorage storage $, address assetAddress, address protocol) private {
_onlyInitialized();
if (assetAddress == address(0)) revert AddressZero();
if (protocol == address(0)) {
delete $.autoYieldProtocols[assetAddress];
} else {
if (!_depositProtocolOK($, protocol)) revert InvalidDepositableProtocol();
$.autoYieldProtocols[assetAddress] = protocol;
}
emit IBittyV1Owner.AutoYieldingSet(assetAddress, protocol);
}
function getAutoYieldings(address[] calldata assetAddresses) external view returns (address[] memory protocols) {
DeFiStorage storage $ = BittyStorage.defi();
protocols = new address[](assetAddresses.length);
for (uint256 i; i < assetAddresses.length; ++i) {
protocols[i] = $.autoYieldProtocols[assetAddresses[i]];
}
}
function autoYieldOne(address assetAddress, uint256 amount) external {
_autoYield(BittyStorage.defi(), assetAddress, amount);
}
function autoYield(address[] calldata assetAddresses, uint256[] calldata amounts) external {
if (assetAddresses.length != amounts.length) revert ArrayLengthMismatch();
DeFiStorage storage $ = BittyStorage.defi();
for (uint256 i; i < assetAddresses.length; ++i) {
_autoYield($, assetAddresses[i], amounts[i]);
}
}
/**
* @dev The caller names the amount so a fee float can stay behind; it is capped at the free
* balance rather than refused, because that moves between the keeper reading it and this.
*/
function _autoYield(DeFiStorage storage $, address assetAddress, uint256 amount) private {
_onlyInitialized();
address protocol = $.autoYieldProtocols[assetAddress];
if (protocol == address(0)) return;
if (assetAddress == address(0)) revert AddressZero();
uint256 balance = IERC20(assetAddress).balanceOf(address(this));
if (amount > balance) amount = balance;
if (amount == 0) return;
_deposit($, protocol, assetAddress, amount);
}
/**
* Intent protocols are driven through the clone alone, like yield: the vault approves whatever the
* clone names as its {IBittyV1IntentProtocol-spender} and asks the clone to cancel. Nothing here
* knows which intent protocol it is talking to.
*/
function approveIntentSpender(address intentProtocol, address token) external {
DeFiStorage storage $ = BittyStorage.defi();
if (!_categoryProtocolOK($, PROTOCOL_INTENT, intentProtocol)) revert InvalidIntentProtocol();
if (IBittyV1Guard(BITTY_GUARD).isProtocolDeprecated(intentProtocol)) revert Deprecated();
address spender = IBittyV1IntentProtocol(_cloneProtocol($, intentProtocol)).spender();
IERC20(token).forceApprove(spender, type(uint256).max);
}
/**
* @dev Deprecation does NOT block a cancel. The vault's isValidSignature keeps validating through a
* deprecated protocol's clone so its in-flight orders still settle; refusing to cancel them
* would leave orders that can fill but cannot be withdrawn.
*/
function cancelIntentOrders(address intentProtocol, bytes[] calldata orderIds) external {
DeFiStorage storage $ = BittyStorage.defi();
if (!_categoryProtocolOK($, PROTOCOL_INTENT, intentProtocol)) revert InvalidIntentProtocol();
IBittyV1IntentProtocol(_cloneProtocol($, intentProtocol)).cancelOrders(orderIds);
}
function getClone(address protocol) external view returns (address) {
return _instanceOf(BittyStorage.defi(), protocol);
}
function _lineageOf(address protocol) private view returns (bytes32 lineage) {
if (protocol == address(0)) return bytes32(0);
(bool ok, bytes memory data) =
protocol.staticcall(abi.encodeWithSelector(IBittyV1Protocol.protocolLineage.selector));
if (ok && data.length >= 32) lineage = abi.decode(data, (bytes32));
}
function _instanceOf(DeFiStorage storage $, address protocol) private view returns (address) {
return _instance($, protocol).clone;
}
function _instance(DeFiStorage storage $, address protocol) private view returns (ProtocolInstance memory) {
bytes32 lineage = _lineageOf(protocol);
if (lineage == bytes32(0)) return ProtocolInstance({clone: address(0), version: 0});
return $.clonedProtocols[lineage];
}
function _cloneProtocol(DeFiStorage storage $, address protocol) internal returns (address clone) {
bytes32 lineage = IBittyV1Protocol(protocol).protocolLineage();
if (lineage == bytes32(0)) revert ProtocolLineageMismatch();
clone = $.clonedProtocols[lineage].clone;
if (clone != address(0)) return clone;
clone = address(new ERC1967Proxy(protocol, abi.encodeCall(IBittyV1Protocol.initialize, (address(this)))));
$.clonedProtocols[lineage].clone = clone;
}
function _getReceiptToken(address protocol, address asset) private view returns (address) {
(bool ok, bytes memory data) = protocol.staticcall(abi.encodeWithSignature("receiptTokenOf(address)", asset));
if (ok && data.length >= 32) return abi.decode(data, (address));
return address(0);
}
/**
* Let the clone pull the receipt token it takes back on a withdrawal. Done once per clone version
* and asset, then remembered: asking the clone for the token and the token for an allowance costs
* three calls on every withdrawal otherwise. A clone upgrade moves the version, since a new
* adapter may name a different receipt token.
*/
function _approveReceiptToken(DeFiStorage storage $, ProtocolInstance memory instance, address asset) private {
uint32 approvedAt = instance.version + 1;
if ($.receiptTokenApproved[instance.clone][asset] == approvedAt) return;
address receiptToken = _getReceiptToken(instance.clone, asset);
if (receiptToken == address(0)) return;
if (IERC20(receiptToken).allowance(address(this), instance.clone) != type(uint256).max) {
IERC20(receiptToken).forceApprove(instance.clone, type(uint256).max);
}
$.receiptTokenApproved[instance.clone][asset] = approvedAt;
}
}
src/logic/LockLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {BittyStorage, VaultStorage, DeFiStorage} from "./BittyStorage.sol";
import {TimelockLib} from "./TimelockLib.sol";
import {IBittyV1Owner} from "../interfaces/IBittyV1Owner.sol";
import {VaultLocked} from "../interfaces/IBittyV1Vault.sol";
/**
* @title LockLib
* @notice The two locks, and the sweep that makes them worth engaging.
*
* A locked vault keeps its owner. That is the whole design: the key is assumed to leak, and the
* person it leaked from still needs to use their money afterwards, so a lock does not disable the
* key — it shrinks what any holder of it can reach down to the box the owner drew in advance. Money
* still leaves, but only to a destination vetted before the leak, or as a limit order or the owner's
* market sale that buys stablecoins for this vault — and that sale, like any market trade, may lose
* up to the daily loss allowance against oracle value, which is the one loss a held key keeps under
* a lock. Value may always come home. Nothing else about the configuration moves in EITHER
* direction, because taking away an option the owner still has is as much an attack as granting one
* they never did. The one exception is that loss allowance, which may be lowered, to 0 if need be, to
* cut what the key can still lose ({RiskLogic-updateRisk}).
*
* An emergency lock can be released and still lets the relayer take its fee. A forever lock can do
* neither. Apart from that the two permit exactly the same things, so there is one gate, not two.
*
* Both are instant. A lock that could be queued would be a lock the thief could cancel with the
* same key, and a release that had to be queued would leave the owner with no way to use their own
* vault for the length of the delay — which an attacker would simply wait out.
*
* ── the sweep ────────────────────────────────────────────────────────────────────────────────────
*
* A thief spends their protection window queueing: destinations, a manager grant, looser limits.
* The lock has to void all of it, and the size of "all of it" is the attacker's choice — nothing
* caps how many entries a key can create. Walking the queue would therefore be the vulnerability:
* queue past the block gas limit and the lock could never be engaged again, the owner's last
* control disabled by the thing it defends against.
*
* So {engage} writes two words and contains no loop at all. It closes the current risk epoch, noting
* the moment it did so, and starts a new one. Entries carry the epoch they were made in, and
* {honoured} reads an entry as valid only while its epoch is current or if it had already matured
* when that epoch closed. Nothing is deleted; the losers are unreachable, which is the same thing
* to an attacker and free to the vault. Because each closing time is kept per epoch, an entry swept
* once is swept for ever — a later lock cannot move a freeze line past its maturity and revive it.
*
* The same stamp voids a queued removal of a whitelisted recipient, which is how a lock keeps every
* destination the owner already had: the removal never takes effect, and the entry stays payable.
*
* The handful of pending values that live in fixed slots — the risk scalars, the gas budget, the
* manager grant — are cleared outright, since there is a fixed number of them. Clearing a
* {TimelockedValue}'s pending half keeps every tightening, which had applied immediately, and drops
* every loosening, which had not.
*
*/
library LockLib {
/**
* An epoch stamp meaning "this entry's verdict is final, and it is honoured".
*
* Once an entry has survived a lock — matured before its own epoch closed — nothing can change
* that: the closing time is written once and its maturity is in the past. Re-deriving it on every
* later use costs a cold read of {lockEpochClosedAt} for the life of the entry, so the first use
* that pays for the derivation records it here instead.
*
* Deliberately NOT the current epoch: re-stamping to {lockEpoch} goes stale again at the next
* lock, and the write would be paid once per lock rather than once per entry.
*/
uint32 internal constant SETTLED = type(uint32).max;
uint8 internal constant NONE = 0;
uint8 internal constant EMERGENCY = 1;
uint8 internal constant FOREVER = 2;
function level() internal view returns (uint8) {
return BittyStorage.vault().lockLevel;
}
function lockedForever() internal view returns (bool) {
return BittyStorage.vault().lockLevel == FOREVER;
}
function requireNotLocked() internal view {
if (BittyStorage.vault().lockLevel != NONE) revert VaultLocked();
}
function emergencyLock() internal {
VaultStorage storage $ = BittyStorage.vault();
if ($.lockLevel != NONE) revert VaultLocked();
_engage($, EMERGENCY);
}
function foreverLock() internal {
VaultStorage storage $ = BittyStorage.vault();
if ($.lockLevel == FOREVER) revert VaultLocked();
_engage($, FOREVER);
}
function unlock() internal {
VaultStorage storage $ = BittyStorage.vault();
if ($.lockLevel != EMERGENCY) revert VaultLocked();
$.lockLevel = NONE;
emit IBittyV1Owner.LockLevelSet(NONE, $.lockEpoch);
}
function _engage(VaultStorage storage $, uint8 next) private {
uint32 closing = $.lockEpoch;
$.lockEpochClosedAt[closing] = uint64(block.timestamp);
$.lockEpoch = closing + 1;
$.lockLevel = next;
TimelockLib.cancelPending($.riskConfig.timelock);
TimelockLib.cancelPending($.riskConfig.sendDailyAllowance);
TimelockLib.cancelPending($.riskConfig.dailyLossAllowance);
TimelockLib.cancelPending($.gasBudgetDaily);
uint40 readyAt = $.ownershipReadyAt;
if (readyAt != 0 && block.timestamp < readyAt) {
$.ownershipReadyAt = 0;
$.pendingOwner = address(0);
}
DeFiStorage storage d = BittyStorage.defi();
TimelockLib.cancelPending(d.bridgeDisabled);
if (d.hasPendingAssetManager) {
if (block.timestamp >= d.pendingAssetManagerAt) {
d.assetManager = d.pendingAssetManager;
d.assetManagerExpiresAt = d.pendingAssetManagerExpiresAt;
d.assetManagerPerms = d.pendingAssetManagerPerms;
}
d.pendingAssetManager = address(0);
d.pendingAssetManagerExpiresAt = 0;
d.pendingAssetManagerAt = 0;
d.pendingAssetManagerPerms = 0;
d.hasPendingAssetManager = false;
}
emit IBittyV1Owner.LockLevelSet(next, closing);
}
function lockEpoch() internal view returns (uint32) {
return BittyStorage.vault().lockEpoch;
}
function requireHonoured(uint32 entryEpoch, uint256 maturity) internal view returns (bool settle) {
VaultStorage storage $ = BittyStorage.vault();
if (entryEpoch == $.lockEpoch) return false; // may yet go stale; nothing final to record
if (entryEpoch == SETTLED) return false; // already recorded
if (maturity > $.lockEpochClosedAt[entryEpoch]) revert VaultLocked();
return true;
}
/**
* {requireHonoured} as a question rather than a gate: false for an entry a lock has voided.
* Says nothing about whether `maturity` has come — an entry of the current epoch is honoured
* however far off it is.
*/
function honoured(uint32 entryEpoch, uint256 maturity) internal view returns (bool) {
VaultStorage storage $ = BittyStorage.vault();
if (entryEpoch == SETTLED || entryEpoch == $.lockEpoch) return true;
return maturity <= $.lockEpochClosedAt[entryEpoch];
}
}
src/logic/MarketTradeLogic.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {
IBittyV1Guard,
MarketTradeInfo,
ASSET_AMM_LIQUID,
ASSET_STABLE_COIN,
PROTOCOL_MARKET_TRADE
} from "guard-contracts/src/interfaces/IBittyV1Guard.sol";
import {IBittyV1MarketTradeProtocol} from "protocol-contracts/src/interfaces/IBittyV1MarketTradeProtocol.sol";
import {SafeERC20} from "openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import {Math} from "openzeppelin-contracts/contracts/utils/math/Math.sol";
import {
InvalidMarketTradeProtocol,
MarketTradeNotSupported,
MarketTradePriceTooLow,
DailyLossAllowanceExceeded
} from "../interfaces/IBittyV1DeFi.sol";
import {Deprecated, NotRegistered, ReentrantCall, VaultLocked} from "../interfaces/IBittyV1Vault.sol";
import {BittyStorage, DeFiStorage, VaultStorage} from "./BittyStorage.sol";
import {DeFiLogic} from "./DeFiLogic.sol";
import {LockLib} from "./LockLib.sol";
import {PriceLib} from "./PriceLib.sol";
import {RiskLogic} from "./RiskLogic.sol";
import {BITTY_GUARD, MAX_MARKET_TRADE_SLIPPAGE_BPS, NO_LIMIT} from "./Constants.sol";
/**
* @dev A market trade's two legs as they stood before the protocol ran. See {MarketTradeLogic-_marketLegs}.
*/
struct MarketLegs {
address sellToken;
address buyToken;
uint8 sellCategory;
uint8 buyCategory;
uint256 sellBefore;
uint256 buyBefore;
}
/**
* @title MarketTradeLogic
* @notice Market buys and sells. Every trade is held to oracle value and its shortfall charged to the
* owner's `dailyLossAllowance`, which cannot be lifted — so only an asset with a
* price feed (or a stablecoin) can be traded at market. An allowance of 0 turns market trading
* off: every trade is refused before it runs, even one that would lose nothing.
* @dev Its own library because the price and allowance checks do not fit in {DeFiLogic} under the
* 24,576-byte code size limit. The protocol, asset and clone checks are {DeFiLogic}'s own, called
* as internal functions and so compiled in here: one definition, no library-to-library link.
* Operates on the same ERC-7201 {DeFiStorage} and {VaultStorage}.
*/
library MarketTradeLogic {
using SafeERC20 for IERC20;
// Set while a market trade runs — keccak256("bitty.transient.vault.marketTrade"). The trade is
// judged by the vault's balances before and after the protocol runs, and the route is the
// caller's: it can run the caller's code mid-swap (a token's transfer hook, a pool hook, ETH sent
// to a contract). Anything that call could do to move those balances — unwind a position into
// the vault, run a second trade, fill a signed intent order, wrap idle ETH — would be counted as
// what the trade did, so a sale into the caller's own pool could pass as fair. Every vault
// function that moves balances refuses while it is set (see {requireNotTrading}). Transient, so
// like {PaymentCore}'s payout lock it binds nothing across an upgrade.
bytes32 private constant _TRADING_SLOT = 0x2c5e93362f6cd886a87129ab7e35433621ed27ad98f1b17be33ee853e8647670;
/**
* Reverts while a market trade is running. Called by every vault function that moves balances.
*/
function requireNotTrading() internal view {
if (isTrading()) revert ReentrantCall();
}
function isTrading() internal view returns (bool trading) {
assembly ("memory-safe") {
trading := tload(_TRADING_SLOT)
}
}
function _setTrading(bool trading) private {
assembly ("memory-safe") {
tstore(_TRADING_SLOT, trading)
}
}
function marketSell(
address marketTradeProtocol,
address sellToken,
uint256 sellAmount,
address buyToken,
uint256 buyAmountMin,
bytes memory path
) external {
requireNotTrading();
_setTrading(true);
DeFiStorage storage $ = BittyStorage.defi();
DeFiLogic._onlyInitialized();
uint64 lossAllowance = _lossAllowance();
(MarketLegs memory legs, MarketTradeInfo memory info) = _marketLegs($, marketTradeProtocol, sellToken, buyToken);
if (LockLib.level() != 0) _requireIntoStableCoin(legs);
address clone = DeFiLogic._cloneProtocol($, marketTradeProtocol);
if (sellToken != address(0) && sellAmount > 0 && IERC20(sellToken).allowance(address(this), clone) < sellAmount)
{
IERC20(sellToken).forceApprove(clone, type(uint256).max);
}
bytes memory data = abi.encode(sellToken, sellAmount, buyToken, buyAmountMin, path);
IBittyV1MarketTradeProtocol(clone).swap{value: sellToken == address(0) ? sellAmount : 0}(data, address(this));
_settleMarketTrade(legs, info, lossAllowance);
_setTrading(false);
}
function marketBuy(
address marketTradeProtocol,
address sellToken,
uint256 sellAmountMax,
address buyToken,
uint256 buyAmount,
bytes memory reversedPath
) external {
requireNotTrading();
_setTrading(true);
DeFiStorage storage $ = BittyStorage.defi();
DeFiLogic._onlyInitialized();
uint64 lossAllowance = _lossAllowance();
(MarketLegs memory legs, MarketTradeInfo memory info) = _marketLegs($, marketTradeProtocol, sellToken, buyToken);
address clone = DeFiLogic._cloneProtocol($, marketTradeProtocol);
if (sellToken != address(0) && IERC20(sellToken).allowance(address(this), clone) < sellAmountMax) {
IERC20(sellToken).forceApprove(clone, type(uint256).max);
}
bytes memory data = abi.encode(sellToken, sellAmountMax, buyToken, buyAmount, reversedPath);
IBittyV1MarketTradeProtocol(clone).swapExactOut(data, address(this));
_settleMarketTrade(legs, info, lossAllowance);
_setTrading(false);
}
/**
* @dev A locked vault sells only out of a non-stablecoin and into a stablecoin: the one trade that
* turns an asset its escape destination may not accept into one it will. The proceeds land in
* the vault, but the sale is priced and charged to the loss allowance as any trade is, so a
* held owner key may still lose up to that allowance per day through it, until the vault holds
* no non-stablecoin. Under a lock the allowance can only be lowered ({RiskLogic-updateRisk}),
* and at 0 this sale is refused. A stablecoin already is the exit, so swapping one for another
* under a lock is refused.
*/
function _requireIntoStableCoin(MarketLegs memory legs) private pure {
if (legs.buyCategory & ASSET_STABLE_COIN == 0 || legs.sellCategory & ASSET_STABLE_COIN != 0) {
revert VaultLocked();
}
}
function _lossAllowance() private view returns (uint64 allowance) {
allowance = RiskLogic.effectiveDailyLossAllowance(BittyStorage.vault());
if (allowance == 0) revert DailyLossAllowanceExceeded();
}
/**
* @dev Everything a market trade checks before it runs, from one guard read,
* {IBittyV1Guard-marketTradeInfo}, which also brings the price feeds: the protocol is a live
* market-trade protocol; the bought token is registered, and named on the owner's own allow
* list when that is on; the sold token has a category, which the guard keeps for an asset it
* has removed, and need not be on the owner's list, since selling out of an asset either list
* has dropped is how the vault leaves it; the tokens differ — the same token on both legs would net its
* own sale against its own purchase and hide both — and both may trade at market. The vault's
* balance of each token is taken just before the protocol runs.
*/
function _marketLegs(DeFiStorage storage $, address protocol, address sellToken, address buyToken)
private
view
returns (MarketLegs memory legs, MarketTradeInfo memory info)
{
info = IBittyV1Guard(BITTY_GUARD).marketTradeInfo(protocol, sellToken, buyToken);
bool ownList = BittyStorage.vault().ownAllowListActive;
if (info.protocolCategory != PROTOCOL_MARKET_TRADE || (ownList && !$.protocols[protocol])) {
revert InvalidMarketTradeProtocol();
}
if (info.protocolDeprecated) revert Deprecated();
if (info.sellCategory == 0) revert NotRegistered();
if (info.buyCategory == 0 || (ownList && !$.assets[buyToken])) revert NotRegistered();
if (sellToken == buyToken) revert MarketTradeNotSupported();
if (info.sellCategory & info.buyCategory & ASSET_AMM_LIQUID == 0) revert MarketTradeNotSupported();
legs.sellToken = sellToken;
legs.buyToken = buyToken;
legs.sellCategory = info.sellCategory;
legs.buyCategory = info.buyCategory;
legs.sellBefore = _balanceOf(sellToken);
legs.buyBefore = _balanceOf(buyToken);
}
/**
* @dev What a market trade actually did, measured on the vault's own balances: never from the
* arguments or the protocol, since the route the protocol runs is the caller's to choose —
* any pool, any hop, including one the caller created and priced. A leaked key that sells
* into such a pool for nothing is the case this exists for.
*
* The sold leg is valued rounding up and the bought leg rounding down, both at oracle value,
* and the trade must come out within {MAX_MARKET_TRADE_SLIPPAGE_BPS} of what it sold. What it
* came out short is then charged to `lossAllowance`: the 5% bounds one trade, and this bounds
* the day, however many trades a leaked key — the owner's or an asset manager's — splits a
* drain into. A trade that comes out ahead of the oracle charges nothing and credits nothing
* back. Under {NO_LIMIT} nothing is priced: no oracle, no slippage bound, no charge.
*/
function _settleMarketTrade(MarketLegs memory legs, MarketTradeInfo memory info, uint64 lossAllowance) private {
uint256 sellAfter = _balanceOf(legs.sellToken);
uint256 buyAfter = _balanceOf(legs.buyToken);
uint256 sold = legs.sellBefore > sellAfter ? legs.sellBefore - sellAfter : 0;
uint256 bought = buyAfter > legs.buyBefore ? buyAfter - legs.buyBefore : 0;
if (sold == 0 || lossAllowance == NO_LIMIT) return;
PriceLib.requireSequencerUp(info.sequencerUptimeFeed); // zero when both legs are stablecoins
uint256 valueIn = PriceLib.usdValue(
legs.sellToken, legs.sellCategory, sold, Math.Rounding.Ceil, info.sellFeed, info.sellQuoteFeed
);
uint256 valueOut = PriceLib.usdValue(
legs.buyToken, legs.buyCategory, bought, Math.Rounding.Floor, info.buyFeed, info.buyQuoteFeed
);
if (valueOut * 10_000 < valueIn * (10_000 - MAX_MARKET_TRADE_SLIPPAGE_BPS)) revert MarketTradePriceTooLow();
if (valueOut < valueIn) _chargeLoss(valueIn - valueOut, lossAllowance);
}
/**
* @notice Charge a bridge's loss to the daily loss allowance: `lost` of `token`, what left the
* vault less what arrives on the other side, valued at oracle price rounding up.
* @dev `info` is the guard's {IBittyV1Guard-marketTradeInfo} read with `token` on both legs; the
* bought leg's category and feeds are the token's current ones. An allowance of 0 refuses any
* bridge that loses anything.
*/
function chargeBridgeLoss(MarketTradeInfo memory info, address token, uint256 lost) external {
uint64 lossAllowance = RiskLogic.effectiveDailyLossAllowance(BittyStorage.vault());
if (lost == 0 || lossAllowance == NO_LIMIT) return;
PriceLib.requireSequencerUp(info.sequencerUptimeFeed);
uint256 value =
PriceLib.usdValue(token, info.buyCategory, lost, Math.Rounding.Ceil, info.buyFeed, info.buyQuoteFeed);
_chargeLoss(value, lossAllowance);
}
/**
* @dev The same one-day period as the send allowance's — opened by the first loss, reset by the
* first one a day or more later — kept separately for what trades and bridges lose.
*/
function _chargeLoss(uint256 loss, uint64 lossAllowance) private {
VaultStorage storage v = BittyStorage.vault();
uint64 periodStart = v.lossPeriodStart;
uint256 lost = v.lossInPeriod;
if (periodStart == 0 || block.timestamp >= uint256(periodStart) + 1 days) {
periodStart = uint64(block.timestamp);
lost = 0;
}
lost += loss;
if (lost > uint256(lossAllowance) * 1e18) revert DailyLossAllowanceExceeded();
v.lossPeriodStart = periodStart;
v.lossInPeriod = uint128(lost);
}
function _balanceOf(address token) private view returns (uint256) {
return token == address(0) ? address(this).balance : IERC20(token).balanceOf(address(this));
}
}
src/logic/PaymentCore.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {
NotInitialized,
TransferFailed,
ReentrantCall,
ProtectionPeriodNotEnded,
IBittyV1Vault
} from "../interfaces/IBittyV1Vault.sol";
import {IBittyV1Guard, ASSET_STABLE_COIN} from "guard-contracts/src/interfaces/IBittyV1Guard.sol";
import {IERC20} from "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {WETH} from "solmate/tokens/WETH.sol";
import {LockLib} from "./LockLib.sol";
import {BittyStorage, Deferred, VaultStorage, DeFiStorage} from "./BittyStorage.sol";
import {BITTY_GUARD} from "./Constants.sol";
/**
* @title PaymentCore
* @notice Primitives shared by {PaymentLogic} (sends) and {WhitelistLogic}:
* the reentrancy-guarded native/ERC-20 payout, the stablecoin check, the protection-window
* helpers, and the locked-immutable test. Internal, so each consumer inlines what it uses.
*/
library PaymentCore {
using SafeERC20 for IERC20;
// Transient native-ETH payout reentrancy lock — keccak256("bitty.transient.vault.payingEth").
//
// TSTORE, not SSTORE: this lives for one transaction and is gone. So unlike the ERC-7201 roots in
// {BittyStorage}, the id here binds nothing across an upgrade — there is never persisted data at
// this slot for a later implementation to lose track of. It is versionless for consistency with
// those, not because it has to be.
bytes32 private constant _PAYING_ETH_SLOT = 0x71073f41b1fbea3b4b767dfde0481e6b3581a828457e188fce9c91ccd560f31d;
function onlyInitialized(VaultStorage storage vaultStorage) internal view {
if (!vaultStorage.isInitialized) revert NotInitialized();
}
function stableCoinAllowed(address asset) internal view returns (bool) {
if ((IBittyV1Guard(BITTY_GUARD).assetCategory(asset) & ASSET_STABLE_COIN) == 0) return false;
if (BittyStorage.vault().ownAllowListActive) {
if (!BittyStorage.defi().assets[asset]) return false;
}
return true;
}
function payOut(VaultStorage storage vaultStorage, address asset, uint256 amount, address to) internal {
if (amount == 0) return;
if (asset == address(0)) {
bool locked;
assembly ("memory-safe") {
locked := tload(_PAYING_ETH_SLOT)
}
if (locked) revert ReentrantCall();
assembly ("memory-safe") {
tstore(_PAYING_ETH_SLOT, 1)
}
WETH(payable(vaultStorage.gasWrapped)).withdraw(amount);
(bool ok,) = to.call{value: amount}("");
if (!ok) revert TransferFailed();
assembly ("memory-safe") {
tstore(_PAYING_ETH_SLOT, 0)
}
} else {
IERC20(asset).safeTransfer(to, amount);
}
}
function protectionDeadline(uint256 protection) internal view returns (uint256) {
return protection == 0 ? 0 : block.timestamp + protection;
}
function requireProtectionElapsed(uint256 effectiveAt) internal view {
if (block.timestamp < effectiveAt) revert ProtectionPeriodNotEnded();
}
}
src/logic/PaymentLogic.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {
AlreadyInitialized,
AddressZero,
AmountIsZero,
ArrayLengthMismatch,
EmptyArray,
PaymentExceedsRiskCap,
PaymentExceedsPeriodLimit,
PaymentNotStableCoin
} from "../interfaces/IBittyV1Vault.sol";
import {IBittyV1Owner} from "../interfaces/IBittyV1Owner.sol";
import {IERC20Metadata} from "openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {Math} from "openzeppelin-contracts/contracts/utils/math/Math.sol";
import {BittyStorage, VaultStorage} from "./BittyStorage.sol";
import {PaymentCore} from "./PaymentCore.sol";
import {RiskLogic} from "./RiskLogic.sol";
import {NO_LIMIT} from "./Constants.sol";
import {LockLib} from "./LockLib.sol";
/**
* @title PaymentLogic
* @notice The main vault's core payments: initialization and the owner's own sends, metered by the
* send daily allowance. Whitelisted-recipient payouts live in {WhitelistLogic}, the gas budget in
* {TokenAsGasLogic}, and the risk config in {RiskLogic}; shared payout/protection primitives
* come from {PaymentCore}.
* @dev Internal, so it compiles into the vault rather than being linked: a send is the commonest call a
* vault takes, and reaching a separate library costs it a cold account access every time. The
* other logic libraries stay external because the vault could not hold them all.
*/
library PaymentLogic {
/**
* @dev A new vault starts open: no timelock, and no limit on regular sends or on what trades
* and bridges may lose, which are then not priced at all. The owner protects it by setting
* numbers: each one is a tightening from open, so it applies at once.
*
* Nothing is written but the flags: {VaultStorage.unsetIsOpen} makes an unset setting read
* as open, and rides in this slot, which is written here anyway. A vault created before
* 1.1.1 has it false and keeps what its unset settings meant: a day's timelock, and, by
* {VaultStorage.unsetRiskIsDefault}, sends off and {DEFAULT_DAILY_LOSS_ALLOWANCE} from
* 1.0.10, the ceiling before that.
*/
function initialize(address gasWrapped, bool restrictToOwnAllowList) internal {
VaultStorage storage vaultStorage = BittyStorage.vault();
if (vaultStorage.isInitialized) revert AlreadyInitialized();
vaultStorage.isInitialized = true;
vaultStorage.unsetRiskIsDefault = true;
vaultStorage.unsetIsOpen = true;
vaultStorage.gasWrapped = gasWrapped;
vaultStorage.ownAllowListActive = restrictToOwnAllowList;
}
function send(address recipient, address asset, uint256 amount) internal {
VaultStorage storage vaultStorage = BittyStorage.vault();
PaymentCore.onlyInitialized(vaultStorage);
if (recipient == address(0)) revert AddressZero();
uint64 cap = _cap(vaultStorage);
if (cap == NO_LIMIT) {
if (amount == 0) revert AmountIsZero();
} else {
uint256 value = _stableValue(asset, amount);
if (value > uint256(cap) * 1e18) revert PaymentExceedsRiskCap();
_checkOwnerSendWindow(vaultStorage, value, cap);
}
PaymentCore.payOut(vaultStorage, asset, amount, recipient);
}
function batchSend(address recipient, address[] memory assets, uint256[] memory amounts) internal {
VaultStorage storage vaultStorage = BittyStorage.vault();
PaymentCore.onlyInitialized(vaultStorage);
uint256 length = assets.length;
if (length == 0) revert EmptyArray();
if (amounts.length != length) revert ArrayLengthMismatch();
if (recipient == address(0)) revert AddressZero();
uint64 cap = _cap(vaultStorage);
if (cap == NO_LIMIT) {
for (uint256 i = 0; i < length; i++) {
if (amounts[i] == 0) revert AmountIsZero();
}
} else {
uint256 total;
for (uint256 i = 0; i < length; i++) {
total += _stableValue(assets[i], amounts[i]);
if (total > uint256(cap) * 1e18) revert PaymentExceedsRiskCap();
}
_checkOwnerSendWindow(vaultStorage, total, cap);
}
for (uint256 i = 0; i < length; i++) {
PaymentCore.payOut(vaultStorage, assets[i], amounts[i], recipient);
}
}
/**
* @notice Meters a bridge to someone else's address against the send allowance, as a send of
* `amount` of `asset` would be. See {IBittyV1DeFi-bridgeTo}.
* @dev Unlike a send under {NO_LIMIT}, the asset must be a stablecoin even when nothing is
* metered: a bridge out is only ever a stablecoin.
*/
function meterBridgeOut(address asset, uint256 amount) internal {
if (!PaymentCore.stableCoinAllowed(asset)) revert PaymentNotStableCoin();
VaultStorage storage vaultStorage = BittyStorage.vault();
uint64 cap = _cap(vaultStorage);
if (cap == NO_LIMIT) return;
uint256 value = _stableValue(asset, amount);
if (value > uint256(cap) * 1e18) revert PaymentExceedsRiskCap();
_checkOwnerSendWindow(vaultStorage, value, cap);
}
/**
* Under a cap every regular send is metered, and only a stablecoin can be metered without reading
* a price. 0 means the owner turned regular sends off: every amount is over it, so every send is
* refused. {NO_LIMIT} meters nothing: any asset, any amount.
*/
function _cap(VaultStorage storage vaultStorage) private view returns (uint64) {
return RiskLogic.effectiveSendDailyAllowance(vaultStorage);
}
/**
* What one leg is worth in 18-decimal dollars, rounded up so the allowance is never undercounted.
*/
function _stableValue(address asset, uint256 amount) private view returns (uint256) {
if (amount == 0) revert AmountIsZero();
if (!PaymentCore.stableCoinAllowed(asset)) revert PaymentNotStableCoin();
return Math.mulDiv(amount, 1e18, 10 ** IERC20Metadata(asset).decimals(), Math.Rounding.Ceil);
}
function _checkOwnerSendWindow(VaultStorage storage vaultStorage, uint256 batchStableValue, uint64 cap) private {
uint64 periodStart = vaultStorage.ownerSendPeriodStart;
uint256 sent = vaultStorage.ownerSentInPeriod;
if (periodStart == 0 || block.timestamp >= uint256(periodStart) + 1 days) {
periodStart = uint64(block.timestamp);
sent = 0;
}
uint256 total = sent + batchStableValue;
if (total > uint256(cap) * 1e18) revert PaymentExceedsPeriodLimit();
vaultStorage.ownerSendPeriodStart = periodStart;
vaultStorage.ownerSentInPeriod = uint128(total);
}
}
src/logic/PriceLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {ASSET_STABLE_COIN, PriceFeed} from "guard-contracts/src/interfaces/IBittyV1Guard.sol";
import {IERC20Metadata} from "openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {Math} from "openzeppelin-contracts/contracts/utils/math/Math.sol";
import {PriceFeedMissing, PriceStale, SequencerDown} from "../interfaces/IBittyV1DeFi.sol";
import {SEQUENCER_GRACE_PERIOD} from "./Constants.sol";
/**
* @dev The slice of Chainlink's AggregatorV3Interface the vault reads.
*/
interface IChainlinkFeed {
function latestRoundData()
external
view
returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
/**
* @title PriceLib
* @notice USD value of an asset amount, 18 decimals, for checking a market trade against a price the
* trade itself cannot move.
* @dev A stablecoin is a dollar, the same rule the send allowance counts by, so a stable leg costs no
* feed read. Anything else is priced off the Chainlink feed the guard holds for it — handed in by
* the caller from the one {IBittyV1Guard-marketTradeInfo} read — times the feed of the asset that
* one is quoted in when it is not a USD feed. The feed's decimals and the asset's come with it,
* read once when the guard was configured, so a priced leg's only call is its feed's
* `latestRoundData`; a stablecoin's decimals are still asked of the token. Every doubt
* fails closed: no feed, no staleness bound, a quote that is itself quoted, a non-positive
* answer, an answer older than that bound, or an L2 sequencer that is down or only just back all
* revert, which stops trading and nothing else — sends, withdrawals and locks never read a price.
*
* Internal, so it inlines into {MarketTradeLogic} — no separate deployment.
*/
library PriceLib {
function isStable(uint8 category) internal pure returns (bool) {
return category & ASSET_STABLE_COIN != 0;
}
function usdValue(
address asset,
uint8 category,
uint256 amount,
Math.Rounding rounding,
PriceFeed memory feed,
PriceFeed memory quoteFeed
) internal view returns (uint256) {
if (amount == 0) return 0;
if (isStable(category)) return Math.mulDiv(amount, 1e18, 10 ** _decimals(asset), rounding);
uint256 scale = 10 ** (feed.assetDecimals != 0 ? feed.assetDecimals : _decimals(asset));
(uint256 price, uint256 priceScale) = _feedPrice(asset, feed);
if (feed.hasQuote) {
if (quoteFeed.hasQuote) revert PriceFeedMissing(feed.quote);
(uint256 quotePrice, uint256 quoteScale) = _feedPrice(feed.quote, quoteFeed);
price *= quotePrice;
priceScale *= quoteScale;
}
return Math.mulDiv(amount, price * 1e18, scale * priceScale, rounding);
}
/**
* @dev One feed's answer for `asset`, checked fresh, and the power of ten it is scaled by.
*/
function _feedPrice(address asset, PriceFeed memory feed) private view returns (uint256 price, uint256 scale) {
if (feed.feed == address(0) || feed.maxAge == 0) revert PriceFeedMissing(asset);
(, int256 answer,, uint256 updatedAt,) = IChainlinkFeed(feed.feed).latestRoundData();
if (answer <= 0 || block.timestamp > updatedAt + feed.maxAge) revert PriceStale(asset);
return (uint256(answer), 10 ** feed.decimals);
}
/**
* @dev Chainlink's L2 sequencer check: answer 0 means up, and `startedAt` is when it last changed
* state; a zero `startedAt` is a round that has not been initialised, so it is not trusted
* either. A no-op for a zero `feed`: a chain with none, or a trade that read no price.
*/
function requireSequencerUp(address feed) internal view {
if (feed == address(0)) return;
(, int256 answer, uint256 startedAt,,) = IChainlinkFeed(feed).latestRoundData();
if (answer != 0 || startedAt == 0 || block.timestamp <= startedAt + SEQUENCER_GRACE_PERIOD) {
revert SequencerDown();
}
}
function _decimals(address asset) private view returns (uint8) {
return asset == address(0) ? 18 : IERC20Metadata(asset).decimals();
}
}
src/logic/RiskLogic.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {
NotInitialized,
PendingChanges,
RiskTimelockTooLong,
RiskTimelockTooShort,
TimelockNeedsLimits,
RiskAllowanceOutOfRange,
VaultLocked
} from "../interfaces/IBittyV1Vault.sol";
import {IBittyV1Owner} from "../interfaces/IBittyV1Owner.sol";
import {BittyStorage, VaultStorage, RiskConfig, TimelockedValue} from "./BittyStorage.sol";
import {TimelockLib} from "./TimelockLib.sol";
import {
MAX_RISK_TIMELOCK,
MIN_RISK_TIMELOCK,
MAX_DAILY_ALLOWANCE,
LEGACY_DAILY_ALLOWANCE,
DEFAULT_DAILY_LOSS_ALLOWANCE,
STORED_ZERO,
NO_LIMIT
} from "./Constants.sol";
import {LockLib} from "./LockLib.sol";
/**
* @title RiskLogic
* @notice The main vault's risk surface, which is three numbers: {IBittyV1Owner.RiskSettings.timelock}
* — the one wait in front of everything deferred — `sendDailyAllowance`, the ceiling on
* what may leave per day through regular sends, and `dailyLossAllowance`, the
* ceiling on what market trades and bridges may lose against oracle value per day. None of them can be
* lifted: each is held between the bounds in {Constants}. An unset timelock reads as the
* shortest allowed; what an unset allowance reads as depends on the vault's age (below). Either allowance may be set to 0, which turns regular
* sends, or market trading and bridging, off — the tightest it can be, so it lands at once, and turning it
* back on waits out the timelock like any loosening. A sentinel partial-update lets the owner set one
* without restating the others; tightening applies immediately, loosening waits out the
* timelock in force when it was asked for.
*
* @dev Four numbers used to live here, and the storage held four slots to match. They are three
* now — see {IBittyV1Owner.RiskSettings} for which questions collapsed into which, and why the
* two allowances are kept apart. The period each allowance runs over is no longer a number at
* all: it is one day, opened by the first send (or loss) and reset by the first one a day or more
* later, as {PaymentLogic} and {MarketTradeLogic} keep it. It is not a rolling 24 hours: up to
* twice an allowance can leave within moments across the end of one period and the start of
* the next.
*
* Unset is stored as 0 rather than written at initialization. An unset timelock is 0 on a
* vault created from 1.1.1 on ({VaultStorage.unsetIsOpen}) and
* {MIN_RISK_TIMELOCK} on one created before; a timelock of 0 is stored as
* {STORED_ZERO}. An unset allowance means one of two things, by
* {VaultStorage.unsetIsOpen} and {VaultStorage.unsetRiskIsDefault}: from 1.1.1, no limit
* ({NO_LIMIT}); from 1.0.10, sends off and {DEFAULT_DAILY_LOSS_ALLOWANCE} for trades; before
* that, the ceiling, as it always has — which is what lets those vaults upgrade with nothing
* to migrate. Every read goes through {effectiveTimelock}, {effectiveSendDailyAllowance} and
* {effectiveDailyLossAllowance}; reading the slots directly would see a 0 that means
* "the default", not "off". An allowance of 0 is stored as {STORED_ZERO} for that reason.
*
* Whether a new allowance loosens is judged against the allowance IN FORCE, not the raw slot:
* an unset slot on a 1.0.10 vault means sends are off, and raising it must wait out the
* timelock like any other loosening, while on a 1.1.1 vault it means no limit, so any number
* is a tightening.
*
* Split out of {PaymentLogic}; operates on the same ERC-7201 {VaultStorage}.
*/
library RiskLogic {
uint256 constant UNCHANGED = type(uint256).max;
function _onlyInitialized(VaultStorage storage vaultStorage) private view {
if (!vaultStorage.isInitialized) revert NotInitialized();
}
/**
* The timelock in force: what the owner set, or while they have set nothing, 0 on a vault
* created from 1.1.1 on and {MIN_RISK_TIMELOCK} on one created before.
*/
function effectiveTimelock(VaultStorage storage $) internal view returns (uint64) {
return _read(TimelockLib.effective($.riskConfig.timelock), _unsetTimelock($));
}
/**
* The send allowance in force, in whole USD, or {NO_LIMIT}: what the owner set, or while they
* have set nothing, no limit on a vault created from 1.1.1 on, 0 on one created from 1.0.10 on,
* and {LEGACY_DAILY_ALLOWANCE} on one created before.
*/
function effectiveSendDailyAllowance(VaultStorage storage $) internal view returns (uint64) {
return _read(TimelockLib.effective($.riskConfig.sendDailyAllowance), _unsetSend($));
}
/**
* The daily loss allowance in force, in whole USD: what the owner set, or
* {LEGACY_DAILY_ALLOWANCE}; no limit while unset on a vault created from 1.1.1 on.
*/
function effectiveDailyLossAllowance(VaultStorage storage $) internal view returns (uint64) {
return _read(TimelockLib.effective($.riskConfig.dailyLossAllowance), _unsetLoss($));
}
function _unsetTimelock(VaultStorage storage $) private view returns (uint64) {
return $.unsetIsOpen ? 0 : MIN_RISK_TIMELOCK;
}
function _unsetSend(VaultStorage storage $) private view returns (uint64) {
return $.unsetIsOpen ? NO_LIMIT : $.unsetRiskIsDefault ? 0 : LEGACY_DAILY_ALLOWANCE;
}
function _unsetLoss(VaultStorage storage $) private view returns (uint64) {
return $.unsetIsOpen ? NO_LIMIT : $.unsetRiskIsDefault ? DEFAULT_DAILY_LOSS_ALLOWANCE : LEGACY_DAILY_ALLOWANCE;
}
/**
* A value as stored, read back: 0 is unset, so `unset`; {STORED_ZERO} is 0.
*/
function _read(uint64 stored, uint64 unset) private pure returns (uint64) {
if (stored == STORED_ZERO) return 0;
return stored == 0 ? unset : stored;
}
/**
* Where a value is headed: the change still waiting if there is one, else the value itself.
*/
function _headedTo(TimelockedValue storage tv) private view returns (uint64) {
return tv.pendingAt != 0 ? tv.pending : tv.value;
}
/**
* A timelock above 0 is protection, and protection with no ceiling protects nothing: a leaked key
* would send or trade everything away without needing anything the timelock delays. So wherever
* the settings are headed, a timelock above 0 comes with a number for both allowances. Judged on
* where each value is headed, so no waiting change can land the vault in that state either.
*/
function _requireLimitsUnderTimelock(VaultStorage storage $) private view {
RiskConfig storage r = $.riskConfig;
if (_read(_headedTo(r.timelock), _unsetTimelock($)) == 0) return;
if (
_read(_headedTo(r.sendDailyAllowance), _unsetSend($)) == NO_LIMIT
|| _read(_headedTo(r.dailyLossAllowance), _unsetLoss($)) == NO_LIMIT
) revert TimelockNeedsLimits();
}
function riskTimelock() external view returns (uint64) {
return effectiveTimelock(BittyStorage.vault());
}
function updateRisk(IBittyV1Owner.RiskSettings calldata settings) external {
VaultStorage storage vaultStorage = BittyStorage.vault();
_onlyInitialized(vaultStorage);
RiskConfig storage r = vaultStorage.riskConfig;
if (LockLib.level() != LockLib.NONE) _requireLockedLowering(vaultStorage, settings);
uint64 timelock = effectiveTimelock(vaultStorage);
if (settings.timelock != UNCHANGED) {
if (settings.timelock > MAX_RISK_TIMELOCK) revert RiskTimelockTooLong();
if (settings.timelock != 0 && settings.timelock < MIN_RISK_TIMELOCK) revert RiskTimelockTooShort();
uint64 next = settings.timelock == 0 ? STORED_ZERO : uint64(settings.timelock);
TimelockLib.setCap(r.timelock, next, settings.timelock < timelock, timelock);
}
if (settings.sendDailyAllowance != UNCHANGED) {
_setAllowance(
r.sendDailyAllowance,
settings.sendDailyAllowance,
MAX_DAILY_ALLOWANCE,
effectiveSendDailyAllowance(vaultStorage),
timelock
);
}
if (settings.dailyLossAllowance != UNCHANGED) {
_setAllowance(
r.dailyLossAllowance,
settings.dailyLossAllowance,
MAX_DAILY_ALLOWANCE,
effectiveDailyLossAllowance(vaultStorage),
timelock
);
}
_requireLimitsUnderTimelock(vaultStorage);
emit IBittyV1Owner.RiskSettingsUpdated(settings);
}
/**
* @dev Under a lock the one number that still bounds a loss is the daily loss allowance, as
* the owner's sale into a stablecoin is the one trade a lock leaves open. So it alone may move,
* and only down, which applies at once; nothing else may, since a lock admits no change that
* would wait out the timelock. At 0 the locked sale is off, and under a forever lock that is
* for good: an asset the escape destination cannot take is then left to a limit order.
*/
function _requireLockedLowering(VaultStorage storage $, IBittyV1Owner.RiskSettings calldata settings) private view {
if (settings.timelock != UNCHANGED || settings.sendDailyAllowance != UNCHANGED) revert VaultLocked();
if (settings.dailyLossAllowance > effectiveDailyLossAllowance($)) revert VaultLocked();
}
/**
* 0 to `max`, or {NO_LIMIT}; 0 is stored as {STORED_ZERO}, since a stored 0 means unset. It loosens when it
* is above `inForce`, the allowance in force before the change.
*/
function _setAllowance(TimelockedValue storage tv, uint256 allowance, uint64 max, uint64 inForce, uint64 timelock)
private
{
if (allowance > max && allowance != NO_LIMIT) revert RiskAllowanceOutOfRange();
uint64 next = allowance == 0 ? STORED_ZERO : uint64(allowance);
TimelockLib.setCap(tv, next, allowance > inForce, timelock);
}
function pendingChanges() external view returns (PendingChanges memory p) {
VaultStorage storage $ = BittyStorage.vault();
RiskConfig storage r = $.riskConfig;
p.lockLevel = LockLib.level();
(p.timelock, p.timelockAt) = _waiting(r.timelock);
if (p.timelock == STORED_ZERO) p.timelock = 0;
(p.sendDailyAllowance, p.sendDailyAllowanceAt) = _waiting(r.sendDailyAllowance);
if (p.sendDailyAllowance == STORED_ZERO) p.sendDailyAllowance = 0;
(p.dailyLossAllowance, p.dailyLossAllowanceAt) = _waiting(r.dailyLossAllowance);
if (p.dailyLossAllowance == STORED_ZERO) p.dailyLossAllowance = 0;
(p.gasBudgetDaily, p.gasBudgetDailyAt) = _waiting($.gasBudgetDaily);
(, p.bridgeEnableAt) = _waiting(BittyStorage.defi().bridgeDisabled);
}
function _waiting(TimelockedValue storage tv) private view returns (uint64 value, uint64 vaule1) {
if (tv.pendingAt == 0 || block.timestamp >= tv.pendingAt) return (0, 0);
return (tv.pending, tv.pendingAt);
}
function riskSettings()
external
view
returns (uint64 timelock, uint64 sendDailyAllowance, uint64 dailyLossAllowance)
{
VaultStorage storage $ = BittyStorage.vault();
return (effectiveTimelock($), effectiveSendDailyAllowance($), effectiveDailyLossAllowance($));
}
}
src/logic/TimelockLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {TimelockedValue} from "./BittyStorage.sol";
/**
* @title TimelockLib
* @notice The shared timelocked-value math used by the risk config and the relayed-gas budget. A change
* that tightens risk (or lowers a limit) applies immediately; a change that loosens is deferred
* by the given timelock. Internal, so it inlines into each consumer — no separate deployment.
*/
library TimelockLib {
function effective(TimelockedValue storage tv) internal view returns (uint64) {
if (tv.pendingAt != 0 && block.timestamp >= tv.pendingAt) return tv.pending;
return tv.value;
}
function _settle(TimelockedValue storage tv) private {
if (tv.pendingAt != 0 && block.timestamp >= tv.pendingAt) {
tv.value = tv.pending;
tv.pending = 0;
tv.pendingAt = 0;
}
}
/**
* Drop a waiting loosening; one whose time has already come is in force, so it stays.
*/
function cancelPending(TimelockedValue storage tv) internal {
if (tv.pendingAt == 0) return;
_settle(tv);
tv.pending = 0;
tv.pendingAt = 0;
}
function _apply(TimelockedValue storage tv, uint64 next, bool loosen, uint64 timelock) private {
if (!loosen) {
tv.value = next;
tv.pending = 0;
tv.pendingAt = 0;
} else {
tv.pending = next;
tv.pendingAt = uint64(block.timestamp) + timelock;
}
}
/**
* A cap, with whether it loosens decided by the caller: what an unset slot means depends on the
* vault (see {VaultStorage.unsetRiskIsDefault}), so only the caller knows the value in force.
*/
function setCap(TimelockedValue storage tv, uint64 next, bool loosen, uint64 timelock) internal {
_settle(tv);
_apply(tv, next, loosen, timelock);
}
function setGasBudget(TimelockedValue storage tv, uint64 next, uint64 timelock) internal {
_settle(tv);
bool loosen = next == 0 || (tv.value != 0 && next > tv.value);
_apply(tv, next, loosen, timelock);
}
}
src/logic/TokenAsGasLogic.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {
NotInitialized,
AmountIsZero,
InvalidAsset,
InsufficientBalance,
GasBudgetExceeded,
GasBudgetTooHigh
} from "../interfaces/IBittyV1Vault.sol";
import {IBittyV1Owner} from "../interfaces/IBittyV1Owner.sol";
import {IBittyV1Guard, ASSET_STABLE_COIN, PriceFeed} from "guard-contracts/src/interfaces/IBittyV1Guard.sol";
import {IERC20} from "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "openzeppelin-contracts/contracts/utils/math/Math.sol";
import {BittyStorage, VaultStorage} from "./BittyStorage.sol";
import {TimelockLib} from "./TimelockLib.sol";
import {RiskLogic} from "./RiskLogic.sol";
import {PriceLib} from "./PriceLib.sol";
import {BITTY_GUARD, BITTY_FEE_COLLECTOR, SENTINEL, SYSTEM_DAILY_MAX_GAS_BUDGET} from "./Constants.sol";
/**
* @title TokenAsGasLogic
* @notice The main vault's relayed-gas surface: the per-UTC-day USD budget the vault will pay a trusted
* forwarder from, its config, the one-time activation fee, and the per-relay charge. Fees are
* paid in a stablecoin (a dollar) or the vault's WETH ({VaultStorage-gasWrapped}, valued off the
* guard's Chainlink feed), so the same daily budget bounds both.
* Split out of {PaymentLogic}; operates on the same ERC-7201 {VaultStorage}.
*/
library TokenAsGasLogic {
using SafeERC20 for IERC20;
function _onlyInitialized(VaultStorage storage vaultStorage) private view {
if (!vaultStorage.isInitialized) revert NotInitialized();
}
function _dailyLimit(VaultStorage storage vaultStorage) private view returns (uint64) {
if (vaultStorage.tokenAsGasDisabled) return 0;
uint64 owned = TimelockLib.effective(vaultStorage.gasBudgetDaily);
return owned == 0 ? SYSTEM_DAILY_MAX_GAS_BUDGET : owned;
}
function disableTokenAsGas() external {
VaultStorage storage vaultStorage = BittyStorage.vault();
_onlyInitialized(vaultStorage);
vaultStorage.tokenAsGasDisabled = true;
// Off is the tightest the budget can be, so a raise still waiting out the timelock goes with it;
// otherwise it would land unseen the moment the owner turned token-as-gas back on.
TimelockLib.cancelPending(vaultStorage.gasBudgetDaily);
emit IBittyV1Owner.TokenAsGasSet(false, new address[](0), 0);
}
function setTokenAsGas(address[] calldata assets, uint64 dailyLimit) external {
VaultStorage storage vaultStorage = BittyStorage.vault();
_onlyInitialized(vaultStorage);
if (dailyLimit > SYSTEM_DAILY_MAX_GAS_BUDGET) revert GasBudgetTooHigh();
mapping(address => address) storage allowed = vaultStorage.tokenAsGasAssets;
address entry = allowed[SENTINEL];
while (entry != SENTINEL && entry != address(0)) {
address next = allowed[entry];
allowed[entry] = address(0);
entry = next;
}
allowed[SENTINEL] = SENTINEL;
for (uint256 i = 0; i < assets.length; i++) {
address asset = assets[i];
if (!_gasEligible(vaultStorage, asset)) revert InvalidAsset();
if (asset == address(0) || asset == SENTINEL || allowed[asset] != address(0)) continue;
allowed[asset] = allowed[SENTINEL];
allowed[SENTINEL] = asset;
}
vaultStorage.tokenAsGasDisabled = false;
uint64 timelock = RiskLogic.effectiveTimelock(vaultStorage);
TimelockLib.setGasBudget(vaultStorage.gasBudgetDaily, dailyLimit, timelock);
emit IBittyV1Owner.TokenAsGasSet(true, assets, dailyLimit);
}
function getTokenAsGasAssets() external view returns (address[] memory) {
mapping(address => address) storage allowed = BittyStorage.vault().tokenAsGasAssets;
uint256 n;
for (address a = allowed[SENTINEL]; a != SENTINEL && a != address(0); a = allowed[a]) {
n++;
}
address[] memory out = new address[](n);
uint256 i;
for (address a = allowed[SENTINEL]; a != SENTINEL && a != address(0); a = allowed[a]) {
out[i++] = a;
}
return out;
}
function gasBudgetDailyLimit() external view returns (uint256) {
return _dailyLimit(BittyStorage.vault());
}
function gasBudgetRemaining() external view returns (uint256) {
VaultStorage storage vaultStorage = BittyStorage.vault();
uint256 limit = uint256(_dailyLimit(vaultStorage)) * 1e18;
if (vaultStorage.gasBudgetDay != uint64(block.timestamp / 1 days)) return limit;
uint256 spent = vaultStorage.gasSpentToday;
return spent >= limit ? 0 : limit - spent;
}
function relayerFeeValue(address asset, uint256 amount) external view returns (uint256) {
return _feeValue(BittyStorage.vault(), asset, amount);
}
function payActivationFee(address asset, uint256 amount) external {
VaultStorage storage vaultStorage = BittyStorage.vault();
_onlyInitialized(vaultStorage);
if (!_gasEligible(vaultStorage, asset)) revert InvalidAsset();
if (IERC20(asset).balanceOf(address(this)) < amount) revert InsufficientBalance();
IERC20(asset).safeTransfer(BITTY_FEE_COLLECTOR, amount);
emit IBittyV1Owner.ActivationFeePaid(asset, amount);
}
function _gasEligible(VaultStorage storage vaultStorage, address asset) private view returns (bool) {
return
asset == vaultStorage.gasWrapped
|| (IBittyV1Guard(BITTY_GUARD).assetCategory(asset) & ASSET_STABLE_COIN) != 0;
}
function _feeValue(VaultStorage storage vaultStorage, address asset, uint256 amount)
private
view
returns (uint256)
{
if (asset != vaultStorage.gasWrapped) {
return Math.mulDiv(amount, 1e18, 10 ** IERC20Metadata(asset).decimals(), Math.Rounding.Ceil);
}
IBittyV1Guard guard = IBittyV1Guard(BITTY_GUARD);
PriceLib.requireSequencerUp(guard.sequencerUptimeFeed());
PriceFeed memory feed = guard.priceFeed(asset);
PriceFeed memory quoteFeed;
if (feed.hasQuote) quoteFeed = guard.priceFeed(feed.quote);
return PriceLib.usdValue(asset, 0, amount, Math.Rounding.Ceil, feed, quoteFeed);
}
function _tokenAsGasAssetAllowed(VaultStorage storage vaultStorage, address asset) private view returns (bool) {
if (asset == address(0) || asset == SENTINEL) return false;
if (!_gasEligible(vaultStorage, asset)) return false;
address head = vaultStorage.tokenAsGasAssets[SENTINEL];
if (head == address(0) || head == SENTINEL) {
return true;
}
return vaultStorage.tokenAsGasAssets[asset] != address(0);
}
function payRelayerFee(address asset, uint256 amount) external {
VaultStorage storage vaultStorage = BittyStorage.vault();
_onlyInitialized(vaultStorage);
if (amount == 0) revert AmountIsZero();
if (!_tokenAsGasAssetAllowed(vaultStorage, asset)) revert InvalidAsset();
uint256 value = _feeValue(vaultStorage, asset, amount);
uint64 today = uint64(block.timestamp / 1 days);
uint256 spent = (vaultStorage.gasBudgetDay == today ? uint256(vaultStorage.gasSpentToday) : 0) + value;
uint256 limit = uint256(_dailyLimit(vaultStorage)) * 1e18;
if (spent > limit) revert GasBudgetExceeded();
vaultStorage.gasBudgetDay = today;
vaultStorage.gasSpentToday = uint96(spent);
IERC20(asset).safeTransfer(BITTY_FEE_COLLECTOR, amount);
emit IBittyV1Owner.RelayerFeePaid(asset, amount, spent, limit - spent);
}
}
src/logic/WhitelistLogic.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {
AddressZero,
AmountIsZero,
IBittyV1Vault,
NoEscapeRecipient,
WhitelistedRecipientNotFound,
WhitelistedRecipientWrongChain,
WhitelistedRecipientIsVault,
RecipientNotAnAddress,
WhitelistEntryView,
WHITELIST_REMOVED,
WHITELIST_PENDING,
WHITELIST_PAYABLE,
WHITELIST_VOIDED,
WHITELIST_REMOVAL_QUEUED
} from "../interfaces/IBittyV1Vault.sol";
import {IBittyV1Owner} from "../interfaces/IBittyV1Owner.sol";
import {BittyStorage, Deferred, VaultStorage, WhitelistEntry} from "./BittyStorage.sol";
import {PaymentCore} from "./PaymentCore.sol";
import {LockLib} from "./LockLib.sol";
import {RiskLogic} from "./RiskLogic.sol";
import {ANY_EVM_CHAIN, EVM_CHAIN_KEY, BITTY_GUARD} from "./Constants.sol";
import {IBittyV1Guard} from "guard-contracts/src/interfaces/IBittyV1Guard.sol";
/**
* @title WhitelistLogic
* @notice Whitelisted recipients: add / review / remove, and the protected payout to a pre-approved
* recipient. Split out of {PaymentLogic}; shares payout/protection via {PaymentCore}.
*
* @dev A whitelisted recipient is the owner's way out after a key leaks: a lock stops every other
* payment, but not these. So taking one away has to wait like granting one does. Were removal
* instant, the thief's first call would empty the list, and the forever lock that was meant to
* save the vault would instead seal the money in it.
*
* Removing an entry the owner can already pay therefore queues, for the timelock in force, and
* the entry stays payable until then. A lock voids the queued removal by the same epoch stamp
* that voids a queued addition, so locking keeps every destination the owner already had.
* Nothing is lost by removing at once an entry nobody can pay yet — one still waiting out its
* own window, or voided by a lock — so those go immediately, as does everything on a vault with
* no timelock.
*
* An entry is an address and nothing else: it accepts any asset the vault holds. A recipient
* held to one asset would strand every other one once the vault is locked, because a locked
* vault cannot trade into it — and this list is what a locked vault pays out through. Nor is
* there editing an entry in place: a new address is an addition and the old one a removal, and
* made together in one multicall the new becomes payable just as the old stops being.
*
* An entry may name another chain ({addWhitelistedRecipientOn}): an address there, which the
* vault reaches only by a bridge. Every payout here refuses such an entry, since the same 20
* bytes on this chain need not be anyone's, and so does the forever lock's escape check, since
* the bridge it would need (the switch, the adapter, the route) can go away under a lock. Or
* it may name every EVM chain ({ANY_EVM_CHAIN}): the same address here, paid like an entry
* here and an escape like one, and on any EVM chain a bridge reaches.
*
* The price is that a matured destination that should not be there cannot be struck off at
* once either. A thief who has one can pay to it whatever the rules on removal, so the owner's
* answer is the same as before: move the money to a destination of their own first.
*/
library WhitelistLogic {
function addWhitelistedRecipientOne(address recipient) external returns (uint256 id) {
id = _add(recipient);
emit IBittyV1Owner.WhitelistedRecipientSet(id, recipient);
}
/**
* An entry on `chainId`, or on every EVM chain for {ANY_EVM_CHAIN}, under the same protection
* window as one here. `recipient` is 32 bytes so a Solana address fits; one here or on every
* EVM chain must be a 20-byte address. This chain's own id makes an ordinary entry. The
* vault's own address is refused: on another EVM chain it is the vault's counterpart, which
* {IBittyV1DeFi-bridge} already reaches, and on TRON no one's.
*
* A 32-byte address keeps its low 20 bytes in the entry, so every existing check reads the
* entry as present, and the whole of it beside; one whose low 20 bytes are all zero is refused,
* which no real key's address is.
*/
function addWhitelistedRecipientOn(uint256 chainId, bytes32 recipient) external returns (uint256 id) {
address low = address(uint160(uint256(recipient)));
bool wide = uint256(recipient) >> 160 != 0;
if (chainId == 0 || chainId == block.chainid) {
if (wide) revert RecipientNotAnAddress();
id = _add(low);
emit IBittyV1Owner.WhitelistedRecipientSet(id, low);
return id;
}
if (wide && chainId == ANY_EVM_CHAIN) revert RecipientNotAnAddress();
if (!wide && low == address(this)) revert WhitelistedRecipientIsVault();
id = _add(low);
VaultStorage storage vaultStorage = BittyStorage.vault();
vaultStorage.whitelistedRecipientChain[id] = chainId;
if (wide) vaultStorage.whitelistedRecipientAccount[id] = recipient;
emit IBittyV1Owner.WhitelistedRecipientSetOn(id, chainId, recipient);
}
/**
* Entry `id`'s address on its chain, as 32 bytes.
*/
function _account(VaultStorage storage vaultStorage, uint256 id, address recipient)
private
view
returns (bytes32 account)
{
account = vaultStorage.whitelistedRecipientAccount[id];
if (account == 0) account = bytes32(uint256(uint160(recipient)));
}
function _add(address recipient) private returns (uint256 id) {
VaultStorage storage vaultStorage = BittyStorage.vault();
PaymentCore.onlyInitialized(vaultStorage);
if (recipient == address(0)) revert AddressZero();
uint256 effectiveAt = PaymentCore.protectionDeadline(RiskLogic.effectiveTimelock(vaultStorage));
id = ++vaultStorage.nextWhitelistedRecipientId;
vaultStorage.whitelistedRecipient[id].recipient = recipient;
vaultStorage.whitelistedRecipientDeferred[id] = Deferred({
effectiveAt: uint64(effectiveAt), lockEpoch: effectiveAt == 0 ? LockLib.SETTLED : LockLib.lockEpoch()
});
}
/**
* Refuse unless entry `id` can be paid right now — it exists, its own window has run, no lock voided
* it and no removal of it has landed. Asked before the forever lock: once that is engaged nothing
* can be added, so a vault locked with no payable recipient could never pay anything out again.
* The vault itself is no way out either: paying it moves nothing, so it is refused like a missing
* entry, and so is one on another chain. One named entry rather than a search of the list, so
* the check costs the same however many entries a thief has queued.
*/
function requireEscape(uint256 id) external view {
VaultStorage storage vaultStorage = BittyStorage.vault();
WhitelistEntry memory entry = vaultStorage.whitelistedRecipient[id];
if (
entry.recipient == address(0) || entry.recipient == address(this) || _removed(entry)
|| !_here(vaultStorage.whitelistedRecipientChain[id])
) {
revert NoEscapeRecipient();
}
if (!_payable(vaultStorage.whitelistedRecipientDeferred[id])) revert NoEscapeRecipient();
}
function removeWhitelistedRecipients(uint256[] calldata ids) external {
VaultStorage storage vaultStorage = BittyStorage.vault();
PaymentCore.onlyInitialized(vaultStorage);
uint64 timelock = RiskLogic.effectiveTimelock(vaultStorage);
for (uint256 i; i < ids.length; ++i) {
_remove(vaultStorage, ids[i], timelock);
}
if (ids.length > 0) emit IBittyV1Owner.WhitelistedRecipientsRemoved(ids);
}
/**
* Remove entry `id`: at once if the owner cannot pay it yet, otherwise queued behind the
* timelock. A removal already queued starts over.
*/
function _remove(VaultStorage storage vaultStorage, uint256 id, uint64 timelock) private {
WhitelistEntry storage entry = vaultStorage.whitelistedRecipient[id];
if (_settle(vaultStorage, id, entry) == address(0)) revert WhitelistedRecipientNotFound();
if (!_payable(vaultStorage.whitelistedRecipientDeferred[id])) {
_delete(vaultStorage, id);
return;
}
uint64 removeAt = uint64(block.timestamp) + timelock;
entry.removeAt = removeAt;
entry.removeEpoch = LockLib.lockEpoch();
emit IBittyV1Owner.WhitelistedRecipientRemovalQueued(id, removeAt);
}
/**
* Whether the owner can pay the entry as it stands: its window has run and no lock voided it.
*/
function _payable(Deferred storage deferred) private view returns (bool) {
uint64 effectiveAt = deferred.effectiveAt;
return block.timestamp >= effectiveAt && LockLib.honoured(deferred.lockEpoch, effectiveAt);
}
/**
* Whether a queued removal of `entry` has taken effect: its time has come and no lock voided it.
*/
function _removed(WhitelistEntry memory entry) private view returns (bool) {
uint64 removeAt = entry.removeAt;
return removeAt != 0 && block.timestamp >= removeAt && LockLib.honoured(entry.removeEpoch, removeAt);
}
/**
* Carry out the removal queued against `entry` once its time has come, or drop it if a lock
* voided it. Returns the recipient as it now stands, zero once removed. Free when nothing is
* queued.
*/
function _settle(VaultStorage storage vaultStorage, uint256 id, WhitelistEntry storage entry)
private
returns (address)
{
uint64 removeAt = entry.removeAt;
if (removeAt == 0 || block.timestamp < removeAt) return entry.recipient;
if (!LockLib.honoured(entry.removeEpoch, removeAt)) {
entry.removeAt = 0;
entry.removeEpoch = 0;
return entry.recipient;
}
_delete(vaultStorage, id);
return address(0);
}
function _delete(VaultStorage storage vaultStorage, uint256 id) private {
delete vaultStorage.whitelistedRecipient[id];
delete vaultStorage.whitelistedRecipientDeferred[id];
if (vaultStorage.whitelistedRecipientChain[id] != 0) {
delete vaultStorage.whitelistedRecipientChain[id];
delete vaultStorage.whitelistedRecipientAccount[id];
}
}
function sendToWhitelistedRecipientOne(uint256 id, address asset, uint256 amount) external {
VaultStorage storage vaultStorage = BittyStorage.vault();
PaymentCore.onlyInitialized(vaultStorage);
address recipient = _sendToWhitelistedRecipient(vaultStorage, id, asset, amount);
emit IBittyV1Owner.WhitelistedRecipientPaid(id, recipient, asset, amount);
}
/**
* The address entry `id` pays to, if it can be paid right now — the same test every payout to a
* whitelisted recipient passes, for assets the vault hands over itself (an ERC-721) rather than
* through {PaymentCore-payOut}. Settles a landed removal and records a verdict a lock made final,
* exactly as a payout does.
*/
function payableRecipient(uint256 id) external returns (address recipient) {
VaultStorage storage vaultStorage = BittyStorage.vault();
PaymentCore.onlyInitialized(vaultStorage);
return _payableHere(vaultStorage, id);
}
/**
* The address entry `id` pays to on `destinationChainId`, if it is on that chain (or on every
* EVM chain, and that one is EVM) and can be paid right now: the same test as
* {payableRecipient}, for the bridge that pays it. Which chains a bridge can reach at all is
* the guard's routes' to say, and which of them are EVM the guard's {EVM_CHAIN_KEY} marks.
*/
function payableRecipientOn(uint256 id, uint256 destinationChainId) external returns (bytes32 recipient) {
VaultStorage storage vaultStorage = BittyStorage.vault();
PaymentCore.onlyInitialized(vaultStorage);
uint256 chainId = vaultStorage.whitelistedRecipientChain[id];
bool reaches = chainId == ANY_EVM_CHAIN
? IBittyV1Guard(BITTY_GUARD).getUint(keccak256(abi.encode(EVM_CHAIN_KEY, destinationChainId))) == 1
: chainId != 0 && chainId == destinationChainId;
if (!reaches || destinationChainId == block.chainid) revert WhitelistedRecipientWrongChain();
recipient = _account(vaultStorage, id, _payableRecipient(vaultStorage, id));
}
/**
* Whether an entry on `chainId` is paid on this chain: one here, or one on every EVM chain.
*/
function _here(uint256 chainId) private pure returns (bool) {
return chainId == 0 || chainId == ANY_EVM_CHAIN;
}
function _sendToWhitelistedRecipient(VaultStorage storage vaultStorage, uint256 id, address asset, uint256 amount)
private
returns (address recipient)
{
if (amount == 0) revert AmountIsZero();
recipient = _payableHere(vaultStorage, id);
PaymentCore.payOut(vaultStorage, asset, amount, recipient);
}
/**
* {_payableRecipient} for a payout on this chain, which an entry on another chain never takes.
*/
function _payableHere(VaultStorage storage vaultStorage, uint256 id) private returns (address) {
if (!_here(vaultStorage.whitelistedRecipientChain[id])) revert WhitelistedRecipientWrongChain();
return _payableRecipient(vaultStorage, id);
}
function _payableRecipient(VaultStorage storage vaultStorage, uint256 id) private returns (address recipient) {
WhitelistEntry storage entry = vaultStorage.whitelistedRecipient[id];
recipient = entry.recipient;
if (entry.removeAt != 0) recipient = _settle(vaultStorage, id, entry);
if (recipient == address(0)) revert WhitelistedRecipientNotFound();
Deferred memory deferred = vaultStorage.whitelistedRecipientDeferred[id];
PaymentCore.requireProtectionElapsed(deferred.effectiveAt);
if (LockLib.requireHonoured(deferred.lockEpoch, deferred.effectiveAt)) {
vaultStorage.whitelistedRecipientDeferred[id].lockEpoch = LockLib.SETTLED;
}
}
/**
* The entries as they stand; zeros for an entry that is gone, including one whose queued
* removal has taken effect.
*/
function getWhitelistedRecipients(uint256[] calldata ids) external view returns (address[] memory recipients) {
VaultStorage storage vaultStorage = BittyStorage.vault();
recipients = new address[](ids.length);
for (uint256 i; i < ids.length; ++i) {
WhitelistEntry memory entry = vaultStorage.whitelistedRecipient[ids[i]];
if (!_removed(entry)) recipients[i] = entry.recipient;
}
}
/**
* When each entry's queued removal takes effect; 0 where none is waiting.
*/
function getWhitelistedRecipientRemovals(uint256[] calldata ids) external view returns (uint64[] memory removeAts) {
VaultStorage storage vaultStorage = BittyStorage.vault();
removeAts = new uint64[](ids.length);
for (uint256 i; i < ids.length; ++i) {
WhitelistEntry memory entry = vaultStorage.whitelistedRecipient[ids[i]];
if (block.timestamp < entry.removeAt && LockLib.honoured(entry.removeEpoch, entry.removeAt)) {
removeAts[i] = entry.removeAt;
}
}
}
function getWhitelist(uint256 fromId, uint256 count)
external
view
returns (uint256 lastId, WhitelistEntryView[] memory entries)
{
VaultStorage storage vaultStorage = BittyStorage.vault();
lastId = vaultStorage.nextWhitelistedRecipientId;
if (fromId == 0) fromId = 1;
if (fromId > lastId) return (lastId, entries);
uint256 n = lastId - fromId + 1;
if (count < n) n = count;
entries = new WhitelistEntryView[](n);
for (uint256 i; i < n; ++i) {
entries[i] = _view(vaultStorage, fromId + i);
}
}
/**
* Mirrors the payout: a removal that has landed wins, then one still queued (the entry stays
* payable until it lands), then a lock that voided the entry before it matured, then its window.
*/
function _view(VaultStorage storage vaultStorage, uint256 id) private view returns (WhitelistEntryView memory v) {
WhitelistEntry memory entry = vaultStorage.whitelistedRecipient[id];
v.id = id;
if (entry.recipient == address(0) || _removed(entry)) return v; // WHITELIST_REMOVED
Deferred memory deferred = vaultStorage.whitelistedRecipientDeferred[id];
v.recipient = entry.recipient;
v.chainId = vaultStorage.whitelistedRecipientChain[id];
v.account = _account(vaultStorage, id, entry.recipient);
v.effectiveAt = deferred.effectiveAt;
if (entry.removeAt != 0 && LockLib.honoured(entry.removeEpoch, entry.removeAt)) {
v.removeAt = entry.removeAt;
v.status = WHITELIST_REMOVAL_QUEUED;
} else if (!LockLib.honoured(deferred.lockEpoch, deferred.effectiveAt)) {
v.status = WHITELIST_VOIDED;
} else if (block.timestamp < deferred.effectiveAt) {
v.status = WHITELIST_PENDING;
} else {
v.status = WHITELIST_PAYABLE;
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {
"src/BittyV1Vault.sol": {
"DeFiLogic": "0xe5f77a5f1b0dd4044f185e5b7c72f77f19560634",
"RiskLogic": "0x07adef1a8391eae8a451c68888d97324b0e4a5c9",
"WhitelistLogic": "0x6031f509b9507023dbd5d5e320bdebbdcd445c76",
"TokenAsGasLogic": "0xc9f9bbedb7c9fc62548dae6c9419ea416909dad2"
}
},
"optimizer": {
"runs": 10000,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"guard-contracts/=lib/guard-contracts/",
"protocol-contracts/=lib/protocol-contracts/",
"solmate/=lib/solmate/src/",
"safe-contracts/=lib/safe-smart-account/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"ds-test/=lib/solmate/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/protocol-contracts/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"safe-smart-account/=lib/safe-smart-account/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.