// File: @openzeppelin-5.0/contracts/proxy/Clones.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Clones.sol)

pragma solidity ^0.8.20;

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 */
library Clones {
    /**
     * @dev A clone instance deployment failed.
     */
    error ERC1167FailedCreateClone();

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(0, 0x09, 0x37)
        }
        if (instance == address(0)) {
            revert ERC1167FailedCreateClone();
        }
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(0, 0x09, 0x37, salt)
        }
        if (instance == address(0)) {
            revert ERC1167FailedCreateClone();
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), deployer)
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), implementation)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := keccak256(add(ptr, 0x43), 0x55)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}

// File: contracts/interfaces/v0.8.x/ISplitAtomicFactoryV0.sol



// SPDX-License-Identifier: LGPL-3.0-only
// Creatd By: Art Blocks Inc.

pragma solidity ^0.8.0;

import {Split} from "./ISplitAtomicV0.sol";

interface ISplitAtomicFactoryV0 {
    /**
     * @notice This contract was deployed.
     * @param implementation address with the implementation of the contract
     * @param type_ type of this contract
     * @param requiredSplitAddress address that must be included in all splits
     * @param requiredSplitBasisPoints basis points that must be included in
     * all splits
     */
    event Deployed(
        address indexed implementation,
        bytes32 indexed type_,
        address requiredSplitAddress,
        uint16 requiredSplitBasisPoints
    );
    /**
     * @notice New split atomic contract was created.
     * @param splitAtomic address of the newly created split atomic contract
     */
    event SplitAtomicCreated(address indexed splitAtomic);
    /**
     * @notice This contract was abandoned and no longer can be used to create
     * new split atomic contracts.
     */
    event Abandoned();

    /**
     * @notice Initializes the contract with the provided `splits`.
     * Only callable once.
     * @param splits Splits to configure the contract with. Must add up to
     * 10_000 BPS.
     * @return splitAtomic The address of the newly created split atomic
     * contract
     */
    function createSplit(
        Split[] calldata splits
    ) external returns (address splitAtomic);

    /**
     * @notice The implementation contract that is cloned when creating new
     * split atomic contracts.
     */
    function splitAtomicImplementation() external view returns (address);

    /**
     * @notice The address that must be included in all splits.
     */
    function requiredSplitAddress() external view returns (address);

    /**
     * @notice The basis points that must be included in all splits, for the
     * required split address.
     */
    function requiredSplitBasisPoints() external view returns (uint16);

    /**
     * @notice The deployer of the contract.
     */
    function deployer() external view returns (address);

    /**
     * @notice Indicates whether the contract is abandoned.
     * Once abandoned, the contract can no longer be used to create new split
     * atomic contracts.
     * @return bool True if the contract is abandoned, false otherwise.
     */
    function isAbandoned() external view returns (bool);

    /**
     * @notice Indicates the type of the contract, e.g. `SplitAtomicFactoryV0`.
     * @return type_ The type of the contract.
     */
    function type_() external pure returns (bytes32);
}

// File: contracts/interfaces/v0.8.x/ISplitAtomicV0.sol



// SPDX-License-Identifier: LGPL-3.0-only
// Creatd By: Art Blocks Inc.

pragma solidity ^0.8.0;

/**
 * @notice Struct representing a split.
 * @param recipient The address to send funds to.
 * @param basisPoints The basis points to allocate to recipient (1-10_000).
 */
struct Split {
    // address to send funds to
    address payable recipient;
    // basis points to allocate to recipient (1-10_000)
    uint16 basisPoints;
}

interface ISplitAtomicV0 {
    /**
     * @notice Indicates that the contract has been initialized.
     * @param type_ The type of the contract.
     */
    event Initialized(bytes32 type_);

    /**
     * @notice Indicates that the contract's balance manually was drained of
     * ETH.
     */
    event DrainedETH();

    /**
     * @notice Indicates that the contract's balance manually was drained of
     * ERC20 token at address `ERC20TokenAddress`.
     * @param ERC20TokenAddress The address of the ERC20 token that was
     * drained.
     */
    event DrainedERC20(address ERC20TokenAddress);

    /**
     * @notice Initializes the contract with the provided `splits`.
     * This function should be called atomically, immediately after deployment.
     * Only callable once.
     * @param splits Splits to configure the contract with. Must add up to
     * 10_000 BPS.
     */
    function initialize(Split[] calldata splits) external;

    /**
     * @notice Drains the contract's ETH balance to the configured `splits`.
     * Reverts if not initialized.
     */
    function drainETH() external;

    /**
     * @notice Drains the contract's balance of an input ERC20 token to the
     * configured `splits`. Reverts if not initialized.
     * @param ERC20TokenAddress The address of the ERC20 token to split.
     */
    function drainERC20(address ERC20TokenAddress) external;

