Skip to content
Verified contractExactMIT

BundleCheckout

Address0xd336a3574d60f48aea70cfd03cbcdc047279a3fb
Balance

0 ETH

 

Transactions

3

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
No
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,366,074
Creation transaction
0x67f34c3383…7844b6f665

BundleCheckout.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

/// @notice Unlock factory. Deployed per network. This contract calls it to create a PublicLock.
interface IUnlockFactory {
    function createUpgradeableLockAtVersion(
        bytes memory data,
        uint16 lockVersion
    ) external returns (address);
}

/// @notice The PublicLock functions BundleCheckout uses. ETH locks only.
interface IPublicLock {
    function keyPrice() external view returns (uint256);

    function purchase(
        uint256[] memory values,
        address[] memory recipients,
        address[] memory referrers,
        address[] memory keyManagers,
        bytes[] calldata data
    ) external payable returns (uint256[] memory);

    function withdraw(address tokenAddress, address payable recipient, uint256 amount) external;

    function updateKeyPricing(uint256 keyPrice, address tokenAddress) external;

    function setEventHooks(
        address onKeyPurchaseHook,
        address onKeyCancelHook,
        address onValidKeyHook,
        address onTokenURIHook,
        address onKeyTransferHook,
        address onKeyExtendHook,
        address onKeyGrantHook,
        address onHasRoleHook
    ) external;

    function totalKeys(address owner) external view returns (uint256);

    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);

    function extend(uint256 value, uint256 tokenId, address referrer, bytes calldata data) external payable;

    function setKeyExpiration(uint256 tokenId, uint256 newExpiration) external;
}

