Verified contractPartialMIT
BridgeCore
Address0x0ec8deeb01e7a7b43818dffa670f0460cf292dae
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.29
- Same code
Only this contract
Details
- Compiler
- solc 0.8.29+commit.ab55807c
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- prague
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,017,996
- Creation transaction
- 0xcb72814bb0…00befe58d3
19 files
- src/BridgeCore.solmain13.04 KB
- ../lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol3.15 KB
- ../lib/openzeppelin-contracts-upgradeable/contracts/interfaces/draft-IERC1822Upgradeable.sol890 B
- ../lib/openzeppelin-contracts-upgradeable/contracts/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol7.84 KB
- ../lib/openzeppelin-contracts-upgradeable/contracts/proxy/beacon/IBeaconUpgradeable.sol461 B
- ../lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol6.63 KB
- ../lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol4.76 KB
- ../lib/openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol8.28 KB
- ../lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.35 KB
- ../lib/openzeppelin-contracts-upgradeable/contracts/utils/StorageSlotUpgradeable.sol2.68 KB
- ../lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- src/BridgeStructs.sol2.28 KB
- src/ChannelDeployer.sol1.71 KB
- src/ChannelManager.sol35.31 KB
- src/DAppManager.sol23.81 KB
- src/generated/TokamakEnvironment.sol527 B
- src/interfaces/IChannelRegistry.sol429 B
- src/interfaces/IGrothVerifier.sol364 B
- src/interfaces/ITokamakVerifier.sol482 B
src/BridgeCore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import { Initializable } from "@openzeppelin-upgradeable/proxy/utils/Initializable.sol";
import { OwnableUpgradeable } from "@openzeppelin-upgradeable/access/OwnableUpgradeable.sol";
import { UUPSUpgradeable } from "@openzeppelin-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
import { BridgeStructs } from "./BridgeStructs.sol";
import { DAppManager } from "./DAppManager.sol";
import { ChannelManager } from "./ChannelManager.sol";
import { ChannelDeployer } from "./ChannelDeployer.sol";
import { IGrothVerifier } from "./interfaces/IGrothVerifier.sol";
import { ITokamakVerifier } from "./interfaces/ITokamakVerifier.sol";
import { IChannelRegistry } from "./interfaces/IChannelRegistry.sol";
contract BridgeCore is Initializable, OwnableUpgradeable, UUPSUpgradeable, IChannelRegistry {
uint256 internal constant MAX_MANAGED_STORAGES = 11;
uint16 internal constant BPS_DENOMINATOR = 10_000;
address internal constant TOKAMAK_NETWORK_TOKEN_MAINNET =
0x2be5e8c109e2197D077D13A82dAead6a9b3433C5;
address internal constant TOKAMAK_NETWORK_TOKEN_SEPOLIA =
0xa30fe40285B8f5c0457DbC3B7C8A280373c40044;
error UnknownChannel(uint256 channelId);
error ChannelAlreadyExists(uint256 channelId);
error TooManyManagedStorages(uint256 actualCount, uint256 maxSupported);
error InvalidDAppManager();
error InvalidChannelDeployer();
error InvalidChannelManager(address manager);
error InvalidGrothVerifier();
error InvalidTokamakVerifier();
error InvalidBridgeTokenVault();
error BridgeTokenVaultAlreadySet();
error UnsupportedCanonicalAssetChain(uint256 chainId);
error InvalidJoinTollRefundSchedule();
error DAppMetadataDigestMismatch(uint256 dappId, bytes32 expectedDigest, bytes32 actualDigest);
struct ChannelDeployment {
bool exists;
uint256 dappId;
address leader;
address asset;
address manager;
address bridgeTokenVault;
bytes32 aPubBlockHash;
bytes32 dappMetadataDigestSchema;
bytes32 dappMetadataDigest;
}
DAppManager public dAppManager;
ChannelDeployer public channelDeployer;
IGrothVerifier public grothVerifier;
ITokamakVerifier public tokamakVerifier;
address public bridgeTokenVault;
uint64 public defaultJoinTollRefundCutoff1;
uint64 public defaultJoinTollRefundCutoff2;
uint64 public defaultJoinTollRefundCutoff3;
uint16 public defaultJoinTollRefundBps1;
uint16 public defaultJoinTollRefundBps2;
uint16 public defaultJoinTollRefundBps3;
uint16 public defaultJoinTollRefundBps4;
mapping(uint256 => ChannelDeployment) private _channels;
event ChannelCreated(
uint256 indexed channelId, uint256 indexed dappId, address manager, address bridgeTokenVault
);
event BridgeTokenVaultBound(address indexed bridgeTokenVault);
event ChannelDeployerUpdated(address indexed channelDeployer);
event GrothVerifierUpdated(address indexed grothVerifier);
event TokamakVerifierUpdated(address indexed tokamakVerifier);
event JoinTollRefundScheduleUpdated(
uint64 cutoff1,
uint16 bps1,
uint64 cutoff2,
uint16 bps2,
uint64 cutoff3,
uint16 bps3,
uint16 bps4
);
constructor() {
_disableInitializers();
}
function initialize(
address initialOwner,
DAppManager dAppManager_,
ChannelDeployer channelDeployer_,
IGrothVerifier grothVerifier_,
ITokamakVerifier tokamakVerifier_
) external initializer {
if (address(dAppManager_) == address(0)) {
revert InvalidDAppManager();
}
if (address(channelDeployer_) == address(0) || address(channelDeployer_).code.length == 0) {
revert InvalidChannelDeployer();
}
if (address(grothVerifier_) == address(0)) revert InvalidGrothVerifier();
if (address(tokamakVerifier_) == address(0)) revert InvalidTokamakVerifier();
__Ownable_init();
__UUPSUpgradeable_init();
if (initialOwner != _msgSender()) {
_transferOwnership(initialOwner);
}
dAppManager = dAppManager_;
channelDeployer = channelDeployer_;
grothVerifier = grothVerifier_;
tokamakVerifier = tokamakVerifier_;
_setJoinTollRefundSchedule(6 hours, 7_500, 24 hours, 5_000, 3 days, 2_500, 0);
}
function setChannelDeployer(ChannelDeployer channelDeployer_) external onlyOwner {
if (address(channelDeployer_) == address(0) || address(channelDeployer_).code.length == 0) {
revert InvalidChannelDeployer();
}
channelDeployer = channelDeployer_;
emit ChannelDeployerUpdated(address(channelDeployer_));
}
function setGrothVerifier(IGrothVerifier grothVerifier_) external onlyOwner {
if (address(grothVerifier_) == address(0)) revert InvalidGrothVerifier();
grothVerifier = grothVerifier_;
emit GrothVerifierUpdated(address(grothVerifier_));
}
function setTokamakVerifier(ITokamakVerifier tokamakVerifier_) external onlyOwner {
if (address(tokamakVerifier_) == address(0)) revert InvalidTokamakVerifier();
tokamakVerifier = tokamakVerifier_;
emit TokamakVerifierUpdated(address(tokamakVerifier_));
}
function bindBridgeTokenVault(address bridgeTokenVault_) external onlyOwner {
if (bridgeTokenVault_ == address(0)) revert InvalidBridgeTokenVault();
if (bridgeTokenVault != address(0)) revert BridgeTokenVaultAlreadySet();
bridgeTokenVault = bridgeTokenVault_;
emit BridgeTokenVaultBound(bridgeTokenVault_);
}
function setJoinTollRefundSchedule(
uint64 cutoff1,
uint16 bps1,
uint64 cutoff2,
uint16 bps2,
uint64 cutoff3,
uint16 bps3,
uint16 bps4
) external onlyOwner {
_setJoinTollRefundSchedule(cutoff1, bps1, cutoff2, bps2, cutoff3, bps3, bps4);
}
function canonicalAsset() public view returns (address) {
if (block.chainid == 1) {
return TOKAMAK_NETWORK_TOKEN_MAINNET;
}
if (block.chainid == 11155111 || block.chainid == 31337) {
return TOKAMAK_NETWORK_TOKEN_SEPOLIA;
}
revert UnsupportedCanonicalAssetChain(block.chainid);
}
function createChannel(
uint256 channelId,
uint256 dappId,
uint256 initialJoinToll,
bytes32 expectedDAppMetadataDigest
) external returns (address manager, address boundBridgeTokenVault) {
address leader = msg.sender;
IERC20 asset = IERC20(canonicalAsset());
if (_channels[channelId].exists) revert ChannelAlreadyExists(channelId);
if (bridgeTokenVault == address(0)) revert InvalidBridgeTokenVault();
uint256 managedStorageCount = dAppManager.getManagedStorageCount(dappId);
if (managedStorageCount > MAX_MANAGED_STORAGES) {
revert TooManyManagedStorages(managedStorageCount, MAX_MANAGED_STORAGES);
}
DAppManager.DAppInfo memory dAppInfo = dAppManager.getDAppInfo(dappId);
if (dAppInfo.metadataDigest != expectedDAppMetadataDigest) {
revert DAppMetadataDigestMismatch(
dappId, expectedDAppMetadataDigest, dAppInfo.metadataDigest
);
}
uint256 channelTokenVaultTreeIndex = dAppInfo.channelTokenVaultTreeIndex;
BridgeStructs.DAppVerifierSnapshot memory verifierSnapshot =
dAppManager.getDAppVerifierSnapshot(dappId);
address channelManagerAddress = channelDeployer.deployChannelManager(
channelId,
dappId,
leader,
channelTokenVaultTreeIndex,
address(this),
verifierSnapshot,
dAppInfo.metadataDigestSchema,
dAppInfo.metadataDigest,
dAppInfo.functionRoot,
initialJoinToll,
defaultJoinTollRefundCutoff1,
defaultJoinTollRefundBps1,
defaultJoinTollRefundCutoff2,
defaultJoinTollRefundBps2,
defaultJoinTollRefundCutoff3,
defaultJoinTollRefundBps3,
defaultJoinTollRefundBps4,
dAppManager,
managedStorageCount
);
ChannelManager channelManager = ChannelManager(channelManagerAddress);
_validateChannelManager(
channelManager,
channelId,
dappId,
leader,
channelTokenVaultTreeIndex,
verifierSnapshot,
dAppInfo.metadataDigestSchema,
dAppInfo.metadataDigest,
dAppInfo.functionRoot,
initialJoinToll
);
channelManager.bindBridgeTokenVault(bridgeTokenVault);
bytes32 channelAPubBlockHash = channelManager.aPubBlockHash();
_channels[channelId] = ChannelDeployment({
exists: true,
dappId: dappId,
leader: leader,
asset: address(asset),
manager: address(channelManager),
bridgeTokenVault: bridgeTokenVault,
aPubBlockHash: channelAPubBlockHash,
dappMetadataDigestSchema: dAppInfo.metadataDigestSchema,
dappMetadataDigest: dAppInfo.metadataDigest
});
emit ChannelCreated(channelId, dappId, address(channelManager), bridgeTokenVault);
return (address(channelManager), bridgeTokenVault);
}
function getChannel(uint256 channelId) external view returns (ChannelDeployment memory) {
if (!_channels[channelId].exists) revert UnknownChannel(channelId);
return _channels[channelId];
}
function getChannelManager(uint256 channelId) external view override returns (address) {
if (!_channels[channelId].exists) revert UnknownChannel(channelId);
return _channels[channelId].manager;
}
function _authorizeUpgrade(address) internal override onlyOwner { }
function _validateChannelManager(
ChannelManager channelManager,
uint256 channelId,
uint256 dappId,
address leader,
uint256 channelTokenVaultTreeIndex,
BridgeStructs.DAppVerifierSnapshot memory verifierSnapshot,
bytes32 dappMetadataDigestSchema,
bytes32 dappMetadataDigest,
bytes32 functionRoot,
uint256 initialJoinToll
) private view {
address manager = address(channelManager);
if (
manager.code.length == 0 || channelManager.bridgeCore() != address(this)
|| channelManager.channelId() != channelId || channelManager.dappId() != dappId
|| channelManager.leader() != leader
|| channelManager.channelTokenVaultTreeIndex() != channelTokenVaultTreeIndex
|| channelManager.dappMetadataDigestSchema() != dappMetadataDigestSchema
|| channelManager.dappMetadataDigest() != dappMetadataDigest
|| channelManager.functionRoot() != functionRoot
|| address(channelManager.grothVerifier()) != verifierSnapshot.grothVerifier
|| address(channelManager.tokamakVerifier()) != verifierSnapshot.tokamakVerifier
|| channelManager.joinToll() != initialJoinToll
|| channelManager.joinTollRefundCutoff1() != defaultJoinTollRefundCutoff1
|| channelManager.joinTollRefundBps1() != defaultJoinTollRefundBps1
|| channelManager.joinTollRefundCutoff2() != defaultJoinTollRefundCutoff2
|| channelManager.joinTollRefundBps2() != defaultJoinTollRefundBps2
|| channelManager.joinTollRefundCutoff3() != defaultJoinTollRefundCutoff3
|| channelManager.joinTollRefundBps3() != defaultJoinTollRefundBps3
|| channelManager.joinTollRefundBps4() != defaultJoinTollRefundBps4
) {
revert InvalidChannelManager(manager);
}
}
function _setJoinTollRefundSchedule(
uint64 cutoff1,
uint16 bps1,
uint64 cutoff2,
uint16 bps2,
uint64 cutoff3,
uint16 bps3,
uint16 bps4
) private {
if (
cutoff1 == 0 || cutoff1 >= cutoff2 || cutoff2 >= cutoff3 || bps1 > BPS_DENOMINATOR
|| bps2 > BPS_DENOMINATOR || bps3 > BPS_DENOMINATOR || bps4 > BPS_DENOMINATOR
|| bps1 < bps2 || bps2 < bps3 || bps3 < bps4
) {
revert InvalidJoinTollRefundSchedule();
}
defaultJoinTollRefundCutoff1 = cutoff1;
defaultJoinTollRefundCutoff2 = cutoff2;
defaultJoinTollRefundCutoff3 = cutoff3;
defaultJoinTollRefundBps1 = bps1;
defaultJoinTollRefundBps2 = bps2;
defaultJoinTollRefundBps3 = bps3;
defaultJoinTollRefundBps4 = bps4;
emit JoinTollRefundScheduleUpdated(cutoff1, bps1, cutoff2, bps2, cutoff3, bps3, bps4);
}
}
../lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../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.
*
* By default, the owner account will be the one that deploys the contract. 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 {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing 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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
../lib/openzeppelin-contracts-upgradeable/contracts/interfaces/draft-IERC1822Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822ProxiableUpgradeable {
/**
* @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-upgradeable/contracts/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
../lib/openzeppelin-contracts-upgradeable/contracts/proxy/beacon/IBeaconUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
../lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @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]
* ```
* 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 Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 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 functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_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 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_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() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @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 {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized < type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
../lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./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.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @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() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @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() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
/**
* @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 override notDelegated returns (bytes32) {
return _IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
../lib/openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
../lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../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;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
../lib/openzeppelin-contracts-upgradeable/contracts/utils/StorageSlotUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 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
}
}
}
../lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
src/BridgeStructs.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
library BridgeStructs {
struct NoteReceivePubKey {
bytes32 x;
uint8 yParity;
}
struct ChannelTokenVaultRegistration {
bool exists;
address l2Address;
bytes32 channelTokenVaultKey;
uint256 leafIndex;
uint256 joinTollPaid;
uint64 joinedAt;
NoteReceivePubKey noteReceivePubKey;
bool isZeroBalance;
}
struct EventLogMetadata {
uint16 startOffsetWords;
uint8 topicCount;
}
struct StorageMetadata {
address storageAddr;
bytes32[] preAllocatedKeys;
uint8[] userStorageSlots;
bool isChannelTokenVaultStorage;
}
struct InstanceLayout {
uint8 entryContractOffsetWords;
uint8 functionSigOffsetWords;
uint8 currentRootVectorOffsetWords;
uint8 updatedRootVectorOffsetWords;
EventLogMetadata[] eventLogs;
}
struct DAppFunctionMetadata {
address entryContract;
bytes4 functionSig;
bytes32 preprocessInputHash;
InstanceLayout instanceLayout;
}
struct FunctionMetadataProof {
DAppFunctionMetadata metadata;
bytes32[] siblings;
}
struct DAppVerifierSnapshot {
address grothVerifier;
string grothVerifierCompatibleBackendVersion;
address tokamakVerifier;
string tokamakVerifierCompatibleBackendVersion;
}
struct GrothProof {
uint256[4] pA;
uint256[8] pB;
uint256[4] pC;
}
struct FunctionConfig {
bytes32 preprocessInputHash;
uint8 entryContractOffsetWords;
uint8 functionSigOffsetWords;
uint8 currentRootVectorOffsetWords;
uint8 updatedRootVectorOffsetWords;
}
struct GrothUpdate {
bytes32[] currentRootVector;
bytes32 updatedRoot;
bytes32 currentUserKey;
uint256 currentUserValue;
bytes32 updatedUserKey;
uint256 updatedUserValue;
}
struct TokamakProofPayload {
uint128[] proofPart1;
uint256[] proofPart2;
uint128[] functionPreprocessPart1;
uint256[] functionPreprocessPart2;
uint256[] aPubUser;
uint256[] aPubBlock;
}
}
src/ChannelDeployer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import { BridgeStructs } from "./BridgeStructs.sol";
import { ChannelManager } from "./ChannelManager.sol";
import { DAppManager } from "./DAppManager.sol";
contract ChannelDeployer {
function deployChannelManager(
uint256 channelId,
uint256 dappId,
address leader,
uint256 channelTokenVaultTreeIndex,
address bridgeCore,
BridgeStructs.DAppVerifierSnapshot calldata verifierSnapshot,
bytes32 dappMetadataDigestSchema,
bytes32 dappMetadataDigest,
bytes32 functionRoot,
uint256 initialJoinToll,
uint64 joinTollRefundCutoff1,
uint16 joinTollRefundBps1,
uint64 joinTollRefundCutoff2,
uint16 joinTollRefundBps2,
uint64 joinTollRefundCutoff3,
uint16 joinTollRefundBps3,
uint16 joinTollRefundBps4,
DAppManager dAppManager,
uint256 expectedManagedStorageCount
) external returns (address manager) {
ChannelManager channelManager = new ChannelManager(
channelId,
dappId,
leader,
channelTokenVaultTreeIndex,
bridgeCore,
verifierSnapshot,
dappMetadataDigestSchema,
dappMetadataDigest,
functionRoot,
initialJoinToll,
joinTollRefundCutoff1,
joinTollRefundBps1,
joinTollRefundCutoff2,
joinTollRefundBps2,
joinTollRefundCutoff3,
joinTollRefundBps3,
joinTollRefundBps4,
dAppManager,
expectedManagedStorageCount
);
return address(channelManager);
}
}
src/ChannelManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import { BridgeStructs } from "./BridgeStructs.sol";
import { DAppManager } from "./DAppManager.sol";
import { TokamakEnvironment } from "./generated/TokamakEnvironment.sol";
import { IGrothVerifier } from "./interfaces/IGrothVerifier.sol";
import { ITokamakVerifier } from "./interfaces/ITokamakVerifier.sol";
contract ChannelManager {
uint256 internal constant TOKAMAK_APUB_BLOCK_LENGTH =
TokamakEnvironment.TOKAMAK_APUB_BLOCK_LENGTH;
uint256 internal constant TOKAMAK_PREVIOUS_BLOCK_HASHES =
TokamakEnvironment.TOKAMAK_PREVIOUS_BLOCK_HASHES;
uint256 internal constant TOKEN_VAULT_MT_LEAF_COUNT = TokamakEnvironment.MAX_MT_LEAVES;
uint256 internal constant SPLIT_WORD_SIZE = 2;
uint16 internal constant BPS_DENOMINATOR = 10_000;
bytes32 internal constant LIQUID_BALANCE_STORAGE_WRITE_OBSERVED_TOPIC =
keccak256("LiquidBalanceStorageWriteObserved(address,bytes32)");
bytes32 private constant FUNCTION_ITEM_DOMAIN = keccak256("dapp.metadata.v1.function-item");
bytes32 private constant FUNCTION_MERKLE_NODE_DOMAIN =
keccak256("dapp.metadata.v1.function-merkle-node");
bytes32 private constant INSTANCE_LAYOUT_DOMAIN = keccak256("dapp.metadata.v1.instance-layout");
bytes32 private constant EVENT_LOG_ROOT_DOMAIN = keccak256("dapp.metadata.v1.event-log-root");
bytes32 private constant EVENT_LOG_ITEM_DOMAIN = keccak256("dapp.metadata.v1.event-log-item");
error OnlyBridgeCore();
error OnlyBridgeTokenVault();
error OnlyLeader();
error BridgeTokenVaultAlreadySet();
error ManagedStorageCountMismatch(uint256 expectedCount, uint256 actualCount);
error UnexpectedCurrentRootVector();
error UnsupportedChannelFunction(address entryContract, bytes4 functionSig);
error InvalidFunctionMetadataProof(bytes32 leaf, bytes32 expectedRoot);
error TokamakProofRejected();
error InvalidChannelTokenVaultTreeIndex();
error PreprocessInputHashMismatch(bytes32 expectedHash, bytes32 actualHash);
error APubBlockHashMismatch(bytes32 expectedHash, bytes32 actualHash);
error APubBlockLengthMismatch(uint256 expectedLength, uint256 actualLength);
error APubUserTooShort(uint256 expectedLength, uint256 actualLength);
error APubUserWordOutOfRange(uint256 index, uint256 value);
error EntryContractPublicInputOutOfRange(uint256 value);
error FunctionSigPublicInputOutOfRange(uint256 value);
error InvalidL2Address();
error ChannelTokenVaultIdentityAlreadyRegistered(address user);
error ChannelTokenVaultKeyAlreadyRegistered(bytes32 key);
error ChannelTokenVaultLeafIndexAlreadyRegistered(uint256 leafIndex);
error ChannelTokenVaultL2AddressAlreadyRegistered(address l2Address);
error ChannelTokenVaultLeafIndexOutOfRange(uint256 leafIndex);
error ChannelTokenVaultLeafIndexMismatch(uint256 expectedLeafIndex, uint256 actualLeafIndex);
error InvalidL1Address();
error InvalidNoteReceivePubKey();
error InvalidNoteReceivePubKeyYParity(uint8 yParity);
error ChannelTokenVaultIdentityNotRegistered(address user);
error ChannelTokenVaultBalanceNotZero(address user);
error ChannelTokenVaultKeyNotRegistered(bytes32 key);
error ChannelTokenVaultL2AddressNotRegistered(address l2Address);
error UnexpectedChannelTokenVaultStorageAddress(address expected, address actual);
error InvalidJoinTollRefundSchedule();
error UnsupportedObservedEventTopicCount(uint8 topicCount);
error InvalidObservedEventBoundary(uint16 startOffsetWords, uint256 endOffsetWords);
error InvalidObservedEventDataLength(uint16 startOffsetWords, uint256 dataWordLength);
error InvalidLiquidBalanceObservedEventDataLength(uint256 actualLength);
uint256 public immutable channelId;
uint256 public immutable dappId;
uint256 public genesisBlockNumber;
address public immutable leader;
bytes32 public immutable aPubBlockHash;
uint256 public immutable channelTokenVaultTreeIndex;
address public immutable channelTokenVaultStorageAddress;
address public immutable bridgeCore;
IGrothVerifier public immutable grothVerifier;
ITokamakVerifier public immutable tokamakVerifier;
bytes32 public immutable dappMetadataDigestSchema;
bytes32 public immutable dappMetadataDigest;
bytes32 public immutable functionRoot;
string private _grothVerifierCompatibleBackendVersion;
string private _tokamakVerifierCompatibleBackendVersion;
uint64 public immutable joinTollRefundCutoff1;
uint64 public immutable joinTollRefundCutoff2;
uint64 public immutable joinTollRefundCutoff3;
uint16 public immutable joinTollRefundBps1;
uint16 public immutable joinTollRefundBps2;
uint16 public immutable joinTollRefundBps3;
uint16 public immutable joinTollRefundBps4;
address public bridgeTokenVault;
bytes32 public currentRootVectorHash;
uint256 public joinToll;
address[] private _managedStorageAddresses;
mapping(address => BridgeStructs.ChannelTokenVaultRegistration) private
_channelTokenVaultRegistrations;
mapping(bytes32 => address) private _channelTokenVaultKeyOwners;
mapping(uint256 => address) private _channelTokenVaultLeafOwners;
mapping(address => address) private _channelTokenVaultL2AddressOwners;
event BridgeTokenVaultBound(address indexed bridgeTokenVault);
event JoinTollUpdated(uint256 previousJoinToll, uint256 newJoinToll);
event ChannelTokenVaultIdentityRegistered(
address indexed l1Address,
address indexed l2Address,
bytes32 indexed channelTokenVaultKey,
uint256 leafIndex,
uint256 joinTollPaid,
uint64 joinedAt,
bytes32 noteReceivePubKeyX,
uint8 noteReceivePubKeyYParity
);
event ChannelTokenVaultIdentityExited(address indexed l1Address, uint256 indexed leafIndex);
event CurrentRootVectorObserved(bytes32 indexed rootVectorHash, bytes32[] rootVector);
constructor(
uint256 channelId_,
uint256 dappId_,
address leader_,
uint256 channelTokenVaultTreeIndex_,
address bridgeCore_,
BridgeStructs.DAppVerifierSnapshot memory verifierSnapshot_,
bytes32 dappMetadataDigestSchema_,
bytes32 dappMetadataDigest_,
bytes32 functionRoot_,
uint256 initialJoinToll_,
uint64 joinTollRefundCutoff1_,
uint16 joinTollRefundBps1_,
uint64 joinTollRefundCutoff2_,
uint16 joinTollRefundBps2_,
uint64 joinTollRefundCutoff3_,
uint16 joinTollRefundBps3_,
uint16 joinTollRefundBps4_,
DAppManager dAppManager_,
uint256 expectedManagedStorageCount_
) {
channelId = channelId_;
dappId = dappId_;
genesisBlockNumber = block.number;
leader = leader_;
bridgeCore = bridgeCore_;
grothVerifier = IGrothVerifier(verifierSnapshot_.grothVerifier);
tokamakVerifier = ITokamakVerifier(verifierSnapshot_.tokamakVerifier);
dappMetadataDigestSchema = dappMetadataDigestSchema_;
dappMetadataDigest = dappMetadataDigest_;
functionRoot = functionRoot_;
_grothVerifierCompatibleBackendVersion =
verifierSnapshot_.grothVerifierCompatibleBackendVersion;
_tokamakVerifierCompatibleBackendVersion =
verifierSnapshot_.tokamakVerifierCompatibleBackendVersion;
if (
joinTollRefundCutoff1_ == 0 || joinTollRefundCutoff1_ >= joinTollRefundCutoff2_
|| joinTollRefundCutoff2_ >= joinTollRefundCutoff3_
|| joinTollRefundBps1_ > BPS_DENOMINATOR || joinTollRefundBps2_ > BPS_DENOMINATOR
|| joinTollRefundBps3_ > BPS_DENOMINATOR || joinTollRefundBps4_ > BPS_DENOMINATOR
|| joinTollRefundBps1_ < joinTollRefundBps2_
|| joinTollRefundBps2_ < joinTollRefundBps3_
|| joinTollRefundBps3_ < joinTollRefundBps4_
) {
revert InvalidJoinTollRefundSchedule();
}
joinToll = initialJoinToll_;
joinTollRefundCutoff1 = joinTollRefundCutoff1_;
joinTollRefundCutoff2 = joinTollRefundCutoff2_;
joinTollRefundCutoff3 = joinTollRefundCutoff3_;
joinTollRefundBps1 = joinTollRefundBps1_;
joinTollRefundBps2 = joinTollRefundBps2_;
joinTollRefundBps3 = joinTollRefundBps3_;
joinTollRefundBps4 = joinTollRefundBps4_;
address[] memory managedStorageAddresses = dAppManager_.getManagedStorageAddresses(dappId_);
if (managedStorageAddresses.length != expectedManagedStorageCount_) {
revert ManagedStorageCountMismatch(
expectedManagedStorageCount_, managedStorageAddresses.length
);
}
bytes32[] memory initialRootVector = new bytes32[](managedStorageAddresses.length);
for (uint256 i = 0; i < managedStorageAddresses.length; i++) {
initialRootVector[i] = TokamakEnvironment.ZERO_FILLED_TREE_ROOT;
}
uint256[] memory aPubBlock = new uint256[](TOKAMAK_APUB_BLOCK_LENGTH);
uint256 selfBalance;
assembly ("memory-safe") {
selfBalance := selfbalance()
}
aPubBlock[0] = uint256(uint128(uint256(uint160(address(block.coinbase)))));
aPubBlock[1] = uint256(uint160(address(block.coinbase))) >> 128;
aPubBlock[2] = uint256(uint128(block.timestamp));
aPubBlock[3] = block.timestamp >> 128;
aPubBlock[4] = uint256(uint128(block.number));
aPubBlock[5] = block.number >> 128;
aPubBlock[6] = uint256(uint128(uint256(block.prevrandao)));
aPubBlock[7] = uint256(block.prevrandao) >> 128;
aPubBlock[8] = uint256(uint128(block.gaslimit));
aPubBlock[9] = block.gaslimit >> 128;
aPubBlock[10] = uint256(uint128(block.chainid));
aPubBlock[11] = block.chainid >> 128;
aPubBlock[12] = uint256(uint128(selfBalance));
aPubBlock[13] = selfBalance >> 128;
aPubBlock[14] = uint256(uint128(block.basefee));
aPubBlock[15] = block.basefee >> 128;
uint256 offsetWords = 16;
for (uint256 i = 1; i <= TOKAMAK_PREVIOUS_BLOCK_HASHES; i++) {
uint256 blockHashNumber = block.number > i ? block.number - i : 0;
uint256 blockHashValue = uint256(blockhash(blockHashNumber));
aPubBlock[offsetWords] = uint256(uint128(blockHashValue));
aPubBlock[offsetWords + 1] = blockHashValue >> 128;
unchecked {
offsetWords += SPLIT_WORD_SIZE;
}
}
aPubBlockHash = keccak256(abi.encode(aPubBlock));
if (channelTokenVaultTreeIndex_ >= initialRootVector.length) {
revert InvalidChannelTokenVaultTreeIndex();
}
channelTokenVaultTreeIndex = channelTokenVaultTreeIndex_;
channelTokenVaultStorageAddress = managedStorageAddresses[channelTokenVaultTreeIndex_];
currentRootVectorHash = keccak256(abi.encode(initialRootVector));
for (uint256 i = 0; i < managedStorageAddresses.length; i++) {
_managedStorageAddresses.push(managedStorageAddresses[i]);
}
}
function grothVerifierCompatibleBackendVersion() external view returns (string memory) {
return _grothVerifierCompatibleBackendVersion;
}
function tokamakVerifierCompatibleBackendVersion() external view returns (string memory) {
return _tokamakVerifierCompatibleBackendVersion;
}
modifier onlyBridgeCore() {
if (msg.sender != bridgeCore) revert OnlyBridgeCore();
_;
}
modifier onlyBridgeTokenVault() {
if (msg.sender != bridgeTokenVault) revert OnlyBridgeTokenVault();
_;
}
modifier onlyLeader() {
if (msg.sender != leader) revert OnlyLeader();
_;
}
function bindBridgeTokenVault(address bridgeTokenVault_) external onlyBridgeCore {
if (bridgeTokenVault != address(0)) revert BridgeTokenVaultAlreadySet();
bridgeTokenVault = bridgeTokenVault_;
emit BridgeTokenVaultBound(bridgeTokenVault_);
}
function setJoinToll(uint256 joinToll_) external onlyLeader {
uint256 previousJoinToll = joinToll;
joinToll = joinToll_;
emit JoinTollUpdated(previousJoinToll, joinToll_);
}
function registerChannelTokenVaultIdentity(
address l1Address,
address l2Address,
bytes32 channelTokenVaultKey,
uint256 leafIndex,
BridgeStructs.NoteReceivePubKey calldata noteReceivePubKey,
uint256 joinTollPaid
) external onlyBridgeTokenVault {
if (l1Address == address(0)) {
revert InvalidL1Address();
}
if (l2Address == address(0)) revert InvalidL2Address();
if (_channelTokenVaultRegistrations[l1Address].exists) {
revert ChannelTokenVaultIdentityAlreadyRegistered(l1Address);
}
if (_channelTokenVaultL2AddressOwners[l2Address] != address(0)) {
revert ChannelTokenVaultL2AddressAlreadyRegistered(l2Address);
}
if (leafIndex >= TOKEN_VAULT_MT_LEAF_COUNT) {
revert ChannelTokenVaultLeafIndexOutOfRange(leafIndex);
}
if (noteReceivePubKey.x == bytes32(0)) {
revert InvalidNoteReceivePubKey();
}
if (noteReceivePubKey.yParity > 1) {
revert InvalidNoteReceivePubKeyYParity(noteReceivePubKey.yParity);
}
uint256 expectedLeafIndex = _deriveLeafIndexFromStorageKey(uint256(channelTokenVaultKey));
if (leafIndex != expectedLeafIndex) {
revert ChannelTokenVaultLeafIndexMismatch(expectedLeafIndex, leafIndex);
}
if (_channelTokenVaultKeyOwners[channelTokenVaultKey] != address(0)) {
revert ChannelTokenVaultKeyAlreadyRegistered(channelTokenVaultKey);
}
if (_channelTokenVaultLeafOwners[leafIndex] != address(0)) {
revert ChannelTokenVaultLeafIndexAlreadyRegistered(leafIndex);
}
_channelTokenVaultRegistrations[l1Address] = BridgeStructs.ChannelTokenVaultRegistration({
exists: true,
l2Address: l2Address,
channelTokenVaultKey: channelTokenVaultKey,
leafIndex: leafIndex,
joinTollPaid: joinTollPaid,
joinedAt: uint64(block.timestamp),
noteReceivePubKey: BridgeStructs.NoteReceivePubKey({
x: noteReceivePubKey.x, yParity: noteReceivePubKey.yParity
}),
isZeroBalance: true
});
_channelTokenVaultKeyOwners[channelTokenVaultKey] = l1Address;
_channelTokenVaultLeafOwners[leafIndex] = l1Address;
_channelTokenVaultL2AddressOwners[l2Address] = l1Address;
emit ChannelTokenVaultIdentityRegistered(
l1Address,
l2Address,
channelTokenVaultKey,
leafIndex,
joinTollPaid,
uint64(block.timestamp),
noteReceivePubKey.x,
noteReceivePubKey.yParity
);
}
function unregisterChannelTokenVaultIdentity(address l1Address)
external
onlyBridgeTokenVault
returns (bool)
{
BridgeStructs.ChannelTokenVaultRegistration memory registration =
_channelTokenVaultRegistrations[l1Address];
if (!registration.exists) revert ChannelTokenVaultIdentityNotRegistered(l1Address);
if (!registration.isZeroBalance) revert ChannelTokenVaultBalanceNotZero(l1Address);
delete _channelTokenVaultRegistrations[l1Address];
delete _channelTokenVaultKeyOwners[registration.channelTokenVaultKey];
delete _channelTokenVaultLeafOwners[registration.leafIndex];
delete _channelTokenVaultL2AddressOwners[registration.l2Address];
emit ChannelTokenVaultIdentityExited(l1Address, registration.leafIndex);
return true;
}
function getExitTollRefundQuote(address l1Address)
external
view
returns (uint256 refundAmount, uint16 refundBps)
{
BridgeStructs.ChannelTokenVaultRegistration memory registration =
_channelTokenVaultRegistrations[l1Address];
if (!registration.exists) {
return (0, 0);
}
uint256 elapsed = block.timestamp - uint256(registration.joinedAt);
if (elapsed <= joinTollRefundCutoff1) {
refundBps = joinTollRefundBps1;
} else if (elapsed <= joinTollRefundCutoff2) {
refundBps = joinTollRefundBps2;
} else if (elapsed <= joinTollRefundCutoff3) {
refundBps = joinTollRefundBps3;
} else {
refundBps = joinTollRefundBps4;
}
refundAmount = (registration.joinTollPaid * refundBps) / BPS_DENOMINATOR;
}
function executeChannelTransaction(
BridgeStructs.TokamakProofPayload calldata payload,
BridgeStructs.FunctionMetadataProof calldata functionProof
) external returns (bool) {
bytes32 actualPreprocessInputHash = keccak256(
abi.encode(payload.functionPreprocessPart1, payload.functionPreprocessPart2)
);
BridgeStructs.DAppFunctionMetadata calldata functionMetadata = functionProof.metadata;
bytes32 functionLeaf = _hashFunctionMetadata(functionMetadata);
if (!_verifyFunctionMetadataProof(functionLeaf, functionProof.siblings)) {
revert InvalidFunctionMetadataProof(functionLeaf, functionRoot);
}
BridgeStructs.FunctionConfig memory functionConfig = BridgeStructs.FunctionConfig({
preprocessInputHash: functionMetadata.preprocessInputHash,
entryContractOffsetWords: functionMetadata.instanceLayout.entryContractOffsetWords,
functionSigOffsetWords: functionMetadata.instanceLayout.functionSigOffsetWords,
currentRootVectorOffsetWords: functionMetadata.instanceLayout
.currentRootVectorOffsetWords,
updatedRootVectorOffsetWords: functionMetadata.instanceLayout
.updatedRootVectorOffsetWords
});
uint256 rootVectorLength = _managedStorageAddresses.length;
uint256 requiredLength =
functionConfig.updatedRootVectorOffsetWords + rootVectorLength * SPLIT_WORD_SIZE;
uint256 currentRootVectorRequiredLength =
functionConfig.currentRootVectorOffsetWords + rootVectorLength * SPLIT_WORD_SIZE;
if (currentRootVectorRequiredLength > requiredLength) {
requiredLength = currentRootVectorRequiredLength;
}
uint256 entryContractRequiredLength =
functionConfig.entryContractOffsetWords + SPLIT_WORD_SIZE;
if (entryContractRequiredLength > requiredLength) {
requiredLength = entryContractRequiredLength;
}
uint256 functionSigRequiredLength = functionConfig.functionSigOffsetWords + SPLIT_WORD_SIZE;
if (functionSigRequiredLength > requiredLength) {
requiredLength = functionSigRequiredLength;
}
if (payload.aPubUser.length < requiredLength) {
revert APubUserTooShort(requiredLength, payload.aPubUser.length);
}
uint256 entryContractValue =
_decodeSplitWord(payload.aPubUser, functionConfig.entryContractOffsetWords);
if (entryContractValue > type(uint160).max) {
revert EntryContractPublicInputOutOfRange(entryContractValue);
}
address entryContract = address(uint160(entryContractValue));
uint256 functionSigValue =
_decodeSplitWord(payload.aPubUser, functionConfig.functionSigOffsetWords);
if (functionSigValue > type(uint32).max) {
revert FunctionSigPublicInputOutOfRange(functionSigValue);
}
bytes4 functionSig = bytes4(uint32(functionSigValue));
if (
entryContract != functionMetadata.entryContract
|| functionSig != functionMetadata.functionSig
) {
revert UnsupportedChannelFunction(entryContract, functionSig);
}
bytes32 expectedPreprocessInputHash = functionConfig.preprocessInputHash;
if (actualPreprocessInputHash != expectedPreprocessInputHash) {
revert PreprocessInputHashMismatch(
expectedPreprocessInputHash, actualPreprocessInputHash
);
}
if (payload.aPubBlock.length != TOKAMAK_APUB_BLOCK_LENGTH) {
revert APubBlockLengthMismatch(TOKAMAK_APUB_BLOCK_LENGTH, payload.aPubBlock.length);
}
bytes32 actualAPubBlockHash = keccak256(abi.encode(payload.aPubBlock));
if (actualAPubBlockHash != aPubBlockHash) {
revert APubBlockHashMismatch(aPubBlockHash, actualAPubBlockHash);
}
bytes32[] memory currentRootVector = _decodeRootVectorFromAPubUser(
payload.aPubUser, functionConfig.currentRootVectorOffsetWords
);
if (keccak256(abi.encode(currentRootVector)) != currentRootVectorHash) {
revert UnexpectedCurrentRootVector();
}
bytes32[] memory updatedRootVector = _decodeRootVectorFromAPubUser(
payload.aPubUser, functionConfig.updatedRootVectorOffsetWords
);
bool ok = tokamakVerifier.verify(
payload.proofPart1,
payload.proofPart2,
payload.functionPreprocessPart1,
payload.functionPreprocessPart2,
payload.aPubUser,
payload.aPubBlock
);
if (!ok) revert TokamakProofRejected();
_emitObservedEventLogs(
payload.aPubUser, functionConfig, functionMetadata.instanceLayout.eventLogs
);
currentRootVectorHash = keccak256(abi.encode(updatedRootVector));
emit CurrentRootVectorObserved(currentRootVectorHash, updatedRootVector);
return true;
}
function applyVaultUpdate(
bytes32[] calldata currentRootVector,
bytes32 updatedChannelTokenVaultRoot
) external onlyBridgeTokenVault returns (bool) {
if (currentRootVector.length != _managedStorageAddresses.length) {
revert APubUserTooShort(_managedStorageAddresses.length, currentRootVector.length);
}
if (keccak256(abi.encode(currentRootVector)) != currentRootVectorHash) {
revert UnexpectedCurrentRootVector();
}
bytes32[] memory updatedRootVector = new bytes32[](currentRootVector.length);
for (uint256 i = 0; i < currentRootVector.length; i++) {
updatedRootVector[i] = currentRootVector[i];
}
updatedRootVector[channelTokenVaultTreeIndex] = updatedChannelTokenVaultRoot;
currentRootVectorHash = keccak256(abi.encode(updatedRootVector));
emit CurrentRootVectorObserved(currentRootVectorHash, updatedRootVector);
return true;
}
function observeChannelTokenVaultStorageWrite(
address storageAddr,
uint256 storageKey,
uint256 value
) external onlyBridgeTokenVault returns (bool) {
if (storageAddr != channelTokenVaultStorageAddress) {
revert UnexpectedChannelTokenVaultStorageAddress(
channelTokenVaultStorageAddress, storageAddr
);
}
_setChannelTokenVaultZeroBalanceByStorageKey(bytes32(storageKey), value == 0);
return true;
}
function getManagedStorageAddresses() external view returns (address[] memory out) {
out = new address[](_managedStorageAddresses.length);
for (uint256 i = 0; i < _managedStorageAddresses.length; i++) {
out[i] = _managedStorageAddresses[i];
}
}
function getChannelTokenVaultRegistration(address l1Address)
external
view
returns (BridgeStructs.ChannelTokenVaultRegistration memory)
{
return _channelTokenVaultRegistrations[l1Address];
}
function getChannelTokenVaultRegistrationByL2Address(address l2Address)
external
view
returns (BridgeStructs.ChannelTokenVaultRegistration memory)
{
address l1Address = _channelTokenVaultL2AddressOwners[l2Address];
if (l1Address == address(0)) {
return BridgeStructs.ChannelTokenVaultRegistration({
exists: false,
l2Address: address(0),
channelTokenVaultKey: bytes32(0),
leafIndex: 0,
joinTollPaid: 0,
joinedAt: 0,
noteReceivePubKey: BridgeStructs.NoteReceivePubKey({ x: bytes32(0), yParity: 0 }),
isZeroBalance: false
});
}
return _channelTokenVaultRegistrations[l1Address];
}
function getNoteReceivePubKeyByL2Address(address l2Address)
external
view
returns (BridgeStructs.NoteReceivePubKey memory)
{
address l1Address = _channelTokenVaultL2AddressOwners[l2Address];
if (l1Address == address(0)) {
return BridgeStructs.NoteReceivePubKey({ x: bytes32(0), yParity: 0 });
}
return _channelTokenVaultRegistrations[l1Address].noteReceivePubKey;
}
function _decodeRootVectorFromAPubUser(
uint256[] calldata aPubUser,
uint256 rootVectorOffsetWords
) private view returns (bytes32[] memory rootVector) {
uint256 rootVectorLength = _managedStorageAddresses.length;
rootVector = new bytes32[](rootVectorLength);
for (uint256 i = 0; i < rootVectorLength;) {
rootVector[i] =
bytes32(_decodeSplitWord(aPubUser, rootVectorOffsetWords + i * SPLIT_WORD_SIZE));
unchecked {
++i;
}
}
}
function _decodeSplitWord(uint256[] calldata words, uint256 startIndex)
private
pure
returns (uint256 combined)
{
uint256 lower;
uint256 upper;
assembly ("memory-safe") {
let dataOffset := words.offset
lower := calldataload(add(dataOffset, shl(5, startIndex)))
upper := calldataload(add(dataOffset, shl(5, add(startIndex, 1))))
}
if (lower > type(uint128).max) {
revert APubUserWordOutOfRange(startIndex, lower);
}
if (upper > type(uint128).max) {
revert APubUserWordOutOfRange(startIndex + 1, upper);
}
combined = lower | (upper << 128);
}
function _deriveLeafIndexFromStorageKey(uint256 storageKey) private pure returns (uint256) {
return storageKey % TOKEN_VAULT_MT_LEAF_COUNT;
}
function _hashFunctionMetadata(BridgeStructs.DAppFunctionMetadata calldata fnMetadata)
private
pure
returns (bytes32)
{
bytes32 eventLogsHash = keccak256(
abi.encode(EVENT_LOG_ROOT_DOMAIN, fnMetadata.instanceLayout.eventLogs.length)
);
for (uint256 i = 0; i < fnMetadata.instanceLayout.eventLogs.length; i++) {
BridgeStructs.EventLogMetadata calldata eventLog =
fnMetadata.instanceLayout.eventLogs[i];
eventLogsHash = keccak256(
abi.encode(
EVENT_LOG_ITEM_DOMAIN,
eventLogsHash,
eventLog.startOffsetWords,
eventLog.topicCount
)
);
}
bytes32 instanceLayoutHash = keccak256(
abi.encode(
INSTANCE_LAYOUT_DOMAIN,
fnMetadata.instanceLayout.entryContractOffsetWords,
fnMetadata.instanceLayout.functionSigOffsetWords,
fnMetadata.instanceLayout.currentRootVectorOffsetWords,
fnMetadata.instanceLayout.updatedRootVectorOffsetWords,
eventLogsHash
)
);
return keccak256(
abi.encode(
FUNCTION_ITEM_DOMAIN,
fnMetadata.entryContract,
fnMetadata.functionSig,
fnMetadata.preprocessInputHash,
instanceLayoutHash
)
);
}
function _verifyFunctionMetadataProof(bytes32 leaf, bytes32[] calldata siblings)
private
view
returns (bool)
{
bytes32 computed = leaf;
for (uint256 i = 0; i < siblings.length; i++) {
computed = _hashFunctionMerklePair(computed, siblings[i]);
}
return computed == functionRoot;
}
function _hashFunctionMerklePair(bytes32 left, bytes32 right) private pure returns (bytes32) {
(bytes32 first, bytes32 second) = left <= right ? (left, right) : (right, left);
return keccak256(abi.encode(FUNCTION_MERKLE_NODE_DOMAIN, first, second));
}
function _emitObservedEventLogs(
uint256[] calldata aPubUser,
BridgeStructs.FunctionConfig memory functionConfig,
BridgeStructs.EventLogMetadata[] calldata eventLogs
) private {
for (uint256 i = 0; i < eventLogs.length; i++) {
BridgeStructs.EventLogMetadata calldata eventLog = eventLogs[i];
if (eventLog.topicCount > 4) {
revert UnsupportedObservedEventTopicCount(eventLog.topicCount);
}
uint256 eventEndOffset = _resolveObservedEventBoundary(functionConfig, eventLogs, i);
uint256 dataStartOffset =
uint256(eventLog.startOffsetWords) + uint256(eventLog.topicCount) * SPLIT_WORD_SIZE;
if (eventEndOffset < dataStartOffset) {
revert InvalidObservedEventBoundary(eventLog.startOffsetWords, eventEndOffset);
}
uint256 dataWordLength = eventEndOffset - dataStartOffset;
if (dataWordLength % SPLIT_WORD_SIZE != 0) {
revert InvalidObservedEventDataLength(eventLog.startOffsetWords, dataWordLength);
}
uint256[4] memory topics;
for (uint256 topicIndex = 0; topicIndex < eventLog.topicCount; topicIndex++) {
topics[topicIndex] = _decodeSplitWord(
aPubUser, uint256(eventLog.startOffsetWords) + topicIndex * SPLIT_WORD_SIZE
);
}
bytes memory logData = new bytes((dataWordLength / SPLIT_WORD_SIZE) * 32);
for (uint256 wordIndex = 0; wordIndex < dataWordLength / SPLIT_WORD_SIZE; wordIndex++) {
uint256 value =
_decodeSplitWord(aPubUser, dataStartOffset + wordIndex * SPLIT_WORD_SIZE);
assembly ("memory-safe") {
mstore(add(add(logData, 0x20), mul(wordIndex, 0x20)), value)
}
}
_observeLiquidBalanceStorageWrite(eventLog.topicCount, topics, logData);
_emitRawLog(logData, eventLog.topicCount, topics);
}
}
function _observeLiquidBalanceStorageWrite(
uint8 topicCount,
uint256[4] memory topics,
bytes memory logData
) private {
if (topicCount != 1 || bytes32(topics[0]) != LIQUID_BALANCE_STORAGE_WRITE_OBSERVED_TOPIC) {
return;
}
if (logData.length != 64) {
revert InvalidLiquidBalanceObservedEventDataLength(logData.length);
}
(address l2Address, bytes32 value) = abi.decode(logData, (address, bytes32));
_setChannelTokenVaultZeroBalanceByL2Address(l2Address, value == bytes32(0));
}
function _setChannelTokenVaultZeroBalanceByStorageKey(bytes32 storageKey, bool isZeroBalance)
private
{
address l1Address = _channelTokenVaultKeyOwners[storageKey];
if (l1Address == address(0)) revert ChannelTokenVaultKeyNotRegistered(storageKey);
_setChannelTokenVaultZeroBalance(l1Address, isZeroBalance);
}
function _setChannelTokenVaultZeroBalanceByL2Address(address l2Address, bool isZeroBalance)
private
{
address l1Address = _channelTokenVaultL2AddressOwners[l2Address];
if (l1Address == address(0)) revert ChannelTokenVaultL2AddressNotRegistered(l2Address);
_setChannelTokenVaultZeroBalance(l1Address, isZeroBalance);
}
function _setChannelTokenVaultZeroBalance(address l1Address, bool isZeroBalance) private {
BridgeStructs.ChannelTokenVaultRegistration storage registration =
_channelTokenVaultRegistrations[l1Address];
if (!registration.exists) revert ChannelTokenVaultIdentityNotRegistered(l1Address);
if (registration.isZeroBalance == isZeroBalance) {
return;
}
registration.isZeroBalance = isZeroBalance;
}
function _resolveObservedEventBoundary(
BridgeStructs.FunctionConfig memory functionConfig,
BridgeStructs.EventLogMetadata[] calldata eventLogs,
uint256 eventLogIndex
) private pure returns (uint256 boundary) {
BridgeStructs.EventLogMetadata calldata eventLog = eventLogs[eventLogIndex];
boundary = type(uint256).max;
if (eventLogIndex + 1 < eventLogs.length) {
uint256 nextStartOffset = eventLogs[eventLogIndex + 1].startOffsetWords;
if (nextStartOffset > eventLog.startOffsetWords) {
boundary = nextStartOffset;
}
}
boundary = _minObservedBoundary(
boundary, functionConfig.updatedRootVectorOffsetWords, eventLog.startOffsetWords
);
boundary = _minObservedBoundary(
boundary, functionConfig.entryContractOffsetWords, eventLog.startOffsetWords
);
boundary = _minObservedBoundary(
boundary, functionConfig.functionSigOffsetWords, eventLog.startOffsetWords
);
boundary = _minObservedBoundary(
boundary, functionConfig.currentRootVectorOffsetWords, eventLog.startOffsetWords
);
if (boundary == type(uint256).max) {
revert InvalidObservedEventBoundary(eventLog.startOffsetWords, boundary);
}
}
function _minObservedBoundary(
uint256 currentBoundary,
uint256 candidateBoundary,
uint16 startOffsetWords
) private pure returns (uint256) {
if (candidateBoundary > startOffsetWords && candidateBoundary < currentBoundary) {
return candidateBoundary;
}
return currentBoundary;
}
function _emitRawLog(bytes memory logData, uint8 topicCount, uint256[4] memory topics) private {
uint256 dataLength = logData.length;
assembly ("memory-safe") {
let dataPtr := add(logData, 0x20)
switch topicCount
case 0 { log0(dataPtr, dataLength) }
case 1 { log1(dataPtr, dataLength, mload(topics)) }
case 2 { log2(dataPtr, dataLength, mload(topics), mload(add(topics, 0x20))) }
case 3 {
log3(
dataPtr,
dataLength,
mload(topics),
mload(add(topics, 0x20)),
mload(add(topics, 0x40))
)
}
case 4 {
log4(
dataPtr,
dataLength,
mload(topics),
mload(add(topics, 0x20)),
mload(add(topics, 0x40)),
mload(add(topics, 0x60))
)
}
}
}
}
src/DAppManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import { Initializable } from "@openzeppelin-upgradeable/proxy/utils/Initializable.sol";
import { OwnableUpgradeable } from "@openzeppelin-upgradeable/access/OwnableUpgradeable.sol";
import { UUPSUpgradeable } from "@openzeppelin-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import { BridgeStructs } from "./BridgeStructs.sol";
import { IGrothVerifier } from "./interfaces/IGrothVerifier.sol";
import { ITokamakVerifier } from "./interfaces/ITokamakVerifier.sol";
interface IBridgeVerifierSource {
function grothVerifier() external view returns (IGrothVerifier);
function tokamakVerifier() external view returns (ITokamakVerifier);
}
contract DAppManager is Initializable, OwnableUpgradeable, UUPSUpgradeable {
uint256 internal constant SEPOLIA_CHAIN_ID = 11155111;
uint256 internal constant LOCAL_CHAIN_ID = 31337;
bytes32 public constant DAPP_METADATA_DIGEST_SCHEMA =
keccak256("tokamak.zk-evm.bridge.dapp-metadata-digest.v1");
bytes32 private constant STORAGE_ROOT_DOMAIN = keccak256("dapp.metadata.v1.storage-root");
bytes32 private constant STORAGE_ITEM_DOMAIN = keccak256("dapp.metadata.v1.storage-item");
bytes32 private constant PREALLOC_ROOT_DOMAIN = keccak256("dapp.metadata.v1.prealloc-root");
bytes32 private constant PREALLOC_ITEM_DOMAIN = keccak256("dapp.metadata.v1.prealloc-item");
bytes32 private constant USER_SLOT_ROOT_DOMAIN = keccak256("dapp.metadata.v1.user-slot-root");
bytes32 private constant USER_SLOT_ITEM_DOMAIN = keccak256("dapp.metadata.v1.user-slot-item");
bytes32 private constant FUNCTION_ROOT_DOMAIN = keccak256("dapp.metadata.v1.function-root");
bytes32 private constant FUNCTION_ITEM_DOMAIN = keccak256("dapp.metadata.v1.function-item");
bytes32 private constant FUNCTION_MERKLE_NODE_DOMAIN =
keccak256("dapp.metadata.v1.function-merkle-node");
bytes32 private constant INSTANCE_LAYOUT_DOMAIN = keccak256("dapp.metadata.v1.instance-layout");
bytes32 private constant EVENT_LOG_ROOT_DOMAIN = keccak256("dapp.metadata.v1.event-log-root");
bytes32 private constant EVENT_LOG_ITEM_DOMAIN = keccak256("dapp.metadata.v1.event-log-item");
bytes32 private constant VERIFIER_SNAPSHOT_DOMAIN =
keccak256("dapp.metadata.v1.verifier-snapshot");
error UnknownDApp(uint256 dappId);
error DuplicateDApp(uint256 dappId);
error InvalidDAppLabelHash(uint256 dappId);
error EmptyStorageLayout(uint256 dappId);
error EmptyFunctionList(uint256 dappId);
error InvalidStorageAddress(uint256 dappId, address storageAddr);
error DuplicateStorageAddress(uint256 dappId, address storageAddr);
error UnknownStorageAddress(uint256 dappId, address storageAddr);
error InvalidFunctionEntryContract(uint256 dappId, address entryContract, bytes4 functionSig);
error DuplicateFunction(uint256 dappId, address entryContract, bytes4 functionSig);
error MissingChannelTokenVaultStorageAddress(uint256 dappId);
error MultipleChannelTokenVaultStorageAddresses(
uint256 dappId, address firstStorageAddr, address secondStorageAddr
);
error MissingPreprocessInputHash(uint256 dappId, address entryContract, bytes4 functionSig);
error DuplicatePreprocessInputHash(uint256 dappId, bytes32 preprocessInputHash);
error InvalidFunctionEventTopicCount(
uint256 dappId, address entryContract, bytes4 functionSig, uint8 topicCount
);
error DAppDeletionDisabled();
error InvalidBridgeCore();
error BridgeCoreAlreadyBound(address existingBridgeCore);
error BridgeCoreNotBound();
struct DAppInfo {
bool exists;
bytes32 labelHash;
uint256 channelTokenVaultTreeIndex;
bytes32 metadataDigestSchema;
bytes32 metadataDigest;
bytes32 functionRoot;
}
struct DAppMetadataDigestParts {
uint256 channelTokenVaultTreeIndex;
bytes32 storageRoot;
bytes32 functionRoot;
}
address public bridgeCore;
mapping(uint256 => DAppInfo) private _dapps;
mapping(uint256 => BridgeStructs.DAppVerifierSnapshot) private _verifierSnapshots;
mapping(uint256 => address[]) private _managedStorageAddresses;
mapping(uint256 => mapping(address => bool)) private _knownStorageAddress;
mapping(uint256 => mapping(address => bool)) private _isChannelTokenVaultStorage;
mapping(uint256 => mapping(address => bytes32[])) private _preAllocatedKeys;
mapping(uint256 => mapping(address => uint8[])) private _userStorageSlots;
event DAppRegistered(
uint256 indexed dappId, bytes32 labelHash, uint256 storageCount, uint256 functionCount
);
event DAppMetadataUpdated(
uint256 indexed dappId, bytes32 labelHash, uint256 storageCount, uint256 functionCount
);
event DAppMetadataDigestUpdated(
uint256 indexed dappId, bytes32 indexed schema, bytes32 indexed digest
);
event DAppDeleted(uint256 indexed dappId, bytes32 labelHash);
event BridgeCoreBound(address indexed bridgeCore);
constructor() {
_disableInitializers();
}
function initialize(address initialOwner) external initializer {
__Ownable_init();
__UUPSUpgradeable_init();
if (initialOwner != _msgSender()) {
_transferOwnership(initialOwner);
}
}
function bindBridgeCore(address bridgeCore_) external onlyOwner {
if (bridgeCore_ == address(0)) {
revert InvalidBridgeCore();
}
if (bridgeCore != address(0)) {
if (bridgeCore == bridgeCore_) {
return;
}
revert BridgeCoreAlreadyBound(bridgeCore);
}
bridgeCore = bridgeCore_;
emit BridgeCoreBound(bridgeCore_);
}
function deleteDApp(uint256 dappId) external onlyOwner {
DAppInfo memory info = _requireDApp(dappId);
if (block.chainid != SEPOLIA_CHAIN_ID && block.chainid != LOCAL_CHAIN_ID) {
revert DAppDeletionDisabled();
}
_clearDAppRuntimeMetadata(dappId);
delete _verifierSnapshots[dappId];
delete _dapps[dappId];
emit DAppDeleted(dappId, info.labelHash);
}
function registerDApp(
uint256 dappId,
bytes32 labelHash,
BridgeStructs.StorageMetadata[] calldata storages,
BridgeStructs.DAppFunctionMetadata[] calldata functions
) external onlyOwner {
if (_dapps[dappId].exists) {
revert DuplicateDApp(dappId);
}
if (labelHash == bytes32(0)) {
revert InvalidDAppLabelHash(dappId);
}
DAppMetadataDigestParts memory digestParts =
_storeDAppRuntimeMetadata(dappId, storages, functions);
BridgeStructs.DAppVerifierSnapshot memory verifierSnapshot =
_snapshotCurrentVerifiers(dappId);
bytes32 metadataDigest =
_computeDAppMetadataDigest(dappId, labelHash, digestParts, verifierSnapshot);
_dapps[dappId] = DAppInfo({
exists: true,
labelHash: labelHash,
channelTokenVaultTreeIndex: digestParts.channelTokenVaultTreeIndex,
metadataDigestSchema: DAPP_METADATA_DIGEST_SCHEMA,
metadataDigest: metadataDigest,
functionRoot: digestParts.functionRoot
});
emit DAppRegistered(dappId, labelHash, storages.length, functions.length);
emit DAppMetadataDigestUpdated(dappId, DAPP_METADATA_DIGEST_SCHEMA, metadataDigest);
}
function updateDAppMetadata(
uint256 dappId,
BridgeStructs.StorageMetadata[] calldata storages,
BridgeStructs.DAppFunctionMetadata[] calldata functions
) external onlyOwner {
DAppInfo memory info = _requireDApp(dappId);
_clearDAppRuntimeMetadata(dappId);
DAppMetadataDigestParts memory digestParts =
_storeDAppRuntimeMetadata(dappId, storages, functions);
BridgeStructs.DAppVerifierSnapshot memory verifierSnapshot =
_snapshotCurrentVerifiers(dappId);
bytes32 metadataDigest =
_computeDAppMetadataDigest(dappId, info.labelHash, digestParts, verifierSnapshot);
_dapps[dappId] = DAppInfo({
exists: true,
labelHash: info.labelHash,
channelTokenVaultTreeIndex: digestParts.channelTokenVaultTreeIndex,
metadataDigestSchema: DAPP_METADATA_DIGEST_SCHEMA,
metadataDigest: metadataDigest,
functionRoot: digestParts.functionRoot
});
emit DAppMetadataUpdated(dappId, info.labelHash, storages.length, functions.length);
emit DAppMetadataDigestUpdated(dappId, DAPP_METADATA_DIGEST_SCHEMA, metadataDigest);
}
function getDAppInfo(uint256 dappId) external view returns (DAppInfo memory) {
if (!_dapps[dappId].exists) {
revert UnknownDApp(dappId);
}
return _dapps[dappId];
}
function getDAppVerifierSnapshot(uint256 dappId)
external
view
returns (BridgeStructs.DAppVerifierSnapshot memory)
{
_requireDApp(dappId);
return _verifierSnapshots[dappId];
}
function getManagedStorageAddresses(uint256 dappId)
external
view
returns (address[] memory out)
{
_requireDApp(dappId);
address[] storage managedStorageAddresses = _managedStorageAddresses[dappId];
out = new address[](managedStorageAddresses.length);
for (uint256 i = 0; i < managedStorageAddresses.length; i++) {
out[i] = managedStorageAddresses[i];
}
}
function getManagedStorageCount(uint256 dappId) external view returns (uint256) {
_requireDApp(dappId);
return _managedStorageAddresses[dappId].length;
}
function getChannelTokenVaultTreeIndex(uint256 dappId) external view returns (uint256) {
return _requireDApp(dappId).channelTokenVaultTreeIndex;
}
function getPreAllocKeys(uint256 dappId, address storageAddr)
external
view
returns (bytes32[] memory out)
{
_requireKnownStorage(dappId, storageAddr);
bytes32[] storage preAllocatedKeys = _preAllocatedKeys[dappId][storageAddr];
out = new bytes32[](preAllocatedKeys.length);
for (uint256 i = 0; i < preAllocatedKeys.length; i++) {
out[i] = preAllocatedKeys[i];
}
}
function getUserSlots(uint256 dappId, address storageAddr)
external
view
returns (uint8[] memory out)
{
_requireKnownStorage(dappId, storageAddr);
uint8[] storage userStorageSlots = _userStorageSlots[dappId][storageAddr];
out = new uint8[](userStorageSlots.length);
for (uint256 i = 0; i < userStorageSlots.length; i++) {
out[i] = userStorageSlots[i];
}
}
function isChannelTokenVaultStorageAddress(uint256 dappId, address storageAddr)
external
view
returns (bool)
{
_requireKnownStorage(dappId, storageAddr);
return _isChannelTokenVaultStorage[dappId][storageAddr];
}
function _authorizeUpgrade(address) internal override onlyOwner { }
function _storeDAppRuntimeMetadata(
uint256 dappId,
BridgeStructs.StorageMetadata[] calldata storages,
BridgeStructs.DAppFunctionMetadata[] calldata functions
) private returns (DAppMetadataDigestParts memory digestParts) {
if (storages.length == 0) {
revert EmptyStorageLayout(dappId);
}
if (functions.length == 0) {
revert EmptyFunctionList(dappId);
}
digestParts.channelTokenVaultTreeIndex = type(uint256).max;
digestParts.storageRoot = keccak256(abi.encode(STORAGE_ROOT_DOMAIN, storages.length));
address channelTokenVaultStorageAddress;
for (uint256 i = 0; i < storages.length; i++) {
BridgeStructs.StorageMetadata calldata storageMetadata = storages[i];
if (storageMetadata.storageAddr == address(0)) {
revert InvalidStorageAddress(dappId, storageMetadata.storageAddr);
}
if (storageMetadata.storageAddr.code.length == 0) {
revert InvalidStorageAddress(dappId, storageMetadata.storageAddr);
}
if (_knownStorageAddress[dappId][storageMetadata.storageAddr]) {
revert DuplicateStorageAddress(dappId, storageMetadata.storageAddr);
}
_knownStorageAddress[dappId][storageMetadata.storageAddr] = true;
_managedStorageAddresses[dappId].push(storageMetadata.storageAddr);
_isChannelTokenVaultStorage[dappId][storageMetadata.storageAddr] =
storageMetadata.isChannelTokenVaultStorage;
for (uint256 j = 0; j < storageMetadata.preAllocatedKeys.length; j++) {
_preAllocatedKeys[dappId][storageMetadata.storageAddr].push(
storageMetadata.preAllocatedKeys[j]
);
}
for (uint256 j = 0; j < storageMetadata.userStorageSlots.length; j++) {
_userStorageSlots[dappId][storageMetadata.storageAddr].push(
storageMetadata.userStorageSlots[j]
);
}
if (storageMetadata.isChannelTokenVaultStorage) {
if (channelTokenVaultStorageAddress != address(0)) {
revert MultipleChannelTokenVaultStorageAddresses(
dappId, channelTokenVaultStorageAddress, storageMetadata.storageAddr
);
}
channelTokenVaultStorageAddress = storageMetadata.storageAddr;
digestParts.channelTokenVaultTreeIndex = i;
}
digestParts.storageRoot = keccak256(
abi.encode(digestParts.storageRoot, _hashStorageMetadata(storageMetadata))
);
}
if (channelTokenVaultStorageAddress == address(0)) {
revert MissingChannelTokenVaultStorageAddress(dappId);
}
bytes32[] memory functionHashes = new bytes32[](functions.length);
bytes32[] memory functionKeys = new bytes32[](functions.length);
bytes32[] memory preprocessInputHashes = new bytes32[](functions.length);
for (uint256 i = 0; i < functions.length; i++) {
functionHashes[i] = _validateAndHashFunctionMetadata(
dappId, functions[i], functionKeys, preprocessInputHashes, i
);
}
digestParts.functionRoot = _computeFunctionMerkleRoot(functionHashes);
}
function _validateAndHashFunctionMetadata(
uint256 dappId,
BridgeStructs.DAppFunctionMetadata calldata fnMetadata,
bytes32[] memory functionKeys,
bytes32[] memory preprocessInputHashes,
uint256 functionIndex
) private view returns (bytes32 functionMetadataHash) {
bytes32 functionKey = _computeFunctionKey(fnMetadata.entryContract, fnMetadata.functionSig);
if (fnMetadata.entryContract == address(0)) {
revert InvalidFunctionEntryContract(
dappId, fnMetadata.entryContract, fnMetadata.functionSig
);
}
if (fnMetadata.entryContract.code.length == 0) {
revert InvalidFunctionEntryContract(
dappId, fnMetadata.entryContract, fnMetadata.functionSig
);
}
if (fnMetadata.preprocessInputHash == bytes32(0)) {
revert MissingPreprocessInputHash(
dappId, fnMetadata.entryContract, fnMetadata.functionSig
);
}
for (uint256 i = 0; i < functionIndex; i++) {
if (functionKeys[i] == functionKey) {
revert DuplicateFunction(dappId, fnMetadata.entryContract, fnMetadata.functionSig);
}
if (preprocessInputHashes[i] == fnMetadata.preprocessInputHash) {
revert DuplicatePreprocessInputHash(dappId, fnMetadata.preprocessInputHash);
}
}
functionKeys[functionIndex] = functionKey;
preprocessInputHashes[functionIndex] = fnMetadata.preprocessInputHash;
for (uint256 j = 0; j < fnMetadata.instanceLayout.eventLogs.length; j++) {
BridgeStructs.EventLogMetadata calldata eventLog =
fnMetadata.instanceLayout.eventLogs[j];
if (eventLog.topicCount > 4) {
revert InvalidFunctionEventTopicCount(
dappId, fnMetadata.entryContract, fnMetadata.functionSig, eventLog.topicCount
);
}
}
functionMetadataHash = _hashFunctionMetadata(fnMetadata);
}
function _clearDAppRuntimeMetadata(uint256 dappId) private {
address[] storage managedStorageAddresses = _managedStorageAddresses[dappId];
for (uint256 i = 0; i < managedStorageAddresses.length; i++) {
address storageAddr = managedStorageAddresses[i];
delete _knownStorageAddress[dappId][storageAddr];
delete _isChannelTokenVaultStorage[dappId][storageAddr];
delete _preAllocatedKeys[dappId][storageAddr];
delete _userStorageSlots[dappId][storageAddr];
}
delete _managedStorageAddresses[dappId];
}
function _snapshotCurrentVerifiers(uint256 dappId)
private
returns (BridgeStructs.DAppVerifierSnapshot memory verifierSnapshot)
{
if (bridgeCore == address(0)) {
revert BridgeCoreNotBound();
}
IGrothVerifier grothVerifier = IBridgeVerifierSource(bridgeCore).grothVerifier();
ITokamakVerifier tokamakVerifier = IBridgeVerifierSource(bridgeCore).tokamakVerifier();
verifierSnapshot = BridgeStructs.DAppVerifierSnapshot({
grothVerifier: address(grothVerifier),
grothVerifierCompatibleBackendVersion: grothVerifier.compatibleBackendVersion(),
tokamakVerifier: address(tokamakVerifier),
tokamakVerifierCompatibleBackendVersion: tokamakVerifier.compatibleBackendVersion()
});
_verifierSnapshots[dappId] = verifierSnapshot;
}
function _computeDAppMetadataDigest(
uint256 dappId,
bytes32 labelHash,
DAppMetadataDigestParts memory digestParts,
BridgeStructs.DAppVerifierSnapshot memory verifierSnapshot
) private pure returns (bytes32) {
return keccak256(
abi.encode(
DAPP_METADATA_DIGEST_SCHEMA,
dappId,
labelHash,
digestParts.channelTokenVaultTreeIndex,
digestParts.storageRoot,
digestParts.functionRoot,
_hashVerifierSnapshot(verifierSnapshot)
)
);
}
function _hashStorageMetadata(BridgeStructs.StorageMetadata calldata storageMetadata)
private
pure
returns (bytes32)
{
bytes32 preAllocatedKeysHash = keccak256(
abi.encode(PREALLOC_ROOT_DOMAIN, storageMetadata.preAllocatedKeys.length)
);
for (uint256 i = 0; i < storageMetadata.preAllocatedKeys.length; i++) {
preAllocatedKeysHash = keccak256(
abi.encode(
PREALLOC_ITEM_DOMAIN, preAllocatedKeysHash, storageMetadata.preAllocatedKeys[i]
)
);
}
bytes32 userStorageSlotsHash =
keccak256(abi.encode(USER_SLOT_ROOT_DOMAIN, storageMetadata.userStorageSlots.length));
for (uint256 i = 0; i < storageMetadata.userStorageSlots.length; i++) {
userStorageSlotsHash = keccak256(
abi.encode(
USER_SLOT_ITEM_DOMAIN, userStorageSlotsHash, storageMetadata.userStorageSlots[i]
)
);
}
return keccak256(
abi.encode(
STORAGE_ITEM_DOMAIN,
storageMetadata.storageAddr,
preAllocatedKeysHash,
userStorageSlotsHash,
storageMetadata.isChannelTokenVaultStorage
)
);
}
function _hashFunctionMetadata(BridgeStructs.DAppFunctionMetadata calldata fnMetadata)
private
pure
returns (bytes32)
{
bytes32 eventLogsHash = keccak256(
abi.encode(EVENT_LOG_ROOT_DOMAIN, fnMetadata.instanceLayout.eventLogs.length)
);
for (uint256 i = 0; i < fnMetadata.instanceLayout.eventLogs.length; i++) {
BridgeStructs.EventLogMetadata calldata eventLog =
fnMetadata.instanceLayout.eventLogs[i];
eventLogsHash = keccak256(
abi.encode(
EVENT_LOG_ITEM_DOMAIN,
eventLogsHash,
eventLog.startOffsetWords,
eventLog.topicCount
)
);
}
bytes32 instanceLayoutHash = keccak256(
abi.encode(
INSTANCE_LAYOUT_DOMAIN,
fnMetadata.instanceLayout.entryContractOffsetWords,
fnMetadata.instanceLayout.functionSigOffsetWords,
fnMetadata.instanceLayout.currentRootVectorOffsetWords,
fnMetadata.instanceLayout.updatedRootVectorOffsetWords,
eventLogsHash
)
);
return keccak256(
abi.encode(
FUNCTION_ITEM_DOMAIN,
fnMetadata.entryContract,
fnMetadata.functionSig,
fnMetadata.preprocessInputHash,
instanceLayoutHash
)
);
}
function _computeFunctionMerkleRoot(bytes32[] memory leaves) private pure returns (bytes32) {
uint256 levelLength = leaves.length;
while (levelLength > 1) {
uint256 nextLength = (levelLength + 1) / 2;
for (uint256 i = 0; i < nextLength; i++) {
uint256 leftIndex = i * 2;
uint256 rightIndex = leftIndex + 1;
bytes32 left = leaves[leftIndex];
bytes32 right = rightIndex < levelLength ? leaves[rightIndex] : left;
leaves[i] = _hashFunctionMerklePair(left, right);
}
levelLength = nextLength;
}
return leaves[0];
}
function _hashFunctionMerklePair(bytes32 left, bytes32 right) private pure returns (bytes32) {
(bytes32 first, bytes32 second) = left <= right ? (left, right) : (right, left);
return keccak256(abi.encode(FUNCTION_MERKLE_NODE_DOMAIN, first, second));
}
function _computeFunctionKey(address entryContract, bytes4 functionSig)
private
pure
returns (bytes32)
{
return keccak256(abi.encode(entryContract, functionSig));
}
function _hashVerifierSnapshot(BridgeStructs.DAppVerifierSnapshot memory verifierSnapshot)
private
pure
returns (bytes32)
{
return keccak256(
abi.encode(
VERIFIER_SNAPSHOT_DOMAIN,
verifierSnapshot.grothVerifier,
keccak256(bytes(verifierSnapshot.grothVerifierCompatibleBackendVersion)),
verifierSnapshot.tokamakVerifier,
keccak256(bytes(verifierSnapshot.tokamakVerifierCompatibleBackendVersion))
)
);
}
function _requireDApp(uint256 dappId) private view returns (DAppInfo memory info) {
info = _dapps[dappId];
if (!info.exists) {
revert UnknownDApp(dappId);
}
}
function _requireKnownStorage(uint256 dappId, address storageAddr) private view {
_requireDApp(dappId);
if (!_knownStorageAddress[dappId][storageAddr]) {
revert UnknownStorageAddress(dappId, storageAddr);
}
}
}
src/generated/TokamakEnvironment.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Generated by bridge/scripts/deploy-bridge.mjs.
library TokamakEnvironment {
uint8 internal constant MT_DEPTH = 36;
uint256 internal constant MAX_MT_LEAVES = uint256(1) << uint256(MT_DEPTH);
bytes32 internal constant ZERO_FILLED_TREE_ROOT =
0x32fe7eab871c48cbc0c5c1b6444be3d71bfba4056511b49dd0ceb179c8807bc6;
uint256 internal constant TOKAMAK_APUB_BLOCK_LENGTH = 43;
uint256 internal constant TOKAMAK_PREVIOUS_BLOCK_HASHES = 4;
}
src/interfaces/IChannelRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import { IGrothVerifier } from "./IGrothVerifier.sol";
import { ITokamakVerifier } from "./ITokamakVerifier.sol";
interface IChannelRegistry {
function getChannelManager(uint256 channelId) external view returns (address);
function grothVerifier() external view returns (IGrothVerifier);
function tokamakVerifier() external view returns (ITokamakVerifier);
}
src/interfaces/IGrothVerifier.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
interface IGrothVerifier {
function compatibleBackendVersion() external view returns (string memory);
function verifyProof(
uint256[4] calldata pA,
uint256[8] calldata pB,
uint256[4] calldata pC,
uint256[5] calldata pubSignals
) external view returns (bool);
}
src/interfaces/ITokamakVerifier.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
interface ITokamakVerifier {
function compatibleBackendVersion() external view returns (string memory);
function verify(
uint128[] calldata _proof_part1,
uint256[] calldata _proof_part2,
uint128[] calldata _preprocessed_part1,
uint256[] calldata _preprocessed_part2,
uint256[] calldata a_pub_user,
uint256[] calldata a_pub_block
) external view returns (bool);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"@openzeppelin/=../lib/openzeppelin-contracts/contracts/",
"@openzeppelin-upgradeable/=../lib/openzeppelin-contracts-upgradeable/contracts/",
"forge-std/=../lib/forge-std/src/",
"ds-test/=../lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=/private/tmp/tokamak-bridge-verify.um78XJ/lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=/private/tmp/tokamak-bridge-verify.um78XJ/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts-upgradeable/=../lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=/private/tmp/tokamak-bridge-verify.um78XJ/lib/openzeppelin-contracts/contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.