    /**
     * @notice Returns the configured `splits`.
     * @return Split[] memory The configured `splits`.
     */
    function getSplits() external view returns (Split[] memory);

    /**
     * @notice Indicates the type of the contract, e.g. `SplitAtomicV0`.
     * @return type_ The type of the contract.
     */
    function type_() external pure returns (bytes32);
}

// File: contracts/split/SplitAtomicFactoryV0.sol



// SPDX-License-Identifier: LGPL-3.0-only
// Created By: Art Blocks Inc.

// @dev fixed to specific solidity version for clarity and for more clear
// source code verification purposes.
pragma solidity 0.8.22;

import {ISplitAtomicV0, Split} from "../interfaces/v0.8.x/ISplitAtomicV0.sol";
import {ISplitAtomicFactoryV0} from "../interfaces/v0.8.x/ISplitAtomicFactoryV0.sol";

import {Clones} from "@openzeppelin-5.0/contracts/proxy/Clones.sol";

/**
 * @title SplitAtomicFactoryV0
 * @author Art Blocks Inc.
 * @notice Factory contract for creating new split atomic contracts.
 * @dev This contract is deployed once, and then used to create new split
 * atomic contracts. The contract may be abandoned once it is no longer needed.
 * Once abandoned, the contract can no longer be used to create new split
 * atomic contracts.
 * The contract is initialized with a required split address and basis points.
 * All splits must include the required split address and basis points.
 * The contract is initialized with an implementation contract, which is cloned
 * when creating new split atomic contracts.
 */
contract SplitAtomicFactoryV0 is ISplitAtomicFactoryV0 {
    // public type
    bytes32 public constant type_ = "SplitAtomicFactoryV0";

    /**
     * The implementation contract that is cloned when creating new split
     * atomic contracts.
     */
    address public immutable splitAtomicImplementation;

    // required split address and basis points
    // @dev make immutable to avoid SLOAD on every createSplit call
    address public immutable requiredSplitAddress;
    uint16 public immutable requiredSplitBasisPoints;

    // deployer of the contract is the only one who may abandon the contract
    address public immutable deployer;

    /**
     * Indicates whether the contract is abandoned.
     * Once abandoned, the contract can no longer be used to create new split
     * atomic contracts.
     */
    bool public isAbandoned; // default false

    /**
     * @notice validates and assigns immutable configuration variables
     * @param splitAtomicImplementation_ address of the split atomic
     * implementation contract
     * @param requiredSplitAddress_ address that must be included in all splits
     * @param requiredSplitBasisPoints_ basis points that must be included in
     * all splits, for the required split address. Must be <= 10_000.
     */
    constructor(
        address splitAtomicImplementation_,
        address requiredSplitAddress_,
        uint16 requiredSplitBasisPoints_
    ) {
        // input validation
        require(
            requiredSplitBasisPoints_ <= 10_000,
            "only reqd split BPS <= 10_000"
        );
        splitAtomicImplementation = splitAtomicImplementation_;
        requiredSplitAddress = requiredSplitAddress_;
        requiredSplitBasisPoints = requiredSplitBasisPoints_;
        deployer = msg.sender;
        // emit event
        emit Deployed({
            implementation: splitAtomicImplementation_,
            type_: type_,
            requiredSplitAddress: requiredSplitAddress_,
            requiredSplitBasisPoints: requiredSplitBasisPoints_
        });
    }

    /**
     * @notice Creates a new split atomic contract with the provided `splits`.
     * @param splits Splits to configure the contract with. Must add up to
     * 10_000 BPS, and the first split must be the required split; reverts
     * otherwise.
     * @return splitAtomic The address of the newly created split atomic
     * contract. The address is also emitted in the `SplitAtomicCreated` event.
     */
    function createSplit(
        Split[] calldata splits
    ) external returns (address splitAtomic) {
        require(!isAbandoned, "factory is abandoned");
        // validate first split is initial split
        require(
            splits[0].recipient == requiredSplitAddress &&
                splits[0].basisPoints == requiredSplitBasisPoints,
            "splits[0] must be required split"
        );
        // Create the EIP 1167 split atomic contract
        splitAtomic = Clones.clone({implementation: splitAtomicImplementation});
        // initialize the new split atomic contract
        ISplitAtomicV0(splitAtomic).initialize(splits);
        // emit event
        emit SplitAtomicCreated(splitAtomic);
    }

    /**
     * @notice Abandons the contract, preventing it from being used to create
     * new split atomic contracts.
     * Only callable by the deployer, and only once; reverts otherwise.
     */
    function abandon() external {
        require(!isAbandoned, "factory is abandoned");
        require(msg.sender == deployer, "only deployer may abandon");
        // set isAbandoned to true
        isAbandoned = true;
        // emit event
        emit Abandoned();
    }
}