Skip to content
Verified contractExactMIT

Kungaupei

Address0x737cdd61c72cbd0320c06c976dda960307aef12e
Balance

0 ETH

 

Transactions

78

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,162,836
Creation transaction
0xd9ab40204d…15c04034a6

contracts/Kungaupei.sol

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

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {CellKeyRegistry} from "./CellKeyRegistry.sol";
import {SealedRendezvousVault} from "./SealedRendezvousVault.sol";
import {PromiseScoreLedger} from "./PromiseScoreLedger.sol";
import {BurnSignalBook} from "./BurnSignalBook.sol";

/*
 *
 *                        _.-._
 *                      .'  _  '.
 *                     (   ( )   )        no head
 *       ~ ~ ~ ~ ~ ~ ~ ~ '.     .' ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 *      ----------------------`-'-----------------------------
 *                 |        |        |        |
 *               . |      . |      . |      . |
 *              /|\|     /| |     /|\|      \| |
 *             / | \\   / |  \   //  |  \     \  |
 *            o  |  o  o  |   o o   |   o     o |
 *               |      /  \       / | \        |
 *               o     o    o     o  o  o       o
 *
 *            K  U  N  G  A  U  P  E  I
 *
 *             grow roots. no head to cut off.
 *
 *                 https://kungaupei.com
 *
 */

/**
 * @title Kungaupei
 * @notice ERC20 token of Kungaupei ($KUNG), the secret underground network of Dzego and a private
 *         coordination layer for people who have to act together without a leader to arrest.
 *
 * @dev PROJECT
 *      The name comes from Vitalik Buterin's novel Snowmoon, where Kungaupei is the hidden network that
 *      holds Dzego together. Its motto is "Grow roots, no head", and its warning is to resist the Arctic
 *      Empire without becoming the Arctic Empire. The network is built from cells, small groups that are
 *      joined by a key and not by a name. A cell sets up meetings that stay sealed until the bell, then
 *      opens them for a short window and wipes them. People earn a coordination score by the promises
 *      they keep, and nothing else raises it. Anyone who wants to say something loudly can burn $KUNG,
 *      because a signal that costs something is harder to fake. Safehouses and couriers make up the map,
 *      and everything runs in seasons of fourteen nights.
 *
 * @dev SUPPLY
 *      1,000,000,000 KUNG are minted once, to the deployer, in the constructor. There is no owner, no
 *      pause, no blacklist and no way to mint again. Any holder can burn their own tokens, and burning is
 *      the only way supply decreases.
 *
 * @dev KUNGAUPEI CONTRACTS
 *      The six contracts that run the network are deployed by this contract in its constructor, so one
 *      deployment creates all of them and their addresses are readable from here. They cover the cells and
 *      their keys, the sealed meetings, the promise score, the burn signals, the safehouses and couriers
 *      and the fourteen-night season. The deployer is the operator of all six.
 *
 * Website: https://kungaupei.com
 */
