Skip to content
Verified contractExactAGPL-3.0-or-later

Collateral

Address0xcc2924840183cc90ee19d2db0fbec4476abbf215
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.24

 

Same code

5 more contracts

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
Via IR
yes
License
AGPL-3.0-or-later
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,790,407
Creation transaction
0x4e5bf1cf6c…342154ea75

77 files

The source code is large: one file is shown at a time. Choose a file in the list.

lib/blockchainManager/evm/v1/contracts/v2/Collateral.sol

// SPDX-FileCopyrightText: Copyright (C) 2024 Signify Holdings, Inc.
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.24;

import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import {IFactory} from "./interfaces/IFactory.sol";

/**
 * @title Collateral Contract
 * @notice Smart contract for holding collateral assets with multi-signature control
 * @dev Upgradeable contract via beacon pattern
 *      Works in conjunction with Coordinator contract
 *
 * @dev Core functionalities:
 * 1. Multi-Signature Administration
 *    - Multiple admins can control the contract (up to 30 admins)
 *    - Configurable threshold for required signatures
 *    - EIP-712 compliant signatures for all admin actions
 *    - Admin management (add/remove)
 *
 * 2. Asset Management
 *    - Holds both native chain assets (ETH/AVAX) and ERC20 tokens
 *    - Controlled withdrawals and payments via Coordinator contract
 *    - Safe transfer implementations
 *
 * 3. Team Management
 *    - Team name and admin updates
 *    - Contract can be transferred to new set of admins
 *    - Multi-sig required for team transfers
 *
 * 4. Security Features
 *    - Signature replay protection via nonces
 *    - Admin threshold enforcement
 *    - Duplicate signer detection
 *    - Initializable pattern for proxy deployment
 *
 * @dev Technical Details:
 * - Version: 2 (EIP712_DOMAIN_VERSION)
 * - Proxy Pattern: Initializable (OpenZeppelin)
 * - Dependencies: ECDSA, SafeERC20
 * - Factory deployment model
 * - Max admins: 30
 *
 * @dev Key State Variables:
 * - admins[]: Array of admin addresses
 * - _adminThreshold: Required signatures for operations
 * - name: Team identifier
 * - factory: Factory contract address
 * - adminNonce: Prevents signature replay
 *
 * @dev Main Workflows:
 * 1. Admin Management:
 *    - Add/Remove admins (requires multi-sig)
 *    - Update threshold (requires multi-sig)
 *
 * 2. Asset Management:
 *    - Receive assets (native via receive())
 *    - Withdraw assets (via Coordinator only)
 *    - Verify withdrawal signatures
 *
 * 3. Team Transfer:
 *    - Current admins sign transfer
 *    - New admins and name set
 *    - All previous admins removed
 *
 * @dev Access Control:
 * 1. Coordinator Only:
 *    - Asset withdrawals
 *    - Signature verification
 *
 * 2. Factory Only:
 *    - Factory address updates
 *
 * 3. Admins:
 *    - Add/remove admins
 *    - Update threshold
 *    - Transfer team
 *
 * @notice Important Constraints:
 * - Cannot remove last admin
 * - Cannot exceed max admin limit (30)
 * - Threshold cannot exceed admin count
 * - Cannot have duplicate signers
 * - Must maintain minimum admin threshold
 * - Zero addresses not allowed
 */

