TrustProtocol

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "TrustProtocol.sol": {
      "content": "// SPDX-License-Identifier: MIT\r
pragma solidity ^0.8.20;\r
\r
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";\r
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";\r
import "@openzeppelin/contracts/access/Ownable.sol";\r
import "@openzeppelin/contracts/utils/math/Math.sol";\r
\r
/**\r
 * TrustProtocol - https://TrustProtocol.io\r
 * On-Chain Digital Trusts - Automated • Secure • Transparent\r
 */\r
\r
contract TrustProtocol is ERC20, ReentrancyGuard, Ownable {\r
    // Constants\r
    uint256 public constant TOTAL_SUPPLY = 1_000_000_000 * 10**18;\r
    uint256 public constant MAX_BENEFICIARIES_PER_GRANTOR = 10;\r
    uint256 public constant MAX_TRUSTS_PER_CALL = 10;\r
    uint256 public constant MIN_AMOUNT_PER_PERIOD = 10000000000000000;\r
    uint256 public constant MINUTES_PER_DAY = 1440;\r
    uint256 public constant MINUTES_PER_YEAR = 525600;\r
    uint256 public constant MAX_DURATION_YEARS = 100;\r
    uint256 public constant MAX_BACKDATE_SECONDS = 30 * 24 * 60 * 60;\r
    uint256 public constant MAX_FUTURE_SECONDS = 100 * 365 * 24 * 60 * 60;\r
    uint256 public constant MAX_FUTURE_MINUTES = 525600 * 100;\r
\r
    // Structs\r
    struct BeneficiaryParams {\r
        uint256 beneficiaryNumber;\r
        address beneficiary;\r
        uint256 amountPerPeriod;\r
        uint256 periodLengthInMinutes;\r
        uint256 totalPeriods;\r
        uint256 isIrrevocable;\r
        uint256 startTime;\r
    }\r
\r
    struct BeneficiaryConfig {\r
        address grantor;\r
        address beneficiary;\r
        uint256 amountPerPeriod;\r
        uint256 totalAmount;\r
        uint256 totalClaimed;\r
        uint256 startTime;\r
        uint256 endTime;\r
        uint256 periodLengthInMinutes;\r
        uint256 totalPeriods;\r
        uint256 periodsClaimed;\r
        bool isIrrevocable;\r
        bool isActive;\r
    }\r
\r
    struct BeneficiaryInfo {\r
        uint256 slot;\r
        address grantor;\r
        address beneficiary;\r
        uint256 totalAmount;\r
        uint256 amountPerPeriod;\r
        uint256 totalAccrued;\r
        uint256 totalClaimed;\r
        uint256 claimableAmount;\r
        uint256 startTime;\r
        uint256 endTime;\r
        uint256 periodLengthInMinutes;\r
        uint256 totalPeriods;\r
        uint256 periodsAccrued;\r
        uint256 periodsClaimed;\r
        uint256 periodsRemaining;\r
        uint256 nextClaimTime;\r
        bool isIrrevocable;\r
        bool isCompleted;\r
        bool isActive;\r
    }\r
\r
    struct TrustInfo {\r
        address grantor;\r
        uint256 beneficiaryNumber;\r
        BeneficiaryInfo info;\r
    }\r
\r
    struct AccruedAmounts {\r
        uint256 periodsElapsed;\r
        uint256 totalAccrued;\r
        uint256 claimableAmount;\r
    }\r
\r
    struct BeneficiaryIndex {\r
        address[] grantors;\r
        mapping(address => uint256) grantorIndex;\r
        mapping(address => bool) grantorExists;\r
        mapping(address => uint256[]) grantorSlots;\r
        uint256 totalTrusts;\r
        address[] allTrustsGrantors;\r
        uint256[] allTrustsSlots;\r
        mapping(bytes32 => uint256) trustIndex;\r
    }\r
\r
    // Mappings\r
    mapping(address => BeneficiaryConfig[MAX_BENEFICIARIES_PER_GRANTOR]) private _grantorBeneficiaries;\r
    mapping(address => BeneficiaryIndex) private _beneficiaryIndex;\r
\r
    // Events\r
    event BeneficiarySet(\r
        address indexed grantor,\r
        uint256 indexed beneficiaryNumber,\r
        address indexed beneficiary,\r
        uint256 amountPerPeriod,\r
        uint256 periodLengthInMinutes,\r
        uint256 totalPeriods,\r
        uint256 startTime,\r
        uint256 endTime,\r
        bool isIrrevocable\r
    );\r
\r
    event BeneficiaryRemoved(\r
        address indexed grantor,\r
        uint256 indexed beneficiaryNumber,\r
        address indexed beneficiary,\r
        uint256 unlockedAmount,\r
        bool tokensReturnedToGrantor\r
    );\r
\r
    event DistributionClaimed(\r
        address indexed grantor,\r
        uint256 indexed beneficiaryNumber,\r
        address indexed beneficiary,\r
        uint256 amount,\r
        uint256 periodStart,\r
        uint256 periodEnd,\r
        uint256 timestamp\r
    );\r
\r
    event IrrevocableTrustPaidOut(\r
        address indexed grantor,\r
        uint256 indexed beneficiaryNumber,\r
        address indexed beneficiary,\r
        uint256 amount,\r
        uint256 periodStart,\r
        uint256 periodEnd,\r
        uint256 timestamp\r
    );\r
\r
    // Modifiers\r
    modifier validBeneficiaryNumber(uint256 beneficiaryNumber) {\r
        require(beneficiaryNumber >= 1 && beneficiaryNumber <= MAX_BENEFICIARIES_PER_GRANTOR, "Invalid beneficiary number");\r
        _;\r
    }\r
\r
    modifier validIrrevocableFlag(uint256 isIrrevocable) {\r
        require(isIrrevocable == 0 || isIrrevocable == 1, "Invalid irrevocable flag");\r
        _;\r
    }\r
\r
    modifier slotNotActive(address grantor, uint256 beneficiaryNumber) {\r
        uint256 internalSlot = beneficiaryNumber - 1;\r
        require(!_grantorBeneficiaries[grantor][internalSlot].isActive, "Slot already active");\r
        _;\r
    }\r
\r
    constructor() ERC20("TrustProtocol", "XBEN") Ownable(msg.sender) {\r
        _mint(msg.sender, TOTAL_SUPPLY);\r
    }\r
\r
    // ========== PUBLIC VIEW FUNCTIONS ==========\r
\r
    function getMyTrustsCount() public view returns(uint256) {\r
        return _beneficiaryIndex[msg.sender].totalTrusts;\r
    }\r
\r
    function getMyTrusts(uint256 startIndex, uint256 count) public view returns(TrustInfo[] memory) {\r
        require(count > 0, "Count must be positive");\r
        require(count <= MAX_TRUSTS_PER_CALL, "Max 10 trusts per call");\r
        \r
        BeneficiaryIndex storage index = _beneficiaryIndex[msg.sender];\r
        uint256 totalTrusts = index.totalTrusts;\r
        \r
        if (totalTrusts == 0 || startIndex >= totalTrusts) {\r
            return new TrustInfo[](0);\r
        }\r
        \r
        uint256 resultCount = Math.min(count, totalTrusts - startIndex);\r
        TrustInfo[] memory result = new TrustInfo[](resultCount);\r
        \r
        for (uint256 i = 0; i < resultCount; i++) {\r
            uint256 trustNum = startIndex + i;\r
            address grantor = index.allTrustsGrantors[trustNum];\r
            uint256 slotNumber = index.allTrustsSlots[trustNum];\r
            uint256 internalSlot = slotNumber - 1;\r
            \r
            bytes32 trustKey = keccak256(abi.encodePacked(grantor, slotNumber));\r
            require(index.trustIndex[trustKey] == trustNum, "Trust index inconsistency");\r
            \r
            BeneficiaryConfig storage config = _grantorBeneficiaries[grantor][internalSlot];\r
            if (!config.isActive) continue;\r
            \r
            AccruedAmounts memory accrued = _calculateAccruedAmounts(config);\r
            uint256 periodsRemaining = config.totalPeriods - accrued.periodsElapsed;\r
            uint256 nextClaimTime = _calculateNextClaimTime(config, accrued.periodsElapsed);\r
            bool isCompleted = accrued.periodsElapsed >= config.totalPeriods;\r
            \r
            result[i] = TrustInfo({\r
                grantor: grantor,\r
                beneficiaryNumber: slotNumber,\r
                info: _createBeneficiaryInfo(config, slotNumber, accrued, periodsRemaining, nextClaimTime, isCompleted)\r
            });\r
        }\r
        \r
        return result;\r
    }\r
\r
    function getMyTrusts() public view returns(TrustInfo[] memory) {\r
        return getMyTrusts(0, MAX_TRUSTS_PER_CALL);\r
    }\r
\r
    function getMyBeneficiaries() public view returns(BeneficiaryInfo[] memory) {\r
        BeneficiaryConfig[MAX_BENEFICIARIES_PER_GRANTOR] storage beneficiaries = _grantorBeneficiaries[msg.sender];\r
        uint256 activeCount = 0;\r
        \r
        for(uint256 i = 0; i < MAX_BENEFICIARIES_PER_GRANTOR; i++) {\r
            if (beneficiaries[i].isActive) {\r
                activeCount++;\r
            }\r
        }\r
        \r
        BeneficiaryInfo[] memory result = new BeneficiaryInfo[](activeCount);\r
        uint256 resultIndex = 0;\r
        \r
        for(uint256 i = 0; i < MAX_BENEFICIARIES_PER_GRANTOR; i++) {\r
            BeneficiaryConfig storage config = beneficiaries[i];\r
            if (!config.isActive) continue;\r
            \r
            AccruedAmounts memory accrued = _calculateAccruedAmounts(config);\r
            uint256 periodsRemaining = config.totalPeriods - accrued.periodsElapsed;\r
            uint256 nextClaimTime = _calculateNextClaimTime(config, accrued.periodsElapsed);\r
            bool isCompleted = accrued.periodsElapsed >= config.totalPeriods;\r
\r
            result[resultIndex] = _createBeneficiaryInfo(config, i + 1, accrued, periodsRemaining, nextClaimTime, isCompleted);\r
            resultIndex++;\r
        }\r
        return result;\r
    }\r
\r
    function getAvailableBalance(address account) public view returns(uint256) {\r
        uint256 totalObligation = _calculateTotalObligation(account);\r
        uint256 currentBalance = balanceOf(account);\r
        return currentBalance > totalObligation ? currentBalance - totalObligation : 0;\r
    }\r
\r
    function getFinancialStatus(address account) public view returns(uint256 totalBalance, uint256 lockedBalance, uint256 availableBalance) {\r
        totalBalance = balanceOf(account);\r
        lockedBalance = _calculateTotalObligation(account);\r
        availableBalance = totalBalance > lockedBalance ? totalBalance - lockedBalance : 0;\r
    }\r
\r
    // ========== PUBLIC STATE-CHANGING FUNCTIONS ==========\r
\r
    function setBeneficiary(\r
        uint256 beneficiaryNumber,\r
        address beneficiary,\r
        uint256 amountPerPeriod,\r
        uint256 periodLengthInMinutes,\r
        uint256 totalPeriods,\r
        uint256 isIrrevocable,\r
        uint256 startTime\r
    ) external nonReentrant validBeneficiaryNumber(beneficiaryNumber) validIrrevocableFlag(isIrrevocable) \r
        slotNotActive(msg.sender, beneficiaryNumber) {\r
        \r
        BeneficiaryParams memory params = BeneficiaryParams({\r
            beneficiaryNumber: beneficiaryNumber,\r
            beneficiary: beneficiary,\r
            amountPerPeriod: amountPerPeriod,\r
            periodLengthInMinutes: periodLengthInMinutes,\r
            totalPeriods: totalPeriods,\r
            isIrrevocable: isIrrevocable,\r
            startTime: startTime\r
        });\r
        \r
        _setBeneficiary(params);\r
    }\r
\r
function removeBeneficiary(uint256 beneficiaryNumber) external nonReentrant validBeneficiaryNumber(beneficiaryNumber) {\r
    uint256 internalSlot = beneficiaryNumber - 1;\r
    BeneficiaryConfig storage config = _grantorBeneficiaries[msg.sender][internalSlot];\r
    \r
    require(config.isActive, "No beneficiary in this slot");\r
\r
    address removedBeneficiary = config.beneficiary;\r
    uint256 amountPerPeriod = config.amountPerPeriod;\r
    uint256 totalPeriods = config.totalPeriods;\r
    uint256 periodsClaimed = config.periodsClaimed;\r
    bool isIrrevocable = config.isIrrevocable;\r
    \r
    uint256 remainingPeriods = totalPeriods - periodsClaimed;\r
    uint256 unlockedAmount = remainingPeriods * amountPerPeriod;\r
    bool tokensReturnedToGrantor = !isIrrevocable;\r
\r
    config.isActive = false;\r
    _removeBeneficiaryFromMappings(removedBeneficiary, msg.sender, beneficiaryNumber);\r
    delete _grantorBeneficiaries[msg.sender][internalSlot];\r
\r
    if (isIrrevocable && unlockedAmount > 0) {\r
        emit IrrevocableTrustPaidOut(\r
            msg.sender,\r
            beneficiaryNumber,\r
            removedBeneficiary,\r
            unlockedAmount,\r
            periodsClaimed + 1,\r
            periodsClaimed + remainingPeriods,\r
            block.timestamp\r
        );\r
        \r
        _transfer(msg.sender, removedBeneficiary, unlockedAmount);\r
    }\r
\r
    emit BeneficiaryRemoved(msg.sender, beneficiaryNumber, removedBeneficiary, unlockedAmount, tokensReturnedToGrantor);\r
}\r
\r
    function claim(address grantor) external nonReentrant {\r
        BeneficiaryIndex storage index = _beneficiaryIndex[msg.sender];\r
        uint256[] storage beneficiaryNumbers = index.grantorSlots[grantor];\r
        require(beneficiaryNumbers.length > 0, "No trusts found");\r
\r
        uint256 totalClaimAmount = 0;\r
        uint256[] memory claimableNumbers = new uint256[](beneficiaryNumbers.length);\r
        uint256[] memory claimableAmounts = new uint256[](beneficiaryNumbers.length);\r
        uint256 claimablesCount = 0;\r
\r
        for (uint256 i = 0; i < beneficiaryNumbers.length; i++) {\r
            uint256 beneficiaryNumber = beneficiaryNumbers[i];\r
            uint256 internalSlot = beneficiaryNumber - 1;\r
            BeneficiaryConfig storage config = _grantorBeneficiaries[grantor][internalSlot];\r
\r
            if (!config.isActive || config.beneficiary != msg.sender) continue;\r
\r
            uint256 claimableAmount = _calculateClaimableAmountOnly(config);\r
            if (claimableAmount == 0) continue;\r
\r
            claimableNumbers[claimablesCount] = beneficiaryNumber;\r
            claimableAmounts[claimablesCount] = claimableAmount;\r
            claimablesCount++;\r
            totalClaimAmount += claimableAmount;\r
        }\r
\r
        require(totalClaimAmount > 0, "No claimable tokens found");\r
        require(totalClaimAmount <= getAvailableBalance(grantor), "Insufficient balance");\r
\r
        for (uint256 i = 0; i < claimablesCount; i++) {\r
            uint256 beneficiaryNumber = claimableNumbers[i];\r
            uint256 claimableAmount = claimableAmounts[i];\r
            uint256 internalSlot = beneficiaryNumber - 1;\r
            BeneficiaryConfig storage config = _grantorBeneficiaries[grantor][internalSlot];\r
\r
            _updateTrustAfterClaim(grantor, beneficiaryNumber, config, claimableAmount);\r
        }\r
\r
        _transfer(grantor, msg.sender, totalClaimAmount);\r
    }\r
\r
    // ========== INTERNAL FUNCTIONS ==========\r
\r
    function _calculateClaimableAmountOnly(BeneficiaryConfig storage config) internal view returns (uint256 claimableAmount) {\r
    if (block.timestamp < config.startTime) return 0;\r
\r
    uint256 currentTime = block.timestamp;\r
    uint256 minutesPassed;\r
    \r
    if (currentTime >= config.endTime) {\r
        minutesPassed = config.periodLengthInMinutes * config.totalPeriods;\r
    } else {\r
        minutesPassed = (currentTime - config.startTime) / 60;\r
    }\r
    \r
    uint256 periodsElapsed = minutesPassed / config.periodLengthInMinutes;\r
    if (periodsElapsed > config.totalPeriods) periodsElapsed = config.totalPeriods;\r
    \r
    if (periodsElapsed <= config.periodsClaimed) return 0;\r
    \r
    uint256 claimablePeriods = periodsElapsed - config.periodsClaimed;\r
    claimableAmount = claimablePeriods * config.amountPerPeriod;\r
    \r
    return claimableAmount;\r
    }\r
\r
    function _updateTrustAfterClaim(\r
        address grantor,\r
        uint256 beneficiaryNumber, \r
        BeneficiaryConfig storage config,\r
        uint256 claimAmount\r
    ) internal {\r
        uint256 periodsClaimedInThisCall = claimAmount / config.amountPerPeriod;\r
        config.totalClaimed += claimAmount;\r
        config.periodsClaimed += periodsClaimedInThisCall;\r
        \r
        emit DistributionClaimed(\r
            grantor,\r
            beneficiaryNumber,\r
            config.beneficiary,\r
            claimAmount,\r
            config.periodsClaimed - periodsClaimedInThisCall + 1,\r
            config.periodsClaimed,\r
            block.timestamp\r
        );\r
    }\r
\r
    function _setBeneficiary(BeneficiaryParams memory params) internal {\r
        if (params.startTime == 0) params.startTime = block.timestamp;\r
        \r
        _validateBeneficiaryParams(params);\r
        uint256 endTime = _calculateEndTime(params);\r
        _storeBeneficiaryConfig(params, endTime);\r
        _addBeneficiaryToTrustList(params.beneficiary, msg.sender, params.beneficiaryNumber);\r
        _emitBeneficiarySetEvent(params, endTime);\r
    }\r
\r
    function _addBeneficiaryToTrustList(address beneficiary, address grantor, uint256 beneficiaryNumber) internal {\r
        BeneficiaryIndex storage index = _beneficiaryIndex[beneficiary];\r
        \r
        if (!index.grantorExists[grantor]) {\r
            index.grantors.push(grantor);\r
            index.grantorIndex[grantor] = index.grantors.length - 1;\r
            index.grantorExists[grantor] = true;\r
        }\r
        \r
        index.grantorSlots[grantor].push(beneficiaryNumber);\r
        index.allTrustsGrantors.push(grantor);\r
        index.allTrustsSlots.push(beneficiaryNumber);\r
        \r
        bytes32 trustKey = keccak256(abi.encodePacked(grantor, beneficiaryNumber));\r
        index.trustIndex[trustKey] = index.allTrustsGrantors.length - 1;\r
        index.totalTrusts++;\r
    }\r
\r
    function _removeBeneficiaryFromMappings(address beneficiary, address grantor, uint256 beneficiaryNumber) internal {\r
        BeneficiaryIndex storage index = _beneficiaryIndex[beneficiary];\r
        bytes32 trustKey = keccak256(abi.encodePacked(grantor, beneficiaryNumber));\r
        uint256 trustPosition = index.trustIndex[trustKey];\r
        \r
        require(trustPosition < index.allTrustsGrantors.length, "Trust position out of bounds");\r
        require(index.allTrustsGrantors[trustPosition] == grantor, "Grantor mismatch");\r
        require(index.allTrustsSlots[trustPosition] == beneficiaryNumber, "Beneficiary number mismatch");\r
\r
        uint256[] storage slots = index.grantorSlots[grantor];\r
        uint256 slotPosition = _findSlotPosition(slots, beneficiaryNumber);\r
        \r
        if (slotPosition < slots.length - 1) {\r
            uint256 lastSlot = slots[slots.length - 1];\r
            slots[slotPosition] = lastSlot;\r
        }\r
        slots.pop();\r
        \r
        if (trustPosition < index.allTrustsGrantors.length - 1) {\r
            address lastGrantor = index.allTrustsGrantors[index.allTrustsGrantors.length - 1];\r
            uint256 lastSlotNumber = index.allTrustsSlots[index.allTrustsSlots.length - 1];\r
            \r
            index.allTrustsGrantors[trustPosition] = lastGrantor;\r
            index.allTrustsSlots[trustPosition] = lastSlotNumber;\r
            \r
            bytes32 lastTrustKey = keccak256(abi.encodePacked(lastGrantor, lastSlotNumber));\r
            index.trustIndex[lastTrustKey] = trustPosition;\r
        }\r
        \r
        index.allTrustsGrantors.pop();\r
        index.allTrustsSlots.pop();\r
        delete index.trustIndex[trustKey];\r
        index.totalTrusts--;\r
        \r
        if (slots.length == 0) {\r
            uint256 grantorPosition = index.grantorIndex[grantor];\r
            \r
            if (grantorPosition < index.grantors.length - 1) {\r
                address lastGrantor = index.grantors[index.grantors.length - 1];\r
                index.grantors[grantorPosition] = lastGrantor;\r
                index.grantorIndex[lastGrantor] = grantorPosition;\r
            }\r
            index.grantors.pop();\r
            delete index.grantorIndex[grantor];\r
            delete index.grantorExists[grantor];\r
            delete index.grantorSlots[grantor];\r
        }\r
    }\r
\r
    function _findSlotPosition(uint256[] storage slots, uint256 beneficiaryNumber) internal view returns (uint256) {\r
        for (uint256 i = 0; i < slots.length; i++) {\r
            if (slots[i] == beneficiaryNumber) return i;\r
        }\r
        revert("Slot not found");\r
    }\r
\r
function _validateBeneficiaryParams(BeneficiaryParams memory params) internal view {\r
    require(params.beneficiary != address(0), "Beneficiary cannot be zero address");\r
    require(params.beneficiary != msg.sender, "Cannot set self as beneficiary");\r
    \r
    require(params.amountPerPeriod >= MIN_AMOUNT_PER_PERIOD, "Amount per period must be at least 0.01 XBEN");\r
    require(params.amountPerPeriod <= TOTAL_SUPPLY, "Amount per period cannot exceed 1 billion XBEN");\r
    \r
    require(params.periodLengthInMinutes > 0, "Period length must be greater than zero");\r
    require(params.periodLengthInMinutes <= MAX_FUTURE_MINUTES, "Period length cannot exceed 100 years");\r
    \r
    require(params.totalPeriods > 0, "Total periods must be greater than zero");\r
    require(params.totalPeriods <= MAX_FUTURE_MINUTES, "Total periods cannot exceed 52,560,000");\r
\r
    uint256 totalDurationMinutes = params.periodLengthInMinutes * params.totalPeriods;\r
    require(totalDurationMinutes <= MAX_FUTURE_MINUTES, "Total duration cannot exceed 100 years");\r
    \r
    uint256 newTrustObligation = params.amountPerPeriod * params.totalPeriods;\r
    uint256 availableBalance = getAvailableBalance(msg.sender);\r
    require(availableBalance >= newTrustObligation, "Insufficient available XBEN balance");\r
    \r
    if (params.startTime != 0) {\r
        require(params.startTime <= block.timestamp + MAX_FUTURE_SECONDS, "Start time cannot be more than 100 years in future");\r
        if (params.startTime < block.timestamp) {\r
            require(block.timestamp - params.startTime <= MAX_BACKDATE_SECONDS, "Start time cannot be more than 30 days in past");\r
        }\r
    }\r
}\r
\r
    function _calculateEndTime(BeneficiaryParams memory params) internal pure returns (uint256) {\r
        return params.startTime + (params.periodLengthInMinutes * 60 * params.totalPeriods);\r
    }\r
\r
    function _storeBeneficiaryConfig(BeneficiaryParams memory params, uint256 endTime) internal {\r
        uint256 internalSlot = params.beneficiaryNumber - 1;\r
        BeneficiaryConfig storage config = _grantorBeneficiaries[msg.sender][internalSlot];\r
        uint256 totalObligation = params.amountPerPeriod * params.totalPeriods;\r
        \r
        config.grantor = msg.sender;\r
        config.beneficiary = params.beneficiary;\r
        config.amountPerPeriod = params.amountPerPeriod;\r
        config.totalAmount = totalObligation;\r
        config.totalClaimed = 0;\r
        config.startTime = params.startTime;\r
        config.endTime = endTime;\r
        config.periodLengthInMinutes = params.periodLengthInMinutes;\r
        config.totalPeriods = params.totalPeriods;\r
        config.periodsClaimed = 0;\r
        config.isIrrevocable = params.isIrrevocable == 1;\r
        config.isActive = true;\r
    }\r
\r
    function _emitBeneficiarySetEvent(BeneficiaryParams memory params, uint256 endTime) internal {\r
        emit BeneficiarySet(\r
            msg.sender, \r
            params.beneficiaryNumber, \r
            params.beneficiary, \r
            params.amountPerPeriod, \r
            params.periodLengthInMinutes, \r
            params.totalPeriods, \r
            params.startTime, \r
            endTime, \r
            params.isIrrevocable == 1\r
        );\r
    }\r
\r
    function _calculateAccruedAmounts(BeneficiaryConfig storage config) internal view returns (AccruedAmounts memory) {\r
    AccruedAmounts memory accrued;\r
    \r
    if (block.timestamp < config.startTime) return accrued;\r
\r
    uint256 currentTime = block.timestamp;\r
    uint256 minutesPassed;\r
    uint256 totalDurationMinutes = config.periodLengthInMinutes * config.totalPeriods;\r
    \r
    if (currentTime >= config.endTime) {\r
        minutesPassed = totalDurationMinutes;\r
    } else {\r
        minutesPassed = (currentTime - config.startTime) / 60;\r
    }\r
    \r
    accrued.totalAccrued = (config.amountPerPeriod * minutesPassed) / config.periodLengthInMinutes;\r
    if (accrued.totalAccrued > config.totalAmount) accrued.totalAccrued = config.totalAmount;\r
    \r
    accrued.periodsElapsed = minutesPassed / config.periodLengthInMinutes;\r
    if (accrued.periodsElapsed > config.totalPeriods) accrued.periodsElapsed = config.totalPeriods;\r
    \r
    accrued.claimableAmount = _calculateClaimableAmountOnly(config);\r
    \r
    return accrued;\r
    }\r
\r
    function _calculateNextClaimTime(BeneficiaryConfig storage config, uint256 periodsElapsed) internal view returns (uint256) {\r
        if (periodsElapsed >= config.totalPeriods) return 0;\r
        return config.startTime + ((config.periodsClaimed + 1) * config.periodLengthInMinutes * 60);\r
    }\r
\r
    function _calculateTotalObligation(address grantor) internal view returns(uint256 totalObligation) {\r
        BeneficiaryConfig[MAX_BENEFICIARIES_PER_GRANTOR] storage beneficiaries = _grantorBeneficiaries[grantor];\r
        \r
        for(uint256 i = 0; i < MAX_BENEFICIARIES_PER_GRANTOR; i++) {\r
            BeneficiaryConfig storage config = beneficiaries[i];\r
            if(config.isActive) totalObligation += (config.totalAmount - config.totalClaimed);\r
        }\r
    }\r
\r
    function _createBeneficiaryInfo(\r
        BeneficiaryConfig storage config,\r
        uint256 slot,\r
        AccruedAmounts memory accrued,\r
        uint256 periodsRemaining,\r
        uint256 nextClaimTime,\r
        bool isCompleted\r
    ) private view returns (BeneficiaryInfo memory) {\r
        return BeneficiaryInfo({\r
            slot: slot,\r
            grantor: config.grantor,\r
            beneficiary: config.beneficiary,\r
            totalAmount: config.totalAmount,\r
            amountPerPeriod: config.amountPerPeriod,\r
            totalAccrued: accrued.totalAccrued,\r
            totalClaimed: config.totalClaimed,\r
            claimableAmount: accrued.claimableAmount,\r
            startTime: config.startTime,\r
            endTime: config.endTime,\r
            periodLengthInMinutes: config.periodLengthInMinutes,\r
            totalPeriods: config.totalPeriods,\r
            periodsAccrued: accrued.periodsElapsed,\r
            periodsClaimed: config.periodsClaimed,\r
            periodsRemaining: periodsRemaining,\r
            nextClaimTime: nextClaimTime,\r
            isIrrevocable: config.isIrrevocable,\r
            isCompleted: isCompleted,\r
            isActive: config.isActive\r
        });\r
    }\r
\r
    // ERC20 overrides\r
    function transfer(address to, uint256 amount) public override returns (bool) {\r
        require(amount <= getAvailableBalance(msg.sender), "Exceeds available balance");\r
        return super.transfer(to, amount);\r
    }\r
\r
    function transferFrom(address from, address to, uint256 amount) public override returns (bool) {\r
        require(amount <= getAvailableBalance(from), "Exceeds available balance");\r
        return super.transferFrom(from, to, amount);\r
    }\r
}"
    },
    "@openzeppelin/contracts/utils/math/Math.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}
"
    },
    "@openzeppelin/contracts/access/Ownable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}
"
    },
    "@openzeppelin/contracts/security/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases 

Tags:
ERC20, Multisig, Upgradeable, Multi-Signature, Factory|addr:0xa49bf1560119e2df3316885d7ddb4a248b773e34|verified:true|block:23585057|tx:0x50b9a0a6bb7d24e4f2759b204deacd842949bd6ffc56701c32a1ff8177e3d3cd|first_check:1760598674

Submitted on: 2025-10-16 09:11:17

Comments

Log in to comment.

No comments yet.