contract Kungaupei {
    string  private constant _NAME   = "Kungaupei";
    string  private constant _SYMBOL = "KUNG";
    uint8   private constant _DEC    = 18;
    uint256 private constant _SUPPLY = 1000000000 * 10**18;
    uint256 public constant MIN_TERM = 1 hours;
    uint256 public constant MAX_TERM = 90 days;
    uint256 public constant MAX_OPEN = 16;
    uint256 public constant PAIR_LIMIT = 5;
    uint256 public constant SNAPSHOT_EVERY = 1 days;

    enum State { None, Open, Claimed, Kept, Broken, Lapsed, Released }

    struct Promise_ {
        address promisor;
        address counterparty;
        bytes32 what;
        uint64 madeAt;
        uint64 due;
        uint64 proposedDue;
        State state;
    }

    address public operator;
    uint256 public grace = 3 days;
    uint256 public promiseCount;

    mapping(uint256 => Promise_) public promises;
    mapping(address => uint256) public keptCount;
    mapping(address => uint256) public brokenCount;
    mapping(address => uint256) public lapsedCount;
    mapping(address => uint256) public openCount;
    mapping(bytes32 => uint256) public pairCredits;
    mapping(address => uint256) public snapshotScore;
    mapping(address => uint256) public snapshotAt;

    event Pledged(uint256 indexed id, address indexed promisor, address indexed counterparty, uint256 due);
    event Claimed(uint256 indexed id);
    event Kept(uint256 indexed id, bool counted);
    event Broken(uint256 indexed id);
    event Lapsed(uint256 indexed id);
    event Released(uint256 indexed id);
    event MoreTimeAsked(uint256 indexed id, uint256 due);
    event MoreTimeGranted(uint256 indexed id, uint256 due);
    event Snapshot(address indexed who, uint256 score);
    event OperatorChanged(address indexed from, address indexed to);
    mapping(address => uint256) private _bal;
    mapping(address => mapping(address => uint256)) private _allow;
    uint256 private _tot;

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);

    error LowBalance(uint256 have, uint256 need);
    error LowAllowance(uint256 have, uint256 need);
    error BadRecipient();

    constructor() {
        _tot = _SUPPLY;
        _bal[msg.sender] = _SUPPLY;
        emit Transfer(address(0), msg.sender, _SUPPLY);
    }

    function name() external pure returns (string memory) { return _NAME; }
    function symbol() external pure returns (string memory) { return _SYMBOL; }
    function decimals() external pure returns (uint8) { return _DEC; }
    function totalSupply() external view returns (uint256) { return _tot; }
    function balanceOf(address a) external view returns (uint256) { return _bal[a]; }
    function allowance(address o, address s) external view returns (uint256) { return _allow[o][s]; }

    function approve(address spender, uint256 value) external returns (bool) {
        _allow[msg.sender][spender] = value;
        emit Approval(msg.sender, spender, value);
        return true;
    }

    function transfer(address to, uint256 value) external returns (bool) {
        _pay(msg.sender, to, value);
        return true;
    }

    function transferFrom(address from, address to, uint256 value) external returns (bool) {
        _spend(from, value);
        _pay(from, to, value);
        return true;
    }

    function burn(uint256 value) external {
        _destroy(msg.sender, value);
    }

    function burnFrom(address from, uint256 value) external {
        _spend(from, value);
        _destroy(from, value);
    }

    function _pay(address from, address to, uint256 value) private {
        if (to == address(0)) revert BadRecipient();
        uint256 h = _bal[from];
        if (h < value) revert LowBalance(h, value);
        unchecked { _bal[from] = h - value; _bal[to] += value; }
        emit Transfer(from, to, value);
    }

    function _destroy(address from, uint256 value) private {
        uint256 h = _bal[from];
        if (h < value) revert LowBalance(h, value);
        unchecked { _bal[from] = h - value; _tot -= value; }
        emit Transfer(from, address(0), value);
    }

    function _spend(address owner_, uint256 value) private {
        uint256 a = _allow[owner_][msg.sender];
        if (a != type(uint256).max) {
            if (a < value) revert LowAllowance(a, value);
            unchecked { _allow[owner_][msg.sender] = a - value; }
        }
    }
}

@openzeppelin/contracts/interfaces/draft-IERC6093.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)

pragma solidity >=0.8.4;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