contract Collateral is Initializable {
    using SafeERC20 for IERC20;

    /// @notice Elliptic Curve Digital Signature Algorithm Used to validate signature
    using ECDSA for bytes32;

    // Deprecated state variable.
    address private owner;

    // User readable name of signing domain
    string public constant EIP712_DOMAIN_NAME = "Collateral";

    // Current major version of signing domain
    string public constant EIP712_DOMAIN_VERSION = "2";

    // Type hash to check EIP712 domain separator validity in signature
    bytes32 public constant EIP712_DOMAIN_TYPE_HASH =
        keccak256(
            "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"
        );

    // Type hash to update admin threshold signature validity
    bytes32 public constant UPDATE_ADMIN_THRESHOLD_TYPE_HASH =
        keccak256("UpdateAdminThreshold(uint8 threshold,uint256 nonce)");

    // Type hash to add admin signature validity
    bytes32 public constant ADD_ADMIN_TYPE_HASH =
        keccak256("AddAdmin(address admin,uint256 nonce)");

    // Type hash to remove admin signature validity
    bytes32 public constant REMOVE_ADMIN_TYPE_HASH =
        keccak256("RemoveAdmin(address admin,uint256 nonce)");

    // Type hash to withdraw signature validity
    bytes32 public constant WITHDRAW_TYPE_HASH =
        keccak256(
            "Withdraw(address user,address asset,uint256 amount,address recipient,uint256 nonce)"
        );

    // Type hash to transfer team signature validity
    bytes32 public constant TRANSFER_TEAM_TYPE_HASH =
        keccak256(
            "TransferTeam(address[] addingAdmins,string newName,uint256 nonce)"
        );

    /// @notice name of collateral
    string public name;

    /// @notice Factory Address
    ///         It is used to get controller address held in factory
    address public factory;

    /// @notice Admins of this contracts.
    address[] public admins;

    /// @notice Maximum number of admins
    uint8 public constant MAX_ADMINS = 30;

    /// @notice Admin threshold set by user or default(0)
    uint8 internal __adminThreshold;

    /// @notice Nonce used to validate admin signature
    uint256 public adminNonce;

    event AdminThresholdUpdated(uint8 threshold);
    event AdminAdded(address admin);
    event AdminRemoved(address admin);
    event TransferTeam(
        address[] addingAdmins,
        string newName,
        uint8 adminThreshold
    );
    event NativeAssetReceived(address sender, uint256 amount);

    error InvalidAdminThreshold();
    error InvalidSignature();
    error InconsistentInputLength();
    error UnderAdminThreshold();
    error AboveMaxAdmins();
    error Unauthorized();
    error AddressZero();
    error MinAdmins();
    error MaxAdmins();
    error AdminAlreadyExists();
    error LastAdmin();
    error AdminNotFound();
    error DuplicateSigner();
    error CannotSendNativeAsset();

    /// @notice Authorize transactions from Coordinator contract only
    modifier onlyCoordinator() {
        if (_getCoordinator() != msg.sender) {
            revert Unauthorized();
        }
        _;
    }

    /// @notice Authorize transactions from Factory contract only
    modifier onlyFactory() {
        if (factory != msg.sender) {
            revert Unauthorized();
        }
        _;
    }

    /// @notice Revert if address param is 0x0
    modifier validAddress(address _address) {
        if (_address == address(0)) {
            revert AddressZero();
        }
        _;
    }

    /// @notice Prevent the implementation contract from being used
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /**
     * @notice Initialize this contract
     * @param _name name of collateral
     * @param _admin address of the first admin
     */
    function initialize(
        string memory _name,
        address _admin
    ) public validAddress(_admin) initializer {
        name = _name;
        factory = msg.sender;
        admins.push(_admin);
    }

    /**
     * @notice Get admin threshold with some safety logic
     * @return threshold admin threshold
     */
    function adminThreshold() public view returns (uint8) {
        // If threshold is not set, default to 1
        if (__adminThreshold == 0) {
            return 1;
        }
        // If threshold is greater than number of admins, cap it at max admins
        // This ensures we never require more signatures than available admins
        if (__adminThreshold > admins.length) {
            return uint8(admins.length);
        }
        // Return the configured threshold if it's valid
        return __adminThreshold;
    }

    /**
     * @notice Update admin threshold
     * @param _threshold new admin threshold
     * @param _salts disambiguating salts for admin signatures
     * @param _signatures signatures generated by admins in the same order with _salts
     */
    function updateAdminThreshold(
        uint8 _threshold,
        bytes32[] calldata _salts,
        bytes[] calldata _signatures
    ) external {
        // Cannot set threshold to 0
        if (_threshold == 0) {
            revert InvalidAdminThreshold();
        }
        // Cannot set threshold to be greater than current number of admins
        if (_threshold > admins.length) {
            revert InvalidAdminThreshold();
        }

        // Create message hash to verify signature
        bytes32 messageHash = keccak256(
            bytes.concat(
                abi.encode(
                    UPDATE_ADMIN_THRESHOLD_TYPE_HASH,
                    _threshold,
                    adminNonce
                )
            )
        );
        // Verify signatures
        _verifyAdminSignatures(messageHash, _salts, _signatures);

        // Update threshold
        __adminThreshold = _threshold;

        emit AdminThresholdUpdated(__adminThreshold);
    }

    /**
     * @notice Check if _address is admin of this contract
     * @param _address address to check
     * @return status true if _address is admin
     */
    function isAdmin(address _address) public view returns (bool) {
        // Check if _address is in admins array
        (bool found, ) = _getAdminIndex(_address);
        return found;
    }

    /**
     * @notice Add a collateral admin
     * @dev only admin can call this function
     * @param _admin new admin address
     * @param _salts disambiguating salts for admin signatures
     * @param _signatures signatures generated by admins in the same order with _salts
     */
    function addAdmin(
        address _admin,
        bytes32[] calldata _salts,
        bytes[] calldata _signatures
    ) public validAddress(_admin) {
        // Cannot exceed max admins
        if (admins.length >= MAX_ADMINS) {
            revert MaxAdmins();
        }

        // Check if _admin is already in admins array
        (bool found, ) = _getAdminIndex(_admin);
        if (found) {
            revert AdminAlreadyExists();
        }

        // Create message hash from admin address and nonce for signature verification
        bytes32 messageHash = keccak256(
            bytes.concat(abi.encode(ADD_ADMIN_TYPE_HASH, _admin, adminNonce))
        );
        // Verify that enough valid admin signatures were provided
        _verifyAdminSignatures(messageHash, _salts, _signatures);

        // Add the new admin address to the admins array
        admins.push(_admin);

        // Emit event to log the admin addition
        emit AdminAdded(_admin);
    }

    /**
     * @notice Remove a collateral admin
     * @dev only admin can call this function
     * @param _admin admin address to be removed
     * @param _salts disambiguating salts for admin signatures
     * @param _signatures signatures generated by admins in the same order with _salts
     */
    function removeAdmin(
        address _admin,
        bytes32[] calldata _salts,
        bytes[] calldata _signatures
    ) public {
        // Cannot remove the last admin
        if (admins.length == 1) {
            revert LastAdmin();
        }

        // Check if _admin is in admins array
        (bool found, uint256 index) = _getAdminIndex(_admin);
        if (!found) {
            revert AdminNotFound();
        }

        // Create message hash from admin address and nonce for signature verification
        bytes32 messageHash = keccak256(
            bytes.concat(abi.encode(REMOVE_ADMIN_TYPE_HASH, _admin, adminNonce))
        );
        // Verify that enough valid admin signatures were provided
        _verifyAdminSignatures(messageHash, _salts, _signatures);

        // Replace the admin to be removed with the last admin in the array
        admins[index] = admins[admins.length - 1];
        // Remove the last admin from the array
        admins.pop();

        emit AdminRemoved(_admin);
    }

    /**
     * @notice Withdraw ERC-20 asset that this contract owns.
     * @dev only Coordinator can call this function
     * @param _asset asset address
     * @param _recipient recipient address
     * @param _amountNative withdrawed amount
     */
    function withdrawERC20Asset(
        address _asset,
        address _recipient,
        uint256 _amountNative
    ) external onlyCoordinator {
        // Transfer the ERC20 asset to the recipient
        IERC20(_asset).safeTransfer(_recipient, _amountNative);
    }

    /**
     * @notice Withdraw native asset(e.g. ETH and AVAX) that this contract owns.
     * @dev only Coordinator can call this function
     * @param _recipient recipient address
     * @param _amountNative withdrawed amount
     */
    function withdrawNativeAsset(
        address _recipient,
        uint256 _amountNative
    ) external onlyCoordinator {
        // Transfer the asset to the recipient
        (bool sentToRecipient, ) = _recipient.call{value: _amountNative}("");
        if (!sentToRecipient) {
            revert CannotSendNativeAsset();
        }
    }

    /**
     * @notice Verify admin signatures for withdraw
     * @param _user user address
     * @param _asset asset address
     * @param _amount withdrawal amount
     * @param _recipient recipient address
     * @param _salts disambiguating salts for signatures
     * @param _signatures signatures generated by admins in the same order with _salts
     */
    function verifyWithdrawAdminSignatures(
        address _user,
        address _asset,
        uint256 _amount,
        address _recipient,
        bytes32[] calldata _salts,
        bytes[] calldata _signatures
    ) external onlyCoordinator {
        // Create message hash from withdrawal details and nonce for signature verification
        bytes32 messageHash = keccak256(
            bytes.concat(
                abi.encode(
                    WITHDRAW_TYPE_HASH,
                    _user,
                    _asset,
                    _amount,
                    _recipient,
                    adminNonce
                )
            )
        );
        // Verify that enough valid admin signatures were provided
        _verifyAdminSignatures(messageHash, _salts, _signatures);
    }

    /**
     * @notice Transfer the contract to a new team
     * @param _addingAdmins new admins to be added
     * @param _newName new name of collateral
     * @param _transferTeamSalts disambiguating salts for transfer team signatures
     * @param _transferTeamSignatures signatures generated by admins in the same order with _transferTeamSalts
     */
    function transferTeam(
        address[] calldata _addingAdmins,
        string calldata _newName,
        bytes32[] calldata _transferTeamSalts,
        bytes[] calldata _transferTeamSignatures,
        uint8 _adminThreshold
    ) public {
        // Cannot add 0 admins
        if (_addingAdmins.length == 0) {
            revert MinAdmins();
        }
        // Cannot add more than max admins
        if (_addingAdmins.length > MAX_ADMINS) {
            revert MaxAdmins();
        }

        // Create message hash from new admins and nonce for signature verification
        bytes32 messageHash = keccak256(
            bytes.concat(
                abi.encode(
                    TRANSFER_TEAM_TYPE_HASH,
                    keccak256(abi.encodePacked(_addingAdmins)),
                    keccak256(bytes(_newName)),
                    adminNonce
                )
            )
        );
        // Verify that enough valid admin signatures were provided
        _verifyAdminSignatures(
            messageHash,
            _transferTeamSalts,
            _transferTeamSignatures
        );

        // Reset admins array
        admins = new address[](0);

        // Add new admins to the array
        for (uint256 i = 0; i < _addingAdmins.length; i++) {
            if (_addingAdmins[i] == address(0)) {
                revert AddressZero();
            }

            // Check if the admin is already in the array
            (bool found, ) = _getAdminIndex(_addingAdmins[i]);
            if (found) {
                revert AdminAlreadyExists();
            }
            // Add the new admin to the admins array
            admins.push(_addingAdmins[i]);
        }

        name = _newName;

        // Cannot set threshold to be 0 or greater than number of admins
        if (_adminThreshold == 0 || _adminThreshold > admins.length) {
            revert InvalidAdminThreshold();
        }

        __adminThreshold = _adminThreshold;

        emit TransferTeam(_addingAdmins, _newName, _adminThreshold);
    }

    /**
     * @notice Update factory address
     * @dev only current factory can call this function
     * @param _newFactory new factory address
     */
    function updateFactory(
        address _newFactory
    ) external onlyFactory validAddress(_newFactory) {
        factory = _newFactory;
    }

    /**
     * @notice Get admin index from admins array
     * @dev Internal view function
     * @param _admin querying admin address
     * @return found if index is found or not
     * @return index admin address if found
     */
    function _getAdminIndex(
        address _admin
    ) internal view returns (bool, uint256) {
        // Iterate through admins array to find _admin
        for (uint256 i = 0; i < admins.length; i++) {
            if (admins[i] == _admin) {
                return (true, i);
            }
        }
        // Return false and 0 if _admin is not found
        return (false, 0);
    }

    /**
     * @notice Get Coordinator contract address from Factory contract
     * @dev Internal function to interact with Coordinator contract
     * @return address Coordinator contract address
     */
    function _getCoordinator() internal view returns (address) {
        // Controller address is kept in Factory
        return IFactory(factory).coordinator();
    }

    /**
     * @notice Sub function of _verifyPaymentSignature and _verifyWithdrawal
     *         to verify signature is from admins
     * @dev increment nonce when signature is valid
     * @param _messageHash keccak256 hashed message
     * @param _salts disambiguating salts for signatures
     * @param _signatures signatures generated by
     */
    function _verifyAdminSignatures(
        bytes32 _messageHash,
        bytes32[] calldata _salts,
        bytes[] calldata _signatures
    ) internal {
        // Check if the number of salts and signatures are the same
        if (_signatures.length != _salts.length) {
            revert InconsistentInputLength();
        }
        // Check if the number of signatures is greater than or equal to the admin threshold
        if (_signatures.length < adminThreshold()) {
            revert UnderAdminThreshold();
        }
        // Check if the number of signatures is greater than max admins
        if (_signatures.length > MAX_ADMINS) {
            revert AboveMaxAdmins();
        }

        // Array to check if admin is validated
        bool[] memory validationStatus = new bool[](admins.length);

        for (uint256 i = 0; i < _signatures.length; i++) {
            // Create domain separator for EIP712 signature verification
            bytes32 domainSeparator = keccak256(
                abi.encode(
                    EIP712_DOMAIN_TYPE_HASH,
                    keccak256(bytes(EIP712_DOMAIN_NAME)),
                    keccak256(bytes(EIP712_DOMAIN_VERSION)),
                    block.chainid,
                    address(this),
                    _salts[i]
                )
            );

            // Create digest to verify signature
            bytes32 digest = keccak256(
                abi.encodePacked("\x19\x01", domainSeparator, _messageHash)
            );

            bool isValidSignature;
            for (uint8 j = 0; j < admins.length; j++) {
                // Verify that the signature was generated by admin
                // Works for EOAs (ECDSA) and contract wallets (ERC-1271)
                bool ok = SignatureChecker.isValidSignatureNow(
                    admins[j],
                    digest,
                    _signatures[i]
                );
                if (ok) {
                    // Check if the admin is already validated
                    if (validationStatus[j]) {
                        revert DuplicateSigner();
                    }
                    validationStatus[j] = true;
                    isValidSignature = true;
                    break;
                }
            }

            if (!isValidSignature) {
                revert InvalidSignature();
            }
        }

        adminNonce++;
    }

    /**
     * @notice Receive native asset(e.g. ETH and AVAX)
     */
    receive() external payable {
        emit NativeAssetReceived(msg.sender, msg.value);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.