/// @title BundleCheckout
/// @notice One Unlock membership per bundle. The subscription continues until it is cancelled.
/// @dev The holder pays once. The key does not expire. It becomes invalid only when that holder
///      cancels or the bundle owner closes the lock. renew is only how a holder subscribes again
///      after cancelling. The contract is the lock manager. Unlock may deduct its protocol fee
///      before the facilitator fee and the creator split.
contract BundleCheckout {
    uint256 public constant MAX_CREATORS = 25;
    uint256 public constant BPS_DENOMINATOR = 10_000;
    /// @notice Facilitator fee cannot be raised above 20% of the post-protocol-fee proceeds.
    uint256 public constant MAX_FACILITATOR_FEE_BPS = 2_000;

    address public immutable unlockAddress;
    uint16 public immutable publicLockVersion;
    address public facilitator;
    uint256 public facilitatorFeeBps;

    struct Bundle {
        address owner;
        address lock;
        string name;
        address[] creators;
    }

    uint256 public bundleCount;
    mapping(uint256 => Bundle) private _bundles;
    mapping(address => uint256) public bundleIdForLock;
    mapping(address => uint256) public pendingWithdrawals;
    /// @notice Bundle owner closed the lock. Every key on it is invalid.
    mapping(uint256 => bool) public lockCancelled;
    /// @notice Holder ended their own subscription. Their key is invalid until they renew.
    mapping(uint256 => mapping(address => bool)) public holderCancelled;

    uint256 private _entered;

    error ZeroAddress();
    error UnknownBundle(uint256 bundleId);
    error UnknownLock(address lock);
    error InvalidName();
    error InvalidPrice();
    error InvalidDuration();
    error InvalidLockVersion();
    error NoCreators();
    error TooManyCreators(uint256 count);
    error InvalidCreator(address creator);
    error DuplicateCreator(address creator);
    error NotBundleOwner(address caller);
    error NotFacilitator(address caller);
    error InvalidFacilitatorFee(uint256 bps);
    error WrongPayment(uint256 expected, uint256 actual);
    error DirectPurchaseDisabled();
    error DirectTransferDisabled();
    error Reentrancy();
    error NothingToClaim();
    error PaymentFailed();
    error LockCancelled(uint256 bundleId);
    error NoSubscription();
    error AlreadySubscribed(address holder);

    event BundleCreated(
        uint256 indexed bundleId,
        address indexed owner,
        address indexed lock,
        string name,
        uint256 keyPrice,
        uint256 expirationDuration
    );
    event PriceUpdated(uint256 indexed bundleId, uint256 keyPrice);
    event BundlePurchased(
        uint256 indexed bundleId,
        address indexed buyer,
        address indexed recipient,
        uint256 tokenId,
        uint256 paid,
        uint256 distributed,
        uint256 facilitatorFee
    );
    event FacilitatorPaid(uint256 indexed bundleId, address indexed facilitator, uint256 amount);
    event FacilitatorUpdated(address indexed facilitator);
    event FacilitatorFeeUpdated(uint256 facilitatorFeeBps);
    event CreatorPaid(uint256 indexed bundleId, address indexed creator, uint256 amount);
    event PaymentDeferred(uint256 indexed bundleId, address indexed creator, uint256 amount);
    event WithdrawalClaimed(address indexed creator, uint256 amount);
    event SubscriptionRenewed(
        uint256 indexed bundleId,
        address indexed holder,
        uint256 tokenId,
        uint256 paid,
        uint256 facilitatorFee
    );
    event SubscriptionCancelled(uint256 indexed bundleId, address indexed holder);
    event LockClosed(uint256 indexed bundleId, address indexed owner);

    modifier nonReentrant() {
        if (_entered == 1) revert Reentrancy();
        _entered = 1;
        _;
        _entered = 0;
    }

    /// @param unlockFactory Unlock factory for this chain.
    ///        Sepolia: 0x36b34e10295cCE69B652eEB5a8046041074515Da
    ///        Ethereum: 0xe79B93f8E22676774F2A8dAd469175ebd00029FA
    /// @param lockVersion PublicLock version registered on that factory. Use 15.
    /// @param facilitator_ Wallet that receives the facilitator fee on every sale.
    /// @param facilitatorFeeBps_ Fee in basis points of the proceeds left after Unlock's protocol fee.
    ///        300 is 3%. Cannot exceed MAX_FACILITATOR_FEE_BPS.
    constructor(address unlockFactory, uint16 lockVersion, address facilitator_, uint256 facilitatorFeeBps_) {
        if (unlockFactory == address(0) || facilitator_ == address(0) || facilitator_ == address(this)) {
            revert ZeroAddress();
        }
        if (lockVersion == 0) revert InvalidLockVersion();
        if (facilitatorFeeBps_ > MAX_FACILITATOR_FEE_BPS) revert InvalidFacilitatorFee(facilitatorFeeBps_);
        unlockAddress = unlockFactory;
        publicLockVersion = lockVersion;
        facilitator = facilitator_;
        facilitatorFeeBps = facilitatorFeeBps_;
    }

    /// @notice Move the facilitator fee to a new wallet. Unclaimed fees stay with the previous wallet.
    function setFacilitator(address nextFacilitator) external nonReentrant {
        if (msg.sender != facilitator) revert NotFacilitator(msg.sender);
        if (nextFacilitator == address(0) || nextFacilitator == address(this)) revert ZeroAddress();
        facilitator = nextFacilitator;
        emit FacilitatorUpdated(nextFacilitator);
    }

    /// @notice Change the facilitator fee for later purchases. Creators already paid are unchanged.
    function setFacilitatorFee(uint256 nextFeeBps) external nonReentrant {
        if (msg.sender != facilitator) revert NotFacilitator(msg.sender);
        if (nextFeeBps > MAX_FACILITATOR_FEE_BPS) revert InvalidFacilitatorFee(nextFeeBps);
        facilitatorFeeBps = nextFeeBps;
        emit FacilitatorFeeUpdated(nextFeeBps);
    }

    /// @notice Deploy a PublicLock and record who shares each sale.
    /// @param expirationDuration Kept so existing callers still pass a duration. Any non-zero
    ///        value is accepted. The lock is always non-expiring so the holder is not charged again.
    /// @dev maxNumberOfKeys is set to type(uint256).max. PublicLock v15 treats 0 as sold out.
    function createBundle(
        string calldata name,
        address[] calldata creators,
        uint256 keyPrice,
        uint256 expirationDuration
    ) external returns (uint256 bundleId, address lock) {
        if (bytes(name).length == 0 || bytes(name).length > 64) revert InvalidName();
        if (keyPrice == 0) revert InvalidPrice();
        if (expirationDuration == 0) revert InvalidDuration();
        uint256 count = creators.length;
        if (count == 0) revert NoCreators();
        if (count > MAX_CREATORS) revert TooManyCreators(count);

        // PublicLock treats this as a key that does not expire. Cancel is what invalidates it.
        uint256 duration = type(uint256).max;
        bytes memory data = abi.encodeWithSignature(
            "initialize(address,uint256,address,uint256,uint256,string)",
            address(this),
            duration,
            address(0),
            keyPrice,
            type(uint256).max,
            name
        );
        lock = IUnlockFactory(unlockAddress).createUpgradeableLockAtVersion(data, publicLockVersion);
        if (lock == address(0)) revert ZeroAddress();

        bundleId = ++bundleCount;
        Bundle storage bundle = _bundles[bundleId];
        bundle.owner = msg.sender;
        bundle.lock = lock;
        bundle.name = name;
        bundleIdForLock[lock] = bundleId;

        for (uint256 i = 0; i < count; i++) {
            address creator = creators[i];
            if (creator == address(0) || creator == address(this) || creator == lock) {
                revert InvalidCreator(creator);
            }
            for (uint256 j = 0; j < i; j++) {
                if (creators[j] == creator) revert DuplicateCreator(creator);
            }
            bundle.creators.push(creator);
        }

        // Purchase and extend must come through this contract. The valid-key hook
        // rejects a holder who cancelled and every key after the owner closes the lock.
        IPublicLock(lock).setEventHooks(
            address(this),
            address(0),
            address(this),
            address(0),
            address(0),
            address(this),
            address(0),
            address(0)
        );

        emit BundleCreated(bundleId, msg.sender, lock, name, keyPrice, duration);
    }

    /// @notice Change the key price for future purchases. Creators stay the ones set at creation.
    function setKeyPrice(uint256 bundleId, uint256 keyPrice) external {
        Bundle storage bundle = _bundle(bundleId);
        if (msg.sender != bundle.owner) revert NotBundleOwner(msg.sender);
        if (keyPrice == 0) revert InvalidPrice();
        IPublicLock(bundle.lock).updateKeyPricing(keyPrice, address(0));
        emit PriceUpdated(bundleId, keyPrice);
    }

    /// @notice Buy one membership key. msg.value must equal the current key price.
    /// @dev Unlock's protocol fee comes out first. The facilitator fee is a percentage of what remains.
    ///      Creators split the rest in equal shares. Referrer fee is not used.
    function buy(uint256 bundleId, address recipient)
        external
        payable
        nonReentrant
        returns (uint256 tokenId)
    {
        Bundle storage bundle = _bundle(bundleId);
        if (recipient == address(0)) revert ZeroAddress();
        if (lockCancelled[bundleId]) revert LockCancelled(bundleId);
        if (IPublicLock(bundle.lock).totalKeys(recipient) > 0) revert AlreadySubscribed(recipient);

        uint256 price = IPublicLock(bundle.lock).keyPrice();
        if (msg.value != price) revert WrongPayment(price, msg.value);

        uint256 lockBefore = bundle.lock.balance;
        uint256 selfBefore = address(this).balance - msg.value;
        tokenId = _purchase(bundle.lock, recipient, price);

        uint256 lockAfter = bundle.lock.balance;
        if (lockAfter > lockBefore) {
            IPublicLock(bundle.lock).withdraw(address(0), payable(address(this)), lockAfter - lockBefore);
        }

        uint256 distributed = address(this).balance - selfBefore;
        uint256 facilitatorFee = _settle(bundleId, bundle.creators, distributed);
        emit BundlePurchased(bundleId, msg.sender, recipient, tokenId, msg.value, distributed, facilitatorFee);
    }

    /// @notice Subscribe again after cancelling. An active key does not need this.
    /// @dev Clears a holder cancellation. Reverts when the bundle owner has closed the lock.
    ///      PublicLock reverts if the key is still non-expiring.
    function renew(uint256 bundleId) external payable nonReentrant returns (uint256 tokenId) {
        Bundle storage bundle = _bundle(bundleId);
        if (lockCancelled[bundleId]) revert LockCancelled(bundleId);

        IPublicLock lock = IPublicLock(bundle.lock);
        if (lock.totalKeys(msg.sender) == 0) revert NoSubscription();
        tokenId = lock.tokenOfOwnerByIndex(msg.sender, 0);

        uint256 price = lock.keyPrice();
        if (msg.value != price) revert WrongPayment(price, msg.value);

        holderCancelled[bundleId][msg.sender] = false;

        uint256 lockBefore = bundle.lock.balance;
        uint256 selfBefore = address(this).balance - msg.value;
        lock.extend{value: price}(price, tokenId, address(0), "");

        uint256 distributed = _takeProceeds(bundle.lock, lockBefore, selfBefore);
        uint256 facilitatorFee = _settle(bundleId, bundle.creators, distributed);
        emit SubscriptionRenewed(bundleId, msg.sender, tokenId, msg.value, facilitatorFee);
    }

    /// @notice Key holder ends their subscription. The key is invalid immediately.
    /// @dev They can subscribe again with renew, which starts a new paid period.
    function cancelSubscription(uint256 bundleId) external nonReentrant {
        Bundle storage bundle = _bundle(bundleId);
        if (lockCancelled[bundleId]) revert LockCancelled(bundleId);

        IPublicLock lock = IPublicLock(bundle.lock);
        uint256 count = lock.totalKeys(msg.sender);
        if (count == 0) revert NoSubscription();

        uint256[] memory tokenIds = new uint256[](count);
        for (uint256 i = 0; i < count; i++) {
            tokenIds[i] = lock.tokenOfOwnerByIndex(msg.sender, i);
        }
        holderCancelled[bundleId][msg.sender] = true;
        for (uint256 i = 0; i < count; i++) {
            lock.setKeyExpiration(tokenIds[i], block.timestamp);
        }
        emit SubscriptionCancelled(bundleId, msg.sender);
    }

    /// @notice Bundle owner closes the lock. Every key becomes invalid and new sales revert.
    function cancelLock(uint256 bundleId) external {
        Bundle storage bundle = _bundle(bundleId);
        if (msg.sender != bundle.owner) revert NotBundleOwner(msg.sender);
        if (lockCancelled[bundleId]) revert LockCancelled(bundleId);
        lockCancelled[bundleId] = true;
        emit LockClosed(bundleId, msg.sender);
    }

    /// @notice Collect a share that could not be pushed during buy.
    function claim() external nonReentrant {
        uint256 amount = pendingWithdrawals[msg.sender];
        if (amount == 0) revert NothingToClaim();
        pendingWithdrawals[msg.sender] = 0;
        (bool ok,) = msg.sender.call{value: amount}("");
        if (!ok) {
            pendingWithdrawals[msg.sender] = amount;
            revert PaymentFailed();
        }
        emit WithdrawalClaimed(msg.sender, amount);
    }

    function getBundle(uint256 bundleId)
        external
        view
        returns (address owner, address lock, string memory name, uint256 keyPrice, uint256 creatorCount)
    {
        Bundle storage bundle = _bundle(bundleId);
        owner = bundle.owner;
        lock = bundle.lock;
        name = bundle.name;
        keyPrice = IPublicLock(lock).keyPrice();
        creatorCount = bundle.creators.length;
    }

    function getCreators(uint256 bundleId) external view returns (address[] memory) {
        return _bundle(bundleId).creators;
    }

    /// @dev Called by PublicLock before a purchase. Price stays the lock's ETH price.
    function keyPurchasePrice(address, address, address, bytes calldata) external view returns (uint256) {
        if (bundleIdForLock[msg.sender] == 0) revert UnknownLock(msg.sender);
        return IPublicLock(msg.sender).keyPrice();
    }

    /// @dev Called by PublicLock during purchase, before it pays the protocol fee.
    ///      Direct buyers are rejected. This function does not withdraw.
    function onKeyPurchase(uint256, address from, address, address, bytes calldata, uint256, uint256) external view {
        if (bundleIdForLock[msg.sender] == 0) revert UnknownLock(msg.sender);
        if (from != address(this)) revert DirectPurchaseDisabled();
    }

    /// @dev Called by PublicLock on extend. Only BundleCheckout.renew may extend a key.
    function onKeyExtend(uint256, address from, uint256, uint256) external view {
        if (bundleIdForLock[msg.sender] == 0) revert UnknownLock(msg.sender);
        if (from != address(this)) revert DirectPurchaseDisabled();
    }

    /// @dev Called by PublicLock from isValidKey and getHasValidKey.
    ///      Keys do not expire. Cancel flags are what make `isValid` end in false for the owner close,
    ///      and holderCancelled covers a key whose timestamp was cleared.
    function isValidKey(
        address,
        address,
        uint256,
        uint256,
        address keyOwner,
        bool isValid
    ) external view returns (bool) {
        uint256 bundleId = bundleIdForLock[msg.sender];
        if (bundleId == 0) return false;
        if (lockCancelled[bundleId] || holderCancelled[bundleId][keyOwner]) return false;
        return isValid;
    }

    /// @dev Accept ETH only from a lock this contract deployed (withdraw and gas refund).
    receive() external payable {
        if (bundleIdForLock[msg.sender] == 0) revert DirectTransferDisabled();
    }

    function _purchase(address lock, address recipient, uint256 price) private returns (uint256 tokenId) {
        uint256[] memory values = new uint256[](1);
        values[0] = price;
        address[] memory recipients = new address[](1);
        recipients[0] = recipient;
        address[] memory referrers = new address[](1);
        address[] memory keyManagers = new address[](1);
        keyManagers[0] = recipient;
        bytes[] memory data = new bytes[](1);

        uint256[] memory tokenIds = IPublicLock(lock).purchase{value: price}(
            values,
            recipients,
            referrers,
            keyManagers,
            data
        );
        tokenId = tokenIds[0];
    }

    function _bundle(uint256 bundleId) private view returns (Bundle storage bundle) {
        bundle = _bundles[bundleId];
        if (bundle.lock == address(0)) revert UnknownBundle(bundleId);
    }

    function _takeProceeds(address lock, uint256 lockBefore, uint256 selfBefore)
        private
        returns (uint256 distributed)
    {
        uint256 lockAfter = lock.balance;
        if (lockAfter > lockBefore) {
            IPublicLock(lock).withdraw(address(0), payable(address(this)), lockAfter - lockBefore);
        }
        distributed = address(this).balance - selfBefore;
    }

    /// @dev Pay the facilitator, then split the remainder across creators. Returns the fee taken.
    function _settle(uint256 bundleId, address[] storage creators, uint256 amount) private returns (uint256 fee) {
        fee = (amount * facilitatorFeeBps) / BPS_DENOMINATOR;
        address payee = facilitator;
        if (fee > 0) {
            if (_tryPay(payee, fee)) {
                emit FacilitatorPaid(bundleId, payee, fee);
            } else {
                pendingWithdrawals[payee] += fee;
                emit PaymentDeferred(bundleId, payee, fee);
            }
        }
        _split(bundleId, creators, amount - fee);
    }

    /// @dev Equal shares. The first creators receive one extra wei until the remainder is gone.
    ///      A creator that rejects the transfer is credited for claim().
    function _split(uint256 bundleId, address[] storage creators, uint256 amount) private {
        uint256 count = creators.length;
        if (count == 0 || amount == 0) return;

        uint256 share = amount / count;
        uint256 remainder = amount % count;

        for (uint256 i = 0; i < count; i++) {
            uint256 payout = share;
            if (i < remainder) payout += 1;
            if (payout == 0) continue;

            address creator = creators[i];
            if (_tryPay(creator, payout)) {
                emit CreatorPaid(bundleId, creator, payout);
            } else {
                pendingWithdrawals[creator] += payout;
                emit PaymentDeferred(bundleId, creator, payout);
            }
        }
    }

    function _tryPay(address recipient, uint256 payout) private returns (bool) {
        (bool ok,) = recipient.call{value: payout, gas: 100_000}("");
        return ok;
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": false
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.