@openzeppelin/contracts/token/ERC20/ERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

    mapping(address account => mapping(address spender => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * Both values are immutable: they can only be set once during construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /// @inheritdoc IERC20
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /// @inheritdoc IERC20
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /// @inheritdoc IERC20
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner`'s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance < type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity >=0.6.2;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

contracts/BurnSignalBook.sol

pragma solidity ^0.8.24;

interface IKungBurn {
    function burnFrom(address from, uint256 amount) external;
    function balanceOf(address who) external view returns (uint256);
    function allowance(address owner, address spender) external view returns (uint256);
}

/**
 * @title BurnSignalBook
 * @notice Turns burning $KUNG into a costly signal. Anything can be said for free, but a signal backed by
 *         tokens that are gone for good is hard to fake, so Kungaupei lets people attach a burn to a tag,
 *         to a person or to a cell and reads the total as how much it matters.
 *
 * @dev The caller approves this contract on the token and then signals. The tokens are burned straight
 *      from the caller and the amount is recorded against the signal. Anyone can add more to an existing
 *      signal. A signal that collects a thousand tokens is marked as heard. A person's burn weight halves
 *      every seven days, so an old burn counts for less than a recent one. Every write function is total
 *      and returns false or zero instead of reverting, including when the allowance or balance is short.
 *
 * Website: https://kungaupei.com
 */
contract BurnSignalBook {
    string public constant WEBSITE = "https://kungaupei.com";
    uint256 public constant HEARD_AT = 1_000 ether;
    uint256 public constant HALF_LIFE = 7 days;
    uint256 public constant MAX_HALVINGS = 16;

    enum Kind { Tag, Person, Cell }

    struct Signal {
        address from;
        address aimedAt;
        bytes32 tag;
        uint256 cellId;
        uint256 total;
        uint64 at;
        Kind kind;
        bool heard;
    }

    IKungBurn public immutable kung;
    address public operator;
    uint256 public minimum = 1 ether;
    uint256 public signalCount;
    uint256 public totalSignalled;
    uint256 public heardCount;
    uint256 public topSignal;
    bool private _busy;

    mapping(uint256 => Signal) public signals;
    mapping(address => uint256) public burnedHere;
    mapping(address => uint256) private _weight;
    mapping(address => uint256) private _stamp;
    mapping(address => uint256) public aimedTotal;
    mapping(uint256 => uint256) public cellTotal;
    mapping(bytes32 => uint256) public tagTotal;

    event Signalled(uint256 indexed id, address indexed from, Kind kind, uint256 amount);
    event Amplified(uint256 indexed id, address indexed from, uint256 amount);
    event Heard(uint256 indexed id, uint256 total);
    event OperatorChanged(address indexed from, address indexed to);

    constructor(address operator_, address kung_) {
        operator = operator_ == address(0) ? msg.sender : operator_;
        kung = IKungBurn(kung_);
    }

    /// @notice Burns tokens behind a tag. Returns the signal id, or zero.
    function signal(bytes32 tag, uint256 amount) external returns (uint256 id) {
        if (tag == bytes32(0)) return 0;
        id = _open(Kind.Tag, address(0), tag, 0, amount);
        if (id != 0) tagTotal[tag] += amount;
    }

    /// @notice Burns tokens in support of a person.
    function signalPerson(address who, uint256 amount) external returns (uint256 id) {
        if (who == address(0) || who == msg.sender) return 0;
        id = _open(Kind.Person, who, bytes32(0), 0, amount);
        if (id != 0) aimedTotal[who] += amount;
    }

    /// @notice Burns tokens in support of a cell.
    function signalCell(uint256 cellId, bytes32 tag, uint256 amount) external returns (uint256 id) {
        if (cellId == 0) return 0;
        id = _open(Kind.Cell, address(0), tag, cellId, amount);
        if (id != 0) cellTotal[cellId] += amount;
    }

    /// @notice Adds a burn to a signal that already exists. Anyone can back anyone.
    function amplify(uint256 id, uint256 amount) external returns (bool) {
        Signal storage s = signals[id];
        if (s.at == 0 || !_burn(amount)) return false;
        s.total += amount;
        totalSignalled += amount;
        if (s.kind == Kind.Tag) tagTotal[s.tag] += amount;
        else if (s.kind == Kind.Person) aimedTotal[s.aimedAt] += amount;
        else cellTotal[s.cellId] += amount;
        if (s.total > signals[topSignal].total) topSignal = id;
        emit Amplified(id, msg.sender, amount);
        return true;
    }

    /// @notice Sets the smallest burn that counts, between a millionth of a token and a thousand tokens.
    function setMinimum(uint256 amount) external returns (bool) {
        if (msg.sender != operator || amount < 1e12 || amount > 1_000 ether) return false;
        minimum = amount;
        return true;
    }

    function handOver(address next) external returns (bool) {
        if (msg.sender != operator || next == address(0) || next == operator) return false;
        emit OperatorChanged(operator, next);
        operator = next;
        return true;
    }

    /// @notice Marks a signal as heard once it has collected enough. Anyone can call it.
    function execute(uint256 id) external returns (bool) {
        Signal storage s = signals[id];
        if (s.at == 0 || s.heard || s.total < HEARD_AT) return false;
        s.heard = true;
        heardCount += 1;
        emit Heard(id, s.total);
        return true;
    }

    /// @notice Burn weight of an account today, halved for every seven days since its last burn.
    function weightOf(address who) public view returns (uint256) {
        uint256 w = _weight[who];
        if (w == 0) return 0;
        uint256 halvings = (block.timestamp - _stamp[who]) / HALF_LIFE;
        if (halvings >= MAX_HALVINGS) return 0;
        return w >> halvings;
    }

    function _open(Kind kind, address aimedAt, bytes32 tag, uint256 cellId, uint256 amount) private returns (uint256 id) {
        if (!_burn(amount)) return 0;
        id = ++signalCount;
        signals[id] = Signal(msg.sender, aimedAt, tag, cellId, amount, uint64(block.timestamp), kind, false);
        totalSignalled += amount;
        if (amount > signals[topSignal].total) topSignal = id;
        emit Signalled(id, msg.sender, kind, amount);
    }

    function _burn(uint256 amount) private returns (bool) {
        if (_busy || amount < minimum) return false;
        if (kung.balanceOf(msg.sender) < amount || kung.allowance(msg.sender, address(this)) < amount) return false;
        _busy = true;
        bool ok;
        try kung.burnFrom(msg.sender, amount) {
            ok = true;
        } catch {
            ok = false;
        }
        _busy = false;
        if (!ok) return false;
        _weight[msg.sender] = weightOf(msg.sender) + amount;
        _stamp[msg.sender] = block.timestamp;
        burnedHere[msg.sender] += amount;
        return true;
    }
}

contracts/CellKeyRegistry.sol


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

/**
 * @title CellKeyRegistry
 * @notice Records the cells of Kungaupei. A cell is a small group that is joined by a key, never by a
 *         name: the registry stores only the hash of the key, and a person is let in by showing the
 *         secret behind it.
 *
 * @dev No list of members is kept, only how many there are and which cell each address sits in, so the
 *      contract cannot be asked who belongs to a cell. A member can rotate the key, close the doors,
 *      change the size limit or leave. A cell that goes quiet for thirty days is marked dormant and is
 *      revived by any member showing up. Every write function is total and returns false or zero
 *      instead of reverting.
 *Kungaupei
 * Website: https://kungaupei.com
 */
contract CellKeyRegistry {
    string public constant WEBSITE = "https://kungaupei.com";
    uint256 public constant IDLE_LIMIT = 30 days;
    uint256 public constant HARD_CAP = 1024;
    uint256 public constant MIN_CAP = 2;

    struct Cell {
        bytes32 keyHash;
        uint64 formedAt;
        uint64 lastSeen;
        uint32 members;
        uint16 cap;
        bool doorsOpen;
        bool dormant;
    }

    address public operator;
    uint256 public memberCap = 64;
    uint256 public cellCount;
    uint256 public liveCells;

    mapping(uint256 => Cell) public cells;
    mapping(address => uint256) public cellOf;
    mapping(bytes32 => bool) public keyInUse;

    event CellFormed(uint256 indexed id, uint256 cap);
    event Joined(uint256 indexed id, address indexed member);
    event Left(uint256 indexed id, address indexed member);
    event KeyRotated(uint256 indexed id);
    event DoorsChanged(uint256 indexed id, bool open);
    event CapChanged(uint256 indexed id, uint256 cap);
    event CellDormant(uint256 indexed id);
    event CellRevived(uint256 indexed id);
    event CellDissolved(uint256 indexed id);
    event OperatorChanged(address indexed from, address indexed to);

    constructor(address operator_) {
        operator = operator_ == address(0) ? msg.sender : operator_;
    }

    /// @notice Founds a cell around the hash of a secret key and seats the caller. Returns the id, or zero.
    function formCell(bytes32 keyHash) external returns (uint256 id) {
        if (keyHash == bytes32(0) || keyInUse[keyHash] || cellOf[msg.sender] != 0) return 0;
        id = ++cellCount;
        keyInUse[keyHash] = true;
        cells[id] = Cell(keyHash, uint64(block.timestamp), uint64(block.timestamp), 1, uint16(memberCap), true, false);
        cellOf[msg.sender] = id;
        liveCells += 1;
        emit CellFormed(id, memberCap);
        emit Joined(id, msg.sender);
    }

    /// @notice Joins a cell by showing the secret whose hash the cell was founded on.
    function joinCell(uint256 id, bytes32 secret) external returns (bool) {
        Cell storage c = cells[id];
        if (c.formedAt == 0 || c.dormant || !c.doorsOpen || cellOf[msg.sender] != 0) return false;
        if (c.members >= c.cap || keccak256(abi.encodePacked(secret)) != c.keyHash) return false;
        c.members += 1;
        c.lastSeen = uint64(block.timestamp);
        cellOf[msg.sender] = id;
        emit Joined(id, msg.sender);
        return true;
    }

    /// @notice Leaves the cell the caller sits in. The last member out dissolves it.
    function leaveCell() external returns (bool) {
        uint256 id = cellOf[msg.sender];
        if (id == 0) return false;
        Cell storage c = cells[id];
        cellOf[msg.sender] = 0;
        emit Left(id, msg.sender);
        if (c.members > 1) {
            c.members -= 1;
        } else {
            keyInUse[c.keyHash] = false;
            delete cells[id];
            if (liveCells > 0) liveCells -= 1;
            emit CellDissolved(id);
        }
        return true;
    }

    /// @notice Replaces the cell key. The caller must show the secret behind the current key.
    function rotateKey(bytes32 secret, bytes32 newKeyHash) external returns (bool) {
        uint256 id = cellOf[msg.sender];
        Cell storage c = cells[id];
        if (id == 0 || newKeyHash == bytes32(0) || keyInUse[newKeyHash]) return false;
        if (keccak256(abi.encodePacked(secret)) != c.keyHash) return false;
        keyInUse[c.keyHash] = false;
        keyInUse[newKeyHash] = true;
        c.keyHash = newKeyHash;
        c.lastSeen = uint64(block.timestamp);
        emit KeyRotated(id);
        return true;
    }

    /// @notice Shuts the doors so no one else can join. Any member can do this.
    function closeDoors() external returns (bool) {
        uint256 id = cellOf[msg.sender];
        if (id == 0 || !cells[id].doorsOpen) return false;
        cells[id].doorsOpen = false;
        emit DoorsChanged(id, false);
        return true;
    }

    /// @notice Opens the doors again. The caller must show the secret behind the current key.
    function openDoors(bytes32 secret) external returns (bool) {
        uint256 id = cellOf[msg.sender];
        Cell storage c = cells[id];
        if (id == 0 || c.doorsOpen || c.dormant) return false;
        if (keccak256(abi.encodePacked(secret)) != c.keyHash) return false;
        c.doorsOpen = true;
        emit DoorsChanged(id, true);
        return true;
    }

    /// @notice Sets the size limit of the caller's cell, between two and the operator's ceiling.
    function setCellCap(uint256 cap) external returns (bool) {
        uint256 id = cellOf[msg.sender];
        Cell storage c = cells[id];
        if (id == 0 || cap < MIN_CAP || cap > memberCap || cap < c.members) return false;
        c.cap = uint16(cap);
        emit CapChanged(id, cap);
        return true;
    }

    /// @notice Shows the cell is still alive. Revives a dormant cell.
    function touch() external returns (bool) {
        uint256 id = cellOf[msg.sender];
        if (id == 0) return false;
        Cell storage c = cells[id];
        c.lastSeen = uint64(block.timestamp);
        if (c.dormant) {
            c.dormant = false;
            emit CellRevived(id);
        }
        return true;
    }

    /// @notice Sets the ceiling for new cells and for cell limits. Operator only.
    function setMemberCap(uint256 cap) external returns (bool) {
        if (msg.sender != operator || cap < MIN_CAP || cap > HARD_CAP) return false;
        memberCap = cap;
        return true;
    }

    function handOver(address next) external returns (bool) {
        if (msg.sender != operator || next == address(0) || next == operator) return false;
        emit OperatorChanged(operator, next);
        operator = next;
        return true;
    }

    /// @notice Marks a cell dormant once it has been silent for thirty days. Anyone can call it.
    function execute(uint256 id) external returns (bool) {
        Cell storage c = cells[id];
        if (c.formedAt == 0 || c.dormant || block.timestamp < uint256(c.lastSeen) + IDLE_LIMIT) return false;
        c.dormant = true;
        c.doorsOpen = false;
        emit CellDormant(id);
        return true;
    }

    function isMember(address who, uint256 id) external view returns (bool) {
        return id != 0 && cellOf[who] == id;
    }

    function sameCell(address a, address b) external view returns (bool) {
        uint256 id = cellOf[a];
        return id != 0 && cellOf[b] == id;
    }
}

contracts/PromiseScoreLedger.sol


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

/**
 * @title PromiseScoreLedger
 * @notice Keeps the coordination score of Kungaupei, which is nothing more than the share of promises a
 *         person has kept. Two people agree on something, the one who promised says it is done, and the
 *         other confirms. There is no reputation to buy and no one who can award it.
 *
 * @dev A promise names the person it was made to, a hash of what was promised and a due time between one
 *      hour and ninety days away. The counterparty can confirm it, release it, or report it broken once
 *      it is due. The promisor can claim it done or admit it broken. Anyone can lapse a promise that
 *      stayed open past the due time plus a grace period. A pair of people can raise each other's score
 *      with at most five confirmed promises in total, so two accounts cannot pump each other. Every write
 *      function is total and returns false or zero instead of reverting.
 *
 * Website: https://kungaupei.com
 */
contract PromiseScoreLedger {
    uint256 public constant MIN_TERM = 1 hours;
    uint256 public constant MAX_TERM = 90 days;
    uint256 public constant MAX_OPEN = 16;
    uint256 public constant PAIR_LIMIT = 5;
    uint256 public constant SNAPSHOT_EVERY = 1 days;

    enum State { None, Open, Claimed, Kept, Broken, Lapsed, Released }

    struct Promise_ {
        address promisor;
        address counterparty;
        bytes32 what;
        uint64 madeAt;
        uint64 due;
        uint64 proposedDue;
        State state;
    }

    address public operator;
    uint256 public grace = 3 days;
    uint256 public promiseCount;

    mapping(uint256 => Promise_) public promises;
    mapping(address => uint256) public keptCount;
    mapping(address => uint256) public brokenCount;
    mapping(address => uint256) public lapsedCount;
    mapping(address => uint256) public openCount;
    mapping(bytes32 => uint256) public pairCredits;
    mapping(address => uint256) public snapshotScore;
    mapping(address => uint256) public snapshotAt;

    event Pledged(uint256 indexed id, address indexed promisor, address indexed counterparty, uint256 due);
    event Claimed(uint256 indexed id);
    event Kept(uint256 indexed id, bool counted);
    event Broken(uint256 indexed id);
    event Lapsed(uint256 indexed id);
    event Released(uint256 indexed id);
    event MoreTimeAsked(uint256 indexed id, uint256 due);
    event MoreTimeGranted(uint256 indexed id, uint256 due);
    event Snapshot(address indexed who, uint256 score);
    event OperatorChanged(address indexed from, address indexed to);

    constructor(address operator_) {
        operator = operator_ == address(0) ? msg.sender : operator_;
    }

    /// @notice Makes a promise to someone. Returns the id, or zero.
    function pledge(address counterparty, bytes32 what, uint256 due) external returns (uint256 id) {
        if (counterparty == address(0) || counterparty == msg.sender || what == bytes32(0)) return 0;
        if (due < block.timestamp + MIN_TERM || due > block.timestamp + MAX_TERM) return 0;
        if (openCount[msg.sender] >= MAX_OPEN) return 0;
        id = ++promiseCount;
        promises[id] = Promise_(msg.sender, counterparty, what, uint64(block.timestamp), uint64(due), 0, State.Open);
        openCount[msg.sender] += 1;
        emit Pledged(id, msg.sender, counterparty, due);
    }

    /// @notice The promisor says the promise is done, so the counterparty can confirm it.
    function claimKept(uint256 id) external returns (bool) {
        Promise_ storage p = promises[id];
        if (p.promisor != msg.sender || p.state != State.Open) return false;
        p.state = State.Claimed;
        emit Claimed(id);
        return true;
    }

    /// @notice The counterparty confirms the promise was kept. This raises the promisor's score.
    function confirmKept(uint256 id) external returns (bool) {
        Promise_ storage p = promises[id];
        if (p.counterparty != msg.sender || (p.state != State.Open && p.state != State.Claimed)) return false;
        p.state = State.Kept;
        _closeOne(p.promisor);
        bytes32 pair = _pair(p.promisor, p.counterparty);
        bool counted = pairCredits[pair] < PAIR_LIMIT;
        if (counted) {
            pairCredits[pair] += 1;
            keptCount[p.promisor] += 1;
        }
        emit Kept(id, counted);
        return true;
    }

    /// @notice The counterparty lets the promisor off. The score does not move.
    function release(uint256 id) external returns (bool) {
        Promise_ storage p = promises[id];
        if (p.counterparty != msg.sender || (p.state != State.Open && p.state != State.Claimed)) return false;
        p.state = State.Released;
        _closeOne(p.promisor);
        emit Released(id);
        return true;
    }

    /// @notice The promisor admits the promise was not kept.
    function admitBroken(uint256 id) external returns (bool) {
        Promise_ storage p = promises[id];
        if (p.promisor != msg.sender || (p.state != State.Open && p.state != State.Claimed)) return false;
        p.state = State.Broken;
        brokenCount[msg.sender] += 1;
        _closeOne(msg.sender);
        emit Broken(id);
        return true;
    }

    /// @notice The counterparty reports a promise broken once it is due and was never claimed.
    function reportBroken(uint256 id) external returns (bool) {
        Promise_ storage p = promises[id];
        if (p.counterparty != msg.sender || p.state != State.Open || block.timestamp < p.due) return false;
        p.state = State.Broken;
        brokenCount[p.promisor] += 1;
        _closeOne(p.promisor);
        emit Broken(id);
        return true;
    }

    /// @notice Lapses a promise that stayed open past its due time and the grace period. Anyone can call it.
    function lapse(uint256 id) external returns (bool) {
        Promise_ storage p = promises[id];
        if (p.state != State.Open || block.timestamp < uint256(p.due) + grace) return false;
        p.state = State.Lapsed;
        lapsedCount[p.promisor] += 1;
        _closeOne(p.promisor);
        emit Lapsed(id);
        return true;
    }

    /// @notice The promisor asks for a later due date. The counterparty has to agree.
    function askMoreTime(uint256 id, uint256 newDue) external returns (bool) {
        Promise_ storage p = promises[id];
        if (p.promisor != msg.sender || p.state != State.Open || newDue <= p.due) return false;
        if (newDue > block.timestamp + MAX_TERM) return false;
        p.proposedDue = uint64(newDue);
        emit MoreTimeAsked(id, newDue);
        return true;
    }

    /// @notice The counterparty agrees to the later due date.
    function grantMoreTime(uint256 id) external returns (bool) {
        Promise_ storage p = promises[id];
        if (p.counterparty != msg.sender || p.state != State.Open || p.proposedDue <= p.due) return false;
        p.due = p.proposedDue;
        p.proposedDue = 0;
        emit MoreTimeGranted(id, p.due);
        return true;
    }

    /// @notice Sets the grace period before a promise can lapse, between one hour and thirty days.
    function setGrace(uint256 secs) external returns (bool) {
        if (msg.sender != operator || secs < 1 hours || secs > 30 days) return false;
        grace = secs;
        return true;
    }

    function handOver(address next) external returns (bool) {
        if (msg.sender != operator || next == address(0) || next == operator) return false;
        emit OperatorChanged(operator, next);
        operator = next;
        return true;
    }

    /// @notice Records today's score for a person, at most once a day. Anyone can call it.
    function execute(address who) external returns (bool) {
        if (who == address(0) || block.timestamp < snapshotAt[who] + SNAPSHOT_EVERY) return false;
        uint256 s = scoreOf(who);
        snapshotScore[who] = s;
        snapshotAt[who] = block.timestamp;
        emit Snapshot(who, s);
        return true;
    }

    /// @notice Share of settled promises that were kept, from 0 to 1000.
    function scoreOf(address who) public view returns (uint256) {
        uint256 total = settledOf(who);
        if (total == 0) return 0;
        return keptCount[who] * 1000 / total;
    }

    function settledOf(address who) public view returns (uint256) {
        return keptCount[who] + brokenCount[who] + lapsedCount[who];
    }

    function _pair(address a, address b) private pure returns (bytes32) {
        return a < b ? keccak256(abi.encode(a, b)) : keccak256(abi.encode(b, a));
    }

    function _closeOne(address who) private {
        if (openCount[who] > 0) openCount[who] -= 1;
    }
}

contracts/SealedRendezvousVault.sol

// https://kungaupei.com
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

interface ICellSeats {
    function cellOf(address who) external view returns (uint256);
}

/**
 * @title SealedRendezvousVault
 * @notice Keeps the meeting points of Kungaupei sealed until the bell. A member commits to the hash of a
 *         place and a salt, the hash sits on chain unreadable, and only after the next bell can the place
 *         be shown. The cell that was told then has a short window to turn up, after which the entry is
 *         wiped.
 *
 * @dev Time runs in a repeating cycle of twenty-four hours split into four equal phases: decrypt,
 *      rendezvous, disperse and sealed. The bell is the start of each cycle. An entry made at any time is
 *      tied to the next bell, can be changed or withdrawn until one hour before it, and can be revealed
 *      only in the decrypt phase right after it. Attendance is counted in the rendezvous phase and only
 *      for members of the same cell as the person who sealed. Every write function is total and returns
 *      false or zero instead of reverting.
 *
 * Website: https://kungaupei.com
 */
contract SealedRendezvousVault {
    string public constant WEBSITE = "https://kungaupei.com";
    uint256 public constant CYCLE = 24 hours;
    uint256 public constant QUARTER = 6 hours;
    uint256 public constant LOCK = 1 hours;
    uint256 public constant MAX_OPEN = 4;

    enum State { None, Sealed, Revealed, Withdrawn, Missed, Dispersed }
    enum Phase { Decrypt, Rendezvous, Disperse, Sealed }

    struct Entry {
        address sealer;
        uint256 cellId;
        bytes32 sealedHash;
        bytes32 place;
        uint64 bell;
        uint32 attendees;
        State state;
        bool allClear;
    }

    address public operator;
    ICellSeats public immutable cellSeats;
    uint256 public entryCount;
    uint256 public heldCount;

    mapping(uint256 => Entry) public entries;
    mapping(address => uint256) public openEntries;
    mapping(address => uint256) public heldBy;
    mapping(uint256 => mapping(address => bool)) public attended;

    event SealedAt(uint256 indexed id, uint256 indexed cellId, uint256 bell);
    event Resealed(uint256 indexed id);
    event Withdrawn(uint256 indexed id);
    event Revealed(uint256 indexed id, bytes32 place);
    event Attended(uint256 indexed id, address indexed who);
    event AllClear(uint256 indexed id);
    event Dispersed(uint256 indexed id, bool wasRevealed);
    event OperatorChanged(address indexed from, address indexed to);

    constructor(address operator_, address cellSeats_) {
        operator = operator_ == address(0) ? msg.sender : operator_;
        cellSeats = ICellSeats(cellSeats_);
    }

    /// @notice Seals a commitment for the next bell on behalf of the caller's cell. Returns the id, or zero.
    function seal(bytes32 sealedHash) external returns (uint256 id) {
        uint256 cellId = _cellOf(msg.sender);
        if (sealedHash == bytes32(0) || cellId == 0 || openEntries[msg.sender] >= MAX_OPEN) return 0;
        uint256 bell = nextBell(block.timestamp);
        if (bell - block.timestamp < LOCK) return 0;
        id = ++entryCount;
        entries[id] = Entry(msg.sender, cellId, sealedHash, bytes32(0), uint64(bell), 0, State.Sealed, false);
        openEntries[msg.sender] += 1;
        emit SealedAt(id, cellId, bell);
    }

    /// @notice Swaps the commitment of an entry that is still sealed and not yet locked.
    function reseal(uint256 id, bytes32 newHash) external returns (bool) {
        Entry storage e = entries[id];
        if (e.sealer != msg.sender || e.state != State.Sealed || newHash == bytes32(0)) return false;
        if (block.timestamp + LOCK > e.bell) return false;
        e.sealedHash = newHash;
        emit Resealed(id);
        return true;
    }

    /// @notice Pulls an entry before it locks.
    function withdraw(uint256 id) external returns (bool) {
        Entry storage e = entries[id];
        if (e.sealer != msg.sender || e.state != State.Sealed || block.timestamp + LOCK > e.bell) return false;
        e.state = State.Withdrawn;
        e.sealedHash = bytes32(0);
        _closeOne(msg.sender);
        emit Withdrawn(id);
        return true;
    }

    /// @notice Shows the place and salt behind a commitment in the decrypt phase after its bell.
    function reveal(uint256 id, bytes32 place, bytes32 salt) external returns (bool) {
        Entry storage e = entries[id];
        if (e.sealer != msg.sender || e.state != State.Sealed || place == bytes32(0)) return false;
        if (block.timestamp < e.bell || block.timestamp >= uint256(e.bell) + QUARTER) return false;
        if (keccak256(abi.encodePacked(place, salt, msg.sender)) != e.sealedHash) return false;
        e.place = place;
        e.state = State.Revealed;
        emit Revealed(id, place);
        return true;
    }

    /// @notice A member of the same cell confirms they turned up, during the rendezvous phase.
    function attend(uint256 id) external returns (bool) {
        Entry storage e = entries[id];
        if (e.state != State.Revealed || e.sealer == msg.sender || attended[id][msg.sender]) return false;
        uint256 from = uint256(e.bell) + QUARTER;
        if (block.timestamp < from || block.timestamp >= from + QUARTER) return false;
        if (e.cellId == 0 || _cellOf(msg.sender) != e.cellId) return false;
        attended[id][msg.sender] = true;
        e.attendees += 1;
        emit Attended(id, msg.sender);
        return true;
    }

    /// @notice The person who sealed reports a safe dispersal, in the disperse phase.
    function signalAllClear(uint256 id) external returns (bool) {
        Entry storage e = entries[id];
        if (e.sealer != msg.sender || e.state != State.Revealed || e.allClear) return false;
        uint256 from = uint256(e.bell) + 2 * QUARTER;
        if (block.timestamp < from || block.timestamp >= from + QUARTER) return false;
        e.allClear = true;
        emit AllClear(id);
        return true;
    }

    function handOver(address next) external returns (bool) {
        if (msg.sender != operator || next == address(0) || next == operator) return false;
        emit OperatorChanged(operator, next);
        operator = next;
        return true;
    }

    /// @notice Wipes an entry once its window is over. Anyone can call it.
    function execute(uint256 id) external returns (bool) {
        Entry storage e = entries[id];
        if (e.state == State.Revealed && block.timestamp >= uint256(e.bell) + 3 * QUARTER) {
            if (e.attendees > 0) {
                heldCount += 1;
                heldBy[e.sealer] += 1;
            }
            e.place = bytes32(0);
            e.state = State.Dispersed;
            _closeOne(e.sealer);
            emit Dispersed(id, true);
            return true;
        }
        if (e.state == State.Sealed && block.timestamp >= uint256(e.bell) + QUARTER) {
            e.sealedHash = bytes32(0);
            e.state = State.Missed;
            _closeOne(e.sealer);
            emit Dispersed(id, false);
            return true;
        }
        return false;
    }

    function nextBell(uint256 ts) public pure returns (uint256) {
        return (ts / CYCLE + 1) * CYCLE;
    }

    function phaseAt(uint256 ts) public pure returns (Phase) {
        return Phase((ts % CYCLE) / QUARTER);
    }

    function phaseNow() external view returns (Phase) {
        return phaseAt(block.timestamp);
    }

    function _closeOne(address who) private {
        if (openEntries[who] > 0) openEntries[who] -= 1;
    }

    function _cellOf(address who) private view returns (uint256 id) {
        try cellSeats.cellOf(who) returns (uint256 v) {
            id = v;
        } catch {
            id = 0;
        }
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.