Verified contractPartialMIT
SwarmOracle
Address0xfbd1f85ea9ea14432ab3ade43d2ff01bf752ccea
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,407,204
- Creation transaction
- 0xc83be4d330…608cbe4387
14 files
- src/swarm/SwarmOracle.solmain9.58 KB
- lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol3.8 KB
- lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol5.77 KB
- lib/v4-core/lib/openzeppelin-contracts/contracts/utils/Address.sol6.26 KB
- lib/v4-core/lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol7.73 KB
- src/Bitboard.sol34.88 KB
- src/Chess.sol1.92 KB
- src/Rules.sol2.09 KB
- src/swarm/IIntake.sol1.13 KB
- src/swarm/ISwarmOracle.sol2.31 KB
- src/swarm/PositionRing.sol2.78 KB
- src/swarm/SwarmRules.sol6.76 KB
- src/swarm/SwarmText.sol15.89 KB
src/swarm/SwarmOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {IIntake, Attestation} from "./IIntake.sol";
import {ISwarmOracle, ISwarmOracleClient, SwarmCause} from "./ISwarmOracle.sol";
import {SwarmRules} from "./SwarmRules.sol";
import {SwarmText} from "./SwarmText.sol";
/// Swarm Duel's adapter to IMD's oracle: everything IMD-specific in one place. It writes the question (SwarmText), checks IMD's limits before
/// paying, pays the Intake exactly, receives the callback for its own pending request only, checks the attestation
/// (the attester's signature in this contract's own EIP-712 domain, the stored question hash, bytes32, a panel of
/// exactly 7 with a quorum of exactly 3, at least 3 agreeing, not expired), decodes the move and tells SwarmDuel. It
/// holds no money between calls and has no owner; SwarmDuel's deployer can replace it there, after a notice.
contract SwarmOracle is ISwarmOracle {
using SafeERC20 for IERC20;
bytes32 internal constant ACTION = "oracle.request@oracle-1";
uint16 internal constant PANEL = 7;
uint16 internal constant QUORUM = 3;
uint8 internal constant BYTES32 = 2; // the attestation's answerType for bytes32
uint256 internal constant WINDOW_DEPTH = 6; // IMD reads the ask with toBlock at least 5 blocks deep
uint256 internal constant MAX_QUESTION = 2_000;
uint256 internal constant MAX_DEFINITION = 512;
uint256 internal constant MAX_BODY = 16_384;
uint256 internal constant MAX_ALLOW = 256;
bytes32 internal constant TYPEHASH = keccak256(
"OracleAttestation(bytes32 requestId,uint256 chainId,bytes32 questionHash,uint8 answerType,bytes answer,"
"uint256 figure,uint64 fromBlock,uint64 toBlock,bytes32 blockHash,bytes32 panelJobId,uint16 panelSize,"
"uint16 quorum,uint16 agreed,uint64 issuedAt,uint64 expiresAt)"
);
IIntake public immutable intake;
IERC20 public immutable imd;
address public immutable attester;
ISwarmOracleClient public immutable client;
SwarmRules public immutable rules;
uint256 public immutable price;
bytes32 internal immutable DOMAIN;
/// The question hash of each request this adapter paid for and hasn't heard back on (IMD's binding of an answer to
/// a request; SwarmDuel keeps the game's).
mapping(bytes32 requestId => bytes32 questionHash) public pending;
/// Each ask's Intake request id in full, by `gameNo << 16 | Black's ply` (SwarmDuel's record keeps its first sixteen
/// bytes): IMD finds its panel only from the full id. For readers; nothing here reads it.
mapping(uint256 turn => bytes32 requestId) public asks;
event Asked(bytes32 indexed id, uint32 gameNo, uint16 ply, bytes32 questionHash);
event Answered(bytes32 indexed id, uint16 move, uint16 agreed);
event Failed(bytes32 indexed id, uint8 cause, uint8 status, bytes32 reason, uint16 agreed, uint16 answered);
error InvalidSetup();
error NotClient();
error NotIntake();
error Declined(); // the question would break one of IMD's limits: nothing paid, the engine plays
constructor(
IIntake intake_,
IERC20 imd_,
address attester_,
ISwarmOracleClient client_,
SwarmRules rules_,
uint256 price_
) {
if (
address(intake_) == address(0) || address(imd_) == address(0) || attester_ == address(0)
|| address(client_) == address(0) || address(rules_) == address(0) || price_ == 0
) revert InvalidSetup();
(intake, imd, attester, client, rules, price) = (intake_, imd_, attester_, client_, rules_, price_);
DOMAIN = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256("IdentityMD Oracle"),
keccak256("2"),
block.chainid,
address(this)
)
);
}
// ---------------------------------------------------------------- asking
/// @inheritdoc ISwarmOracle
function ask(SwarmRules.Game calldata g, uint16[] calldata legal, uint256[] calldata history)
external
returns (bytes32 id)
{
if (msg.sender != address(client)) revert NotClient();
if (legal.length == 0 || legal.length > MAX_ALLOW) revert Declined();
SwarmText.Ask memory a;
(a.g, a.legal, a.history, a.windowBlock, a.chainId) = (g, legal, history, block.number - WINDOW_DEPTH, block.chainid);
if (g.level > 0) (a.startBoard, a.startWhite, a.startBlack) = rules.start(g.level);
SwarmText.Written memory w = SwarmText.write(a);
if (w.questionLength > MAX_QUESTION || w.longestDefinition > MAX_DEFINITION || w.body.length > MAX_BODY) {
revert Declined();
}
imd.safeTransferFrom(msg.sender, address(this), price);
imd.forceApprove(address(intake), price);
id = intake.requestWithFailure(
ACTION,
w.body,
IIntake.Callback(address(this), this.onOracleResult.selector),
this.onFailure.selector,
address(imd),
price
);
if (imd.allowance(address(this), address(intake)) != 0) imd.forceApprove(address(intake), 0);
(pending[id], asks[(uint256(g.gameNo) << 16) | g.ply]) = (w.questionHash, id);
emit Asked(id, g.gameNo, g.ply, w.questionHash);
}
// ---------------------------------------------------------------- hearing back (the Intake, 200k gas, once)
/// The oracle's answer for request `id`: only from the Intake, only for a request of ours, once.
function onOracleResult(bytes32 id, Attestation calldata a, bytes calldata signature) external {
if (msg.sender != address(intake)) revert NotIntake();
bytes32 questionHash = pending[id];
if (questionHash == 0) return;
delete pending[id];
(bool ok, uint16 move) = _check(questionHash, a, signature);
if (ok) {
emit Answered(id, move, a.agreed);
client.answered(id, move, a.agreed);
} else {
emit Failed(id, SwarmCause.INVALID, 0, 0, a.agreed, 0);
client.failed(id, SwarmCause.INVALID);
}
}
/// No answer for request `id`: status 1 refused (paid), 2 no result. Only IMD's `disagreed` (its panel's answers fell
/// short of the quorum) is a split, the panel's own choice, never counted by the breaker; every other reason
/// (`failed`, `cancelled`, `blocked`, ...: IMD's side, even after some seats answered) counts as a refusal
///. Unsigned, so it only hands the move to the engine.
function onFailure(bytes32 id, uint8 status, bytes32 reason, uint16 agreed, uint16 answered, bytes calldata)
external
{
if (msg.sender != address(intake)) revert NotIntake();
if (pending[id] == 0) return;
delete pending[id];
uint8 cause = status == 2 && reason == "disagreed" ? SwarmCause.SPLIT : SwarmCause.REFUSED;
emit Failed(id, cause, status, reason, agreed, answered);
client.failed(id, cause);
}
/// The EIP-712 digest the attester signs for this contract (a view for tests and the page).
function digest(Attestation calldata a) public view returns (bytes32) {
bytes32 structHash = keccak256(
bytes.concat(
abi.encode(
TYPEHASH, a.requestId, a.chainId, a.questionHash, a.answerType, keccak256(a.answer), a.figure, a.fromBlock
),
abi.encode(a.toBlock, a.blockHash, a.panelJobId, a.panelSize, a.quorum, a.agreed, a.issuedAt, a.expiresAt)
)
);
return keccak256(abi.encodePacked("\x19\x01", DOMAIN, structHash));
}
/// The move in `a`, if `a` is the attester's answer to our question in exactly our settings.
function _check(bytes32 questionHash, Attestation calldata a, bytes calldata signature)
internal
view
returns (bool, uint16)
{
if (
a.questionHash != questionHash || a.answerType != BYTES32 || a.answer.length != 32 || a.panelSize != PANEL
|| a.quorum != QUORUM || a.agreed < QUORUM || block.timestamp > a.expiresAt
) return (false, 0);
(address signer, ECDSA.RecoverError err,) = ECDSA.tryRecover(digest(a), signature);
if (err != ECDSA.RecoverError.NoError || signer != attester) return (false, 0);
return decode(bytes32(a.answer));
}
/// A move from its UCI bytes32, strictly: four lowercase file/rank characters, then nothing or a q, then zeros
/// (a promotion is always to a queen, so the q needs no bit; legality is SwarmDuel's to check).
function decode(bytes32 x) public pure returns (bool, uint16) {
uint8 f1 = uint8(x[0]);
uint8 r1 = uint8(x[1]);
uint8 f2 = uint8(x[2]);
uint8 r2 = uint8(x[3]);
uint8 p = uint8(x[4]);
if (
f1 < 97 || f1 > 104 || f2 < 97 || f2 > 104 || r1 < 49 || r1 > 56 || r2 < 49 || r2 > 56
|| (p != 0 && p != 113) || uint256(x) << 40 != 0
) return (false, 0);
uint16 from = uint16(f1 - 97) + 8 * uint16(r1 - 49);
uint16 to = uint16(f2 - 97) + 8 * uint16(r2 - 49);
return (true, (from << 6) | to);
}
}
lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
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);
}
lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
lib/v4-core/lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
lib/v4-core/lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError, bytes32) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
src/Bitboard.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// Bitboard chess core: the rules the hook plays by (Rules.sol) and the engine's move search. Squares a1 = 0 .. h8 = 63
/// (north = +8). The packed board (64 x 4 bits: 1 pawn 2 bishop 3 knight 4 rook 5 queen 6 king, +8 black) and the
/// 32-bit side states (Chess.sol) are converted once; everything else is bit operations. Promotion is always to a
/// queen. Checked against chess.js (test/RulesRandom.t.sol, test/Bitboard.t.sol).
library Bitboard {
uint64 internal constant FILE_A = 0x0101010101010101;
uint64 internal constant FILE_H = 0x8080808080808080;
uint64 internal constant NOT_A = ~FILE_A;
uint64 internal constant NOT_H = ~FILE_H;
uint64 internal constant NOT_AB = ~(FILE_A | (FILE_A << 1));
uint64 internal constant NOT_GH = ~(FILE_H | (FILE_H >> 1));
uint64 internal constant RANK_3 = 0x0000000000FF0000;
uint64 internal constant RANK_6 = 0x0000FF0000000000;
uint64 internal constant RANK_1 = 0x00000000000000FF;
uint64 internal constant RANK_8 = 0xFF00000000000000;
struct Pos {
uint64[7] pc; // by piece type 1..6, both colours
uint64 white;
uint64 black;
uint32 whiteState; // the verifier's side states (en passant byte, king, rook flags)
uint32 blackState;
}
// ---------------------------------------------------------------- conversion
uint256 internal constant NIBBLE_LOW = 0x1111111111111111111111111111111111111111111111111111111111111111;
function fromBoard(uint256 board, uint32 whiteState, uint32 blackState) internal pure returns (Pos memory p) {
p.whiteState = whiteState;
p.blackState = blackState;
uint256 types = board & (NIBBLE_LOW * 7);
uint256 occupied = (board | (board >> 1) | (board >> 2)) & NIBBLE_LOW; // a piece has a type, 1..6
uint256 black = (board >> 3) & occupied;
for (uint256 t = 1; t <= 6; t++) {
uint256 x = types ^ (NIBBLE_LOW * t); // zero in the nibbles holding type t
p.pc[t] = _compress(~(x | (x >> 1) | (x >> 2)) & NIBBLE_LOW);
}
p.white = _compress(occupied & ~black);
p.black = _compress(black);
}
/// Bit 4 * i of `x` becomes bit i (x has no other bits set).
function _compress(uint256 x) private pure returns (uint64) {
x = (x | (x >> 3)) & 0x0303030303030303030303030303030303030303030303030303030303030303;
x = (x | (x >> 6)) & 0x000f000f000f000f000f000f000f000f000f000f000f000f000f000f000f000f;
x = (x | (x >> 12)) & 0x000000ff000000ff000000ff000000ff000000ff000000ff000000ff000000ff;
x = (x | (x >> 24)) & 0x000000000000ffff000000000000ffff000000000000ffff000000000000ffff;
x = (x | (x >> 48)) & 0x000000000000000000000000ffffffff000000000000000000000000ffffffff;
return uint64(x | (x >> 96));
}
// ---------------------------------------------------------------- bit helpers
/// Index of the lowest set bit (b != 0), by de Bruijn multiplication.
function lsb(uint64 b) internal pure returns (uint8 r) {
assembly ("memory-safe") {
let idx := shr(58, and(mul(and(b, sub(0, b)), 0x03f79d71b4cb0a89), 0xffffffffffffffff))
switch lt(idx, 32)
case 1 { r := byte(idx, 0x0001300239311c033d3a322a261d11043e373b2435332b162d27211e18120c05) }
default { r := byte(sub(idx, 32), 0x3f2f381b3c292510362334152c20170b2e1a280f22141f0a190e13090d080706) }
}
}
function popcount(uint64 b) internal pure returns (uint256 n) {
assembly ("memory-safe") {
let x := sub(b, and(shr(1, b), 0x5555555555555555))
x := add(and(x, 0x3333333333333333), and(shr(2, x), 0x3333333333333333))
x := and(add(x, shr(4, x)), 0x0f0f0f0f0f0f0f0f)
n := shr(56, and(mul(x, 0x0101010101010101), 0xffffffffffffffff))
}
}
// ---------------------------------------------------------------- attacks
function knightAttacks(uint64 b) internal pure returns (uint64) {
uint64 l1 = (b >> 1) & NOT_H;
uint64 l2 = (b >> 2) & NOT_GH;
uint64 r1 = (b << 1) & NOT_A;
uint64 r2 = (b << 2) & NOT_AB;
uint64 h1 = l1 | r1;
uint64 h2 = l2 | r2;
return (h1 << 16) | (h1 >> 16) | (h2 << 8) | (h2 >> 8);
}
function kingAttacks(uint64 b) internal pure returns (uint64) {
uint64 side = ((b << 1) & NOT_A) | ((b >> 1) & NOT_H);
uint64 row = b | side;
return side | (row << 8) | (row >> 8);
}
function pawnAttacks(uint64 b, bool white) internal pure returns (uint64) {
return white ? ((b << 7) & NOT_H) | ((b << 9) & NOT_A) : ((b >> 9) & NOT_H) | ((b >> 7) & NOT_A);
}
uint64 internal constant DIAG = 0x8040201008040201; // a1-h8
uint64 internal constant ANTI = 0x0102040810204080; // h1-a8
/// Full rook lines and bishop lines through `sq`, without `sq` itself.
function rays(uint8 sq) internal pure returns (uint64 rook, uint64 bishop) {
unchecked {
uint64 bit = uint64(1) << sq;
uint256 f = sq & 7;
uint256 r = sq >> 3;
rook = ((FILE_A << f) | (RANK_1 << (8 * r))) ^ bit;
uint64 d = f >= r ? DIAG >> (8 * (f - r)) : DIAG << (8 * (r - f));
uint64 a = f + r <= 7 ? ANTI >> (8 * (7 - f - r)) : ANTI << (8 * (f + r - 7));
bishop = (d | a) ^ bit;
}
}
/// Sliding attacks for every rook-mover in `g` (occluded fill, Kogge-Stone), the four directions in one block:
/// north and south by 8, east (dropping wraps onto the a-file) and west (onto the h-file) by 1. Intermediate values
/// stay within 64 bits because they are masked by `empty`; only each direction's last shift is cut.
function rookAttacks(uint64 g, uint64 empty) internal pure returns (uint64 r) {
assembly ("memory-safe") {
let x := or(g, and(empty, shl(8, g)))
let e := and(empty, shl(8, empty))
x := or(x, and(e, shl(16, x)))
e := and(e, shl(16, e))
x := or(x, and(e, shl(32, x)))
r := and(shl(8, x), 0xffffffffffffffff)
x := or(g, and(empty, shr(8, g)))
e := and(empty, shr(8, empty))
x := or(x, and(e, shr(16, x)))
e := and(e, shr(16, e))
x := or(x, and(e, shr(32, x)))
r := or(r, shr(8, x))
let m := 0xfefefefefefefefe
let em := and(empty, m)
x := or(g, and(em, shl(1, g)))
e := and(em, shl(1, em))
x := or(x, and(e, shl(2, x)))
e := and(e, shl(2, e))
x := or(x, and(e, shl(4, x)))
r := or(r, and(shl(1, x), m))
m := 0x7f7f7f7f7f7f7f7f
em := and(empty, m)
x := or(g, and(em, shr(1, g)))
e := and(em, shr(1, em))
x := or(x, and(e, shr(2, x)))
e := and(e, shr(2, e))
x := or(x, and(e, shr(4, x)))
r := or(r, and(shr(1, x), m))
}
}
/// The four bishop directions in one block: north-east by 9 and south-east by 7 (dropping wraps onto the a-file),
/// north-west by 7 and south-west by 9 (dropping wraps onto the h-file).
function bishopAttacks(uint64 g, uint64 empty) internal pure returns (uint64 r) {
assembly ("memory-safe") {
let m := 0xfefefefefefefefe
let em := and(empty, m)
let x := or(g, and(em, shl(9, g)))
let e := and(em, shl(9, em))
x := or(x, and(e, shl(18, x)))
e := and(e, shl(18, e))
x := or(x, and(e, shl(36, x)))
r := and(shl(9, x), m)
x := or(g, and(em, shr(7, g)))
e := and(em, shr(7, em))
x := or(x, and(e, shr(14, x)))
e := and(e, shr(14, e))
x := or(x, and(e, shr(28, x)))
r := or(r, and(shr(7, x), m))
m := 0x7f7f7f7f7f7f7f7f
em := and(empty, m)
x := or(g, and(em, shl(7, g)))
e := and(em, shl(7, em))
x := or(x, and(e, shl(14, x)))
e := and(e, shl(14, e))
x := or(x, and(e, shl(28, x)))
r := or(r, and(shl(7, x), m))
x := or(g, and(em, shr(9, g)))
e := and(em, shr(9, em))
x := or(x, and(e, shr(18, x)))
e := and(e, shr(18, e))
x := or(x, and(e, shr(36, x)))
r := or(r, and(shr(9, x), m))
}
}
/// Every square attacked by `white`'s side (pawn diagonals, pieces, sliders up to and including the blocker).
function attacksBy(Pos memory p, bool white) internal pure returns (uint64) {
return attacksWith(p, white, ~(p.white | p.black));
}
/// The same with sliders running over `empty` (for example with the enemy king lifted off the board).
function attacksWith(Pos memory p, bool white, uint64 empty) internal pure returns (uint64 a) {
uint64 own = white ? p.white : p.black;
a = pawnAttacks(p.pc[1] & own, white) | knightAttacks(p.pc[3] & own) | kingAttacks(p.pc[6] & own);
a |= rookAttacks((p.pc[4] | p.pc[5]) & own, empty) | bishopAttacks((p.pc[2] | p.pc[5]) & own, empty);
}
/// Whether `sq` is attacked by `byWhite`'s side.
function attacked(Pos memory p, uint8 sq, bool byWhite) internal pure returns (bool) {
uint64 bit = uint64(1) << sq;
uint64 them = byWhite ? p.white : p.black;
uint64 empty = ~(p.white | p.black);
if (pawnAttacks(bit, !byWhite) & p.pc[1] & them != 0) return true;
if (knightAttacks(bit) & p.pc[3] & them != 0) return true;
if (kingAttacks(bit) & p.pc[6] & them != 0) return true;
(uint64 rr, uint64 br) = rays(sq);
uint64 rq = (p.pc[4] | p.pc[5]) & them;
if (rr & rq != 0 && rookAttacks(bit, empty) & rq != 0) return true;
uint64 bq = (p.pc[2] | p.pc[5]) & them;
return br & bq != 0 && bishopAttacks(bit, empty) & bq != 0;
}
/// Number of `white`'s pieces attacking each square, 4 bits per square (the format the strategy helper reads).
function attackCounts(Pos memory p, bool white) internal pure returns (uint256 map) {
uint64 own = white ? p.white : p.black;
uint64 empty = ~(p.white | p.black);
uint64 pieces = own;
while (pieces != 0) {
uint8 sq = lsb(pieces);
pieces &= pieces - 1;
uint64 bit = uint64(1) << sq;
uint64 a = pieceAttacks(p, bit, empty, white);
while (a != 0) {
uint8 t = lsb(a);
a &= a - 1;
uint256 shift = uint256(t) << 2;
if ((map >> shift) & 15 != 15) map += uint256(1) << shift;
}
}
}
function pieceAttacks(Pos memory p, uint64 bit, uint64 empty, bool white) internal pure returns (uint64) {
if (p.pc[1] & bit != 0) return pawnAttacks(bit, white);
if (p.pc[3] & bit != 0) return knightAttacks(bit);
if (p.pc[6] & bit != 0) return kingAttacks(bit);
uint64 a;
if ((p.pc[4] | p.pc[5]) & bit != 0) a = rookAttacks(bit, empty);
if ((p.pc[2] | p.pc[5]) & bit != 0) a |= bishopAttacks(bit, empty);
return a;
}
/// The piece type on `sq` (0 if empty): each square is in at most one of the piece sets.
function pieceAt(Pos memory p, uint8 sq) internal pure returns (uint8 t) {
uint64[7] memory pc = p.pc;
uint256 r = (uint256(pc[1]) >> sq & 1) | (uint256(pc[2]) >> sq & 1) << 1 | ((uint256(pc[3]) >> sq & 1) * 3)
| (uint256(pc[4]) >> sq & 1) << 2 | ((uint256(pc[5]) >> sq & 1) * 5) | ((uint256(pc[6]) >> sq & 1) * 6);
t = uint8(r);
}
// ---------------------------------------------------------------- moves
/// The position after `move` (from << 6 | to): queen promotion, en passant capture, castling rook, and the side
/// states (king and rook flags, the flag of a rook captured at home, the en passant byte).
function makeMove(Pos memory p, uint16 move, bool white) internal pure returns (Pos memory n) {
makeMoveInto(p, n, move, white);
}
/// Same as makeMove, but writes into `n` (a scratch position reused across trial moves, so memory doesn't grow).
function makeMoveInto(Pos memory p, Pos memory n, uint16 move, bool white) internal pure {
for (uint256 i = 1; i <= 6; i++) n.pc[i] = p.pc[i]; // copy values: `n.pc = p.pc` would alias the array
n.white = p.white;
n.black = p.black;
uint8 from = uint8(move >> 6);
uint8 to = uint8(move & 63);
uint8 t = pieceAt(p, from);
uint8 victim = pieceAt(p, to);
if (victim != 0) _remove(n, uint64(1) << to, victim, !white);
_shift(n, from, to, t, white);
uint32 mover = white ? p.whiteState : p.blackState;
if (t == 1) mover = _pawnExtras(p, n, from, to, victim == 0, white, mover);
else if (t == 6) mover = _kingExtras(n, from, to, white, mover);
else if (t == 4) {
if (from == uint8(mover >> 16)) mover |= 0x00800000;
else if (from == uint8(mover >> 24)) mover |= 0x80000000;
}
uint32 other = (white ? p.blackState : p.whiteState) | 0xff;
if (victim != 0) {
// a rook taken on its home square takes its castling right with it (a flagged byte never equals `to`)
if (to == uint8(other >> 16)) other |= 0x00800000;
else if (to == uint8(other >> 24)) other |= 0x80000000;
}
(n.whiteState, n.blackState) = white ? (mover, other) : (other, mover);
}
function _remove(Pos memory n, uint64 bit, uint8 t, bool ofWhite) private pure {
n.pc[t] &= ~bit;
if (ofWhite) n.white &= ~bit;
else n.black &= ~bit;
}
function _shift(Pos memory n, uint8 from, uint8 to, uint8 t, bool white) private pure {
uint64 fb = uint64(1) << from;
uint64 tb = uint64(1) << to;
n.pc[t] = (n.pc[t] & ~fb) | tb;
if (white) n.white = (n.white & ~fb) | tb;
else n.black = (n.black & ~fb) | tb;
}
/// En passant capture, queen promotion and the double-step en passant byte, as the verifier applies them.
function _pawnExtras(Pos memory p, Pos memory n, uint8 from, uint8 to, bool quiet, bool white, uint32 mover)
private
pure
returns (uint32)
{
uint32 other = white ? p.blackState : p.whiteState;
if (quiet && to == uint8(other & 0xff) && (from & 7) != (to & 7)) {
_remove(n, white ? (uint64(1) << to) >> 8 : (uint64(1) << to) << 8, 1, !white);
}
if (to >> 3 == 7 || to >> 3 == 0) {
n.pc[1] &= ~(uint64(1) << to);
n.pc[5] |= uint64(1) << to;
}
uint8 diff = to > from ? to - from : from - to;
if (diff == 16) mover = (mover & ~uint32(0xff)) | uint32(to > from ? from + 8 : to + 8);
return mover;
}
/// Castling moves the rook next to the king; any king move sets both rook flags and the king square.
function _kingExtras(Pos memory n, uint8 from, uint8 to, bool white, uint32 mover) private pure returns (uint32) {
if (to == from + 2 || from == to + 2) {
uint8 rookFrom = to > from ? uint8(mover >> 16) : uint8(mover >> 24);
_shift(n, rookFrom & 63, to > from ? from + 1 : from - 1, 4, white);
}
return ((mover | 0x80800000) & 0xffff00ff) | (uint32(to) << 8);
}
function kingSquare(Pos memory p, bool white) internal pure returns (uint8) {
return uint8((white ? p.whiteState : p.blackState) >> 8);
}
/// Whether `white`'s king is attacked.
function inCheck(Pos memory p, bool white) internal pure returns (bool) {
uint64 k = p.pc[6] & (white ? p.white : p.black);
if (k == 0) return false;
return attacked(p, lsb(k), !white);
}
/// What legality needs to know about the side to move, computed once per position.
struct Gen {
uint64 own;
uint64 opp;
uint64 empty;
uint64 checkMask; // where a non-king move must land: everything, or the checker and the squares between
uint64 pinned; // our pieces that shield the king from an enemy slider
uint64 danger; // squares the enemy attacks with our king lifted off the board
uint8 king; // 64 if there is no king
}
function _prepare(Pos memory p, bool white) private pure returns (Gen memory g) {
g.own = white ? p.white : p.black;
g.opp = white ? p.black : p.white;
g.empty = ~(p.white | p.black);
g.checkMask = type(uint64).max;
uint64 k = p.pc[6] & g.own;
if (k == 0) {
g.king = 64;
return g;
}
g.king = lsb(k);
uint64 rq = (p.pc[4] | p.pc[5]) & g.opp;
uint64 bq = (p.pc[2] | p.pc[5]) & g.opp;
uint64 rk = rookAttacks(k, g.empty);
uint64 bk = bishopAttacks(k, g.empty);
uint64 checkers = (rk & rq) | (bk & bq) | (knightAttacks(k) & p.pc[3] & g.opp)
| (pawnAttacks(k, white) & p.pc[1] & g.opp);
if (checkers != 0) {
if (checkers & (checkers - 1) != 0) g.checkMask = 0; // double check: only the king may move
// a slider's rays and the king's meet only on the squares between them
else if (checkers & rk & rq != 0) g.checkMask = checkers | (rk & rookAttacks(checkers, g.empty));
else if (checkers & bk & bq != 0) g.checkMask = checkers | (bk & bishopAttacks(checkers, g.empty));
else g.checkMask = checkers;
}
// a pinner stands behind the first piece on a line from the king, when that piece is ours
uint64 pinners = rookAttacks(k, g.empty | (rk & g.own)) & ~rk & rq;
while (pinners != 0) {
uint64 one = pinners & (~pinners + 1);
pinners ^= one;
g.pinned |= rookAttacks(one, g.empty) & rk & g.own;
}
pinners = bishopAttacks(k, g.empty | (bk & g.own)) & ~bk & bq;
while (pinners != 0) {
uint64 one = pinners & (~pinners + 1);
pinners ^= one;
g.pinned |= bishopAttacks(one, g.empty) & bk & g.own;
}
g.danger = attacksWith(p, !white, g.empty | k);
}
/// The legal destinations of our piece on `from`. Only en passant is tried on a copy of the position (it removes
/// two pieces from a line); everything else follows from the check mask, the pins and the danger map.
function _legalTargets(Pos memory p, Gen memory g, Pos memory scratch, uint8 from, bool white)
private
pure
returns (uint64 t)
{
t = _targets(p, g, from, white);
if (from == g.king) return t & ~g.danger;
if (g.checkMask == 0) return 0;
uint64 bit = uint64(1) << from;
uint64 ep;
if (p.pc[1] & bit != 0) {
ep = t & pawnAttacks(bit, white) & ~g.opp; // a diagonal step onto an empty square
t ^= ep;
}
t &= g.checkMask;
if (g.pinned & bit != 0) t &= _line(g.king, from);
if (ep != 0) {
makeMoveInto(p, scratch, (uint16(from) << 6) | lsb(ep), white);
if (!inCheck(scratch, white)) t |= ep;
}
}
/// The squares on the line through two aligned squares, without the two squares themselves.
function _line(uint8 a, uint8 b) private pure returns (uint64) {
(uint64 ra, uint64 ba) = rays(a);
(uint64 rb, uint64 bb) = rays(b);
return ra & (uint64(1) << b) != 0 ? ra & rb : ba & bb;
}
/// Whether `move` (from << 6 | to) is legal for `white`'s side.
function isLegal(Pos memory p, uint16 move, bool white) internal pure returns (bool) {
if (move >= 4096) return false;
uint8 from = uint8(move >> 6);
if ((white ? p.white : p.black) & (uint64(1) << from) == 0) return false;
Pos memory scratch;
return _legalTargets(p, _prepare(p, white), scratch, from, white) & (uint64(1) << (move & 63)) != 0;
}
/// All legal moves for `white`'s side, in from-square order (up to 256).
function legalMoves(Pos memory p, bool white) internal pure returns (uint16[] memory moves) {
(moves,) = legalMovesAndCheck(p, white);
}
/// legalMoves, and whether `white`'s king is in check (as inCheck says; found while preparing the moves).
function legalMovesAndCheck(Pos memory p, bool white) internal pure returns (uint16[] memory moves, bool check) {
moves = new uint16[](256);
uint256 n;
Pos memory scratch;
Gen memory g = _prepare(p, white);
check = g.checkMask != type(uint64).max;
uint64 pieces = g.own;
unchecked {
while (pieces != 0) {
uint8 from = lsb(pieces);
pieces &= pieces - 1;
uint64 targets = _legalTargets(p, g, scratch, from, white);
while (targets != 0) {
moves[n++] = (uint16(from) << 6) | lsb(targets);
targets &= targets - 1;
}
}
}
assembly ("memory-safe") {
mstore(moves, n)
mstore(0x40, add(moves, shl(5, add(n, 1)))) // give back the unused slots
}
}
/// Whether `white`'s side has any legal move (the king's moves are tried first).
function hasLegalMove(Pos memory p, bool white) internal pure returns (bool any) {
(, any) = status(p, white);
}
/// Whether `white`'s king is in check (as inCheck says) and whether `white` has any legal move, from one map of the
/// enemy's attacks with our king lifted: the king's own square is attacked exactly when it is in that map.
function status(Pos memory p, bool white) internal pure returns (bool check, bool any) {
uint64 own = white ? p.white : p.black;
uint64 k = p.pc[6] & own;
if (k != 0) {
// usually the king can step somewhere: that needs only the enemy's attacks, not pins or checkers
uint64 danger = attacksWith(p, !white, ~(p.white | p.black) | k);
check = danger & k != 0;
if (kingAttacks(k) & ~own & ~danger != 0) return (check, true);
}
any = _anyLegal(p, white);
}
/// hasLegalMove past its king-step shortcut: every piece's legal targets, the king's first.
function _anyLegal(Pos memory p, bool white) private pure returns (bool) {
Pos memory scratch;
Gen memory g = _prepare(p, white);
if (g.king < 64 && _legalTargets(p, g, scratch, g.king, white) != 0) return true;
uint64 pieces = g.own;
unchecked {
while (pieces != 0) {
uint8 from = lsb(pieces);
pieces &= pieces - 1;
if (from != g.king && _legalTargets(p, g, scratch, from, white) != 0) return true;
}
}
return false;
}
/// Where `white`'s moves give check, computed once per position: sq[t] holds the squares from which a piece of
/// type t attacks the enemy king; disc holds our pieces that alone block one of our sliders from it.
struct Checks {
uint64[7] sq;
uint64 disc;
uint8 king; // the enemy king's square, 64 if there is none
}
function checkInfo(Pos memory p, bool white) internal pure returns (Checks memory c) {
uint64 ek = p.pc[6] & (white ? p.black : p.white);
if (ek == 0) {
c.king = 64;
return c;
}
c.king = lsb(ek);
uint64 empty = ~(p.white | p.black);
uint64 own = white ? p.white : p.black;
uint64 r = rookAttacks(ek, empty);
uint64 b = bishopAttacks(ek, empty);
c.sq[1] = pawnAttacks(ek, !white);
c.sq[2] = b;
c.sq[3] = knightAttacks(ek);
c.sq[4] = r;
c.sq[5] = r | b;
uint64 behind = rookAttacks(ek, empty | (r & own)) & ~r & (p.pc[4] | p.pc[5]) & own;
while (behind != 0) {
uint64 one = behind & (~behind + 1);
behind ^= one;
c.disc |= rookAttacks(one, empty) & r & own;
}
behind = bishopAttacks(ek, empty | (b & own)) & ~b & (p.pc[2] | p.pc[5]) & own;
while (behind != 0) {
uint64 one = behind & (~behind + 1);
behind ^= one;
c.disc |= bishopAttacks(one, empty) & b & own;
}
}
/// Whether a legal `move` by `white` checks the enemy king.
function givesCheck(Pos memory p, Pos memory scratch, uint16 move, bool white) internal pure returns (bool) {
return givesCheckWith(p, checkInfo(p, white), scratch, move, white);
}
/// The same from a precomputed check table. A direct check is a lookup (the moved piece can't open its own line:
/// it would already have been checking); a discovered check is a blocker leaving its line. Castling, en passant
/// and promotions are confirmed on the moved position.
function givesCheckWith(Pos memory p, Checks memory c, Pos memory scratch, uint16 move, bool white)
internal
pure
returns (bool)
{
return givesCheckAs(p, c, scratch, move, white, pieceAt(p, uint8(move >> 6)));
}
/// givesCheckWith when the moving piece's type `t` is already known.
function givesCheckAs(Pos memory p, Checks memory c, Pos memory scratch, uint16 move, bool white, uint8 t)
internal
pure
returns (bool)
{
if (c.king == 64) return false;
uint8 from = uint8(move >> 6);
uint8 to = uint8(move & 63);
uint64 tb = uint64(1) << to;
bool special = (t == 6 && (to == from + 2 || from == to + 2))
|| (t == 1 && ((from & 7) != (to & 7) && (p.white | p.black) & tb == 0 || to >> 3 == 7 || to >> 3 == 0));
if (special) {
makeMoveInto(p, scratch, move, white);
return inCheck(scratch, !white);
}
if (c.sq[t] & tb != 0) return true;
return c.disc & (uint64(1) << from) != 0 && _line(c.king, from) & tb == 0;
}
/// A move by `white` that checkmates, or 0 if there is none. Only checking moves are tried.
function mateInOne(Pos memory p, bool white) internal pure returns (uint16) {
return mateInOne(p, white, type(uint256).max);
}
/// The same, giving up after `tries` checking moves (a bounded search for engines; it may miss a mate).
function mateInOne(Pos memory p, bool white, uint256 tries) internal pure returns (uint16) {
Checks memory c = checkInfo(p, white);
if (c.king == 64) return 0;
uint64 kinds = _checkingKinds(p, c, white);
if (kinds == 0 && c.disc == 0) return 0;
Gen memory g = _prepare(p, white);
Pos memory scratch;
uint64 pieces = g.own;
while (pieces != 0) {
uint8 from = lsb(pieces);
pieces &= pieces - 1;
uint64 fb = uint64(1) << from;
uint8 kind = pieceAt(p, from);
if (kinds & (uint64(1) << kind) == 0 && c.disc & fb == 0) continue; // can't check: skip its legal moves
uint64 t = _legalTargets(p, g, scratch, from, white);
if (t == 0) continue;
// a move onto a square that attacks the king is a check (givesCheckAs); the others are confirmed below
uint64 direct = t & c.sq[kind];
uint64 cand = direct;
if (c.disc & fb != 0) cand |= t & ~_line(c.king, from);
if (kind == 6) cand |= t & ~kingAttacks(fb); // castling
else if (kind == 1) cand |= t & (RANK_1 | RANK_8 | ~(p.white | p.black) & pawnAttacks(fb, white));
while (cand != 0) {
uint8 to = lsb(cand);
uint16 m = (uint16(from) << 6) | to;
cand &= cand - 1;
makeMoveInto(p, scratch, m, white);
if (direct & (uint64(1) << to) == 0 && !inCheck(scratch, !white)) continue;
if (!hasLegalMove(scratch, !white)) return m;
if (--tries == 0) return 0;
}
}
return 0;
}
/// Bit t set when some piece of type t could give a direct check (a superset: own king safety is ignored). Pawns
/// are also flagged for a promotion or en passant, the king for castling; discovered checks are left to the
/// caller (Checks.disc).
function _checkingKinds(Pos memory p, Checks memory c, bool white) private pure returns (uint64 kinds) {
uint64 own = white ? p.white : p.black;
uint64 empty = ~(p.white | p.black);
uint64 open = ~own;
uint64 pawns = p.pc[1] & own;
uint32 state = white ? p.whiteState : p.blackState;
uint8 ep = uint8((white ? p.blackState : p.whiteState) & 0xff);
if (pawns & (white ? RANK_8 >> 8 : RANK_1 << 8) != 0 || ep < 64) kinds |= 2;
if (state & 0x80800000 != 0x80800000) kinds |= 64;
uint64 pushes = white ? (pawns << 8) & empty : (pawns >> 8) & empty;
pushes |= white ? ((pushes & RANK_3) << 8) & empty : ((pushes & RANK_6) >> 8) & empty;
uint64 opp = white ? p.black : p.white;
if ((pushes | (pawnAttacks(pawns, white) & opp)) & c.sq[1] != 0) kinds |= 2;
if (bishopAttacks(p.pc[2] & own, empty) & open & c.sq[2] != 0) kinds |= 4;
if (knightAttacks(p.pc[3] & own) & open & c.sq[3] != 0) kinds |= 8;
if (rookAttacks(p.pc[4] & own, empty) & open & c.sq[4] != 0) kinds |= 16;
uint64 q = p.pc[5] & own;
if ((rookAttacks(q, empty) | bishopAttacks(q, empty)) & open & c.sq[5] != 0) kinds |= 32;
}
/// Pseudo-legal destinations of the piece on `from` (own king safety is checked by the caller).
function _targets(Pos memory p, Gen memory g, uint8 from, bool white) private pure returns (uint64 t) {
(uint64 own, uint64 opp, uint64 empty) = (g.own, g.opp, g.empty);
uint64 bit = uint64(1) << from;
if (p.pc[1] & bit != 0) {
uint64 one = white ? (bit << 8) & empty : (bit >> 8) & empty;
t = one;
if (one != 0) {
uint64 two = white ? ((one & RANK_3) << 8) & empty : ((one & RANK_6) >> 8) & empty;
t |= two;
}
uint64 ep;
uint8 epSq = uint8((white ? p.blackState : p.whiteState) & 0xff);
if (epSq < 64) ep = uint64(1) << epSq;
t |= pawnAttacks(bit, white) & (opp | ep);
return t;
}
if (p.pc[3] & bit != 0) return knightAttacks(bit) & ~own;
if (p.pc[6] & bit != 0) return (kingAttacks(bit) & ~own) | _castling(p, g, white);
if ((p.pc[4] | p.pc[5]) & bit != 0) t = rookAttacks(bit, empty);
if ((p.pc[2] | p.pc[5]) & bit != 0) t |= bishopAttacks(bit, empty);
return t & ~own;
}
/// Castling squares allowed by the verifier's rules: flags clear, rook on its square, the squares between empty,
/// the king not in check and not crossing an attacked square (the destination is checked with the other moves).
/// Attacks come from the danger map (enemy attacks with our king lifted): it differs from the board's attacks only
/// along a line through the king, and a piece on such a line already gives check.
function _castling(Pos memory p, Gen memory g, bool white) private pure returns (uint64 t) {
uint32 state = white ? p.whiteState : p.blackState;
uint8 king = g.king;
uint8 ks = uint8(state >> 16);
uint8 qs = uint8(state >> 24);
bool kingSide = ks < 64 && ks == king + 3;
bool queenSide = qs < 64 && qs + 4 == king;
if (!(kingSide || queenSide) || g.danger & (uint64(1) << king) != 0) return 0;
uint64 rooks = p.pc[4] & g.own;
uint64 blocked = ~g.empty | g.danger;
if (kingSide && rooks & (uint64(1) << ks) != 0) {
uint64 between = (uint64(1) << (king + 1)) | (uint64(1) << (king + 2));
if (between & ~g.empty == 0 && blocked & (uint64(1) << (king + 1)) == 0) t |= uint64(1) << (king + 2);
}
if (queenSide && rooks & (uint64(1) << qs) != 0) {
uint64 between = (uint64(1) << (king - 1)) | (uint64(1) << (king - 2)) | (uint64(1) << (king - 3));
if (between & ~g.empty == 0 && blocked & (uint64(1) << (king - 1)) == 0) t |= uint64(1) << (king - 2);
}
}
// ---------------------------------------------------------------- back to the packed board
/// The packed board after a legal `move` by `white` on `board` (the position `p` describes), equal to
/// toBoard(makeMove(p, move, white)) but made by editing only the nibbles the move changes: the mover (a queen
/// if promoted), what it takes (en passant: the pawn behind the target), and the rook of a castle.
function boardAfter(uint256 board, Pos memory p, uint16 move, bool white) internal pure returns (uint256 b) {
unchecked {
uint256 from = uint256(move >> 6) << 2;
uint256 to = uint256(move & 63) << 2;
uint256 piece = (board >> from) & 15;
b = board & ~(uint256(15) << from) & ~(uint256(15) << to);
if (piece & 7 == 1) {
if (to >> 5 == 7 || to >> 5 == 0) piece = (piece & 8) | 5;
else if ((from >> 2) & 7 != (to >> 2) & 7 && (board >> to) & 15 == 0) b &= ~(uint256(15) << (white ? to - 32 : to + 32));
} else if (piece & 7 == 6 && (to == from + 8 || from == to + 8)) {
uint32 state = white ? p.whiteState : p.blackState;
uint256 rookFrom = (uint256(to > from ? state >> 16 : state >> 24) & 63) << 2;
uint256 rookTo = to > from ? from + 4 : from - 4;
b = (b & ~(uint256(15) << rookFrom)) | (((board >> rookFrom) & 15) << rookTo);
}
b |= piece << to;
}
}
function toBoard(Pos memory p) internal pure returns (uint256 board) {
for (uint256 t = 1; t <= 6; t++) board |= _spread(p.pc[t]) * t;
board |= _spread(p.black) << 3;
}
/// Bit i of `x` becomes bit 4 * i (the inverse of _compress).
function _spread(uint64 b) private pure returns (uint256 x) {
x = b;
x = (x | (x << 96)) & 0x000000000000000000000000ffffffff000000000000000000000000ffffffff;
x = (x | (x << 48)) & 0x000000000000ffff000000000000ffff000000000000ffff000000000000ffff;
x = (x | (x << 24)) & 0x000000ff000000ff000000ff000000ff000000ff000000ff000000ff000000ff;
x = (x | (x << 12)) & 0x000f000f000f000f000f000f000f000f000f000f000f000f000f000f000f000f;
x = (x | (x << 6)) & 0x0303030303030303030303030303030303030303030303030303030303030303;
x = (x | (x << 3)) & 0x1111111111111111111111111111111111111111111111111111111111111111;
}
}
src/Chess.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// What the rules, the engine and the hook share about a chess position, defined once.
///
/// Board: 64 squares of 4 bits (a1 = bits 0-3), piece type in the low three bits (1 pawn, 2 bishop, 3 knight,
/// 4 rook, 5 queen, 6 king), +8 for Black. A side's state packs its castling rooks, king square and en-passant
/// square (the ChessFish encoding). A move is from << 6 | to; promotion is always to a queen.
library Chess {
uint256 internal constant START_BOARD = 0xcbaedabc99999999000000000000000000000000000000001111111143265234;
uint32 internal constant START_WHITE = 0x000704ff;
uint32 internal constant START_BLACK = 0x383f3cff;
/// IMDuel's draw rules beyond stalemate, too little material and a position's third time, counting itself and the
/// positions up to sixteen half-moves earlier (the start position counts from any distance; a repetition further
/// apart is left to the quiet-move limit).
uint16 internal constant MAX_PLY = 200;
uint16 internal constant MAX_QUIET_PLY = 60; // half-moves without a capture or pawn move
/// 64 bits of the position's hash, as the hook's repetition memory and the engine's history keep it.
/// Positions come from play, not from a chooser, so a false match (about 2^-61 per check) is not reachable on
/// purpose. Full side states are kept, which is conservative about castling and en-passant rights.
function positionKey(uint256 board, uint32 whiteState, uint32 blackState, bool blackToMove, uint32 gameNo)
internal
pure
returns (uint64)
{
return uint64(uint256(keccak256(abi.encode(board, whiteState, blackState, blackToMove, gameNo))));
}
/// The piece type on square `sq` (0 empty).
function typeAt(uint256 board, uint256 sq) internal pure returns (uint8) {
return uint8(board >> (sq << 2)) & 7;
}
}
src/Rules.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Bitboard} from "./Bitboard.sol";
/// The rules the hook plays by, on the bitboard core: play a move and say how the game stands (encoding: Chess.sol).
/// Checked against chess.js on every position of test/data/legal.json and test/data/endings.json.
library Rules {
struct Played {
uint256 board;
uint32 mover; // the mover's new state
uint32 other; // the other side's new state
bool check; // the side now to move is in check
uint8 status; // 0 the game goes on, 1 stalemate, 2 checkmate
bool insufficient; // only two kings and at most one knight or bishop are left
}
error Illegal();
/// Plays `m` for the side to move (Black if `black`); reverts if it is illegal.
function move(uint256 board, uint32 mover, uint32 other, bool black, uint16 m)
internal
pure
returns (Played memory)
{
Bitboard.Pos memory p = Bitboard.fromBoard(board, black ? other : mover, black ? mover : other);
if (!Bitboard.isLegal(p, m, !black)) revert Illegal();
return playLegal(board, p, m, black);
}
/// Plays `m`, already known to be legal (taken from Bitboard.legalMoves of `p`, the position of `board`), and says
/// how the game stands.
function playLegal(uint256 board, Bitboard.Pos memory p, uint16 m, bool black) internal pure returns (Played memory r) {
Bitboard.Pos memory n = Bitboard.makeMove(p, m, !black);
r.board = Bitboard.boardAfter(board, p, m, !black);
(r.mover, r.other) = black ? (n.blackState, n.whiteState) : (n.whiteState, n.blackState);
bool any;
(r.check, any) = Bitboard.status(n, black);
r.status = any ? 0 : r.check ? 2 : 1;
uint64 kings = n.pc[6];
uint64 others = (n.white | n.black) & ~kings;
r.insufficient = Bitboard.popcount(kings & n.white) == 1 && Bitboard.popcount(kings & n.black) == 1
&& (others == 0 || (others & (others - 1) == 0 && others & (n.pc[2] | n.pc[3]) != 0));
}
}
src/swarm/IIntake.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// IMD's Intake, the part a buyer calls (imd.fun/docs, version 2 since 2026-10-10; captured in
/// knowledge-base/raw/2026-11-04/docs-llms.txt). Selector 0x9a78c321.
interface IIntake {
struct Callback {
address target;
bytes4 selector;
}
function requestWithFailure(
bytes32 action,
bytes calldata body,
Callback calldata callback,
bytes4 onFailure,
address asset,
uint256 amount
) external returns (bytes32 requestId);
}
/// The oracle's signed answer (domain "IdentityMD Oracle", version 2). `requestId` and `panelJobId` are IMD's UUIDs as
/// sixteen raw bytes, left-aligned; `answer` is `abi.encode` of the value; `answerType` 2 is bytes32.
struct Attestation {
bytes32 requestId;
uint256 chainId;
bytes32 questionHash;
uint8 answerType;
bytes answer;
uint256 figure;
uint64 fromBlock;
uint64 toBlock;
bytes32 blockHash;
bytes32 panelJobId;
uint16 panelSize;
uint16 quorum;
uint16 agreed;
uint64 issuedAt;
uint64 expiresAt;
}
src/swarm/ISwarmOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {SwarmRules} from "./SwarmRules.sol";
/// The port between Swarm Duel and whatever asks the swarm:
/// SwarmDuel asks for Black's move; the adapter answers later with the move or a failure. SwarmDuel knows nothing else
/// about the swarm, so an adapter can be replaced (by the deployer, after a 3-day notice) without touching the game.
interface ISwarmOracle {
/// What one ask costs, in IMD (immutable per adapter).
function price() external view returns (uint256);
/// Asks for Black's move in `g` (a position SwarmRules keeps), paying exactly `price` pulled from the caller.
/// `legal`: Black's legal moves in SwarmRules' order; `history`: the game's moves so far, sixteen to a word (bits
/// 0-11 the move, bit 12 a promotion). Returns the ask's id; reverts, paying nothing, when it can't ask.
function ask(SwarmRules.Game calldata g, uint16[] calldata legal, uint256[] calldata history)
external
returns (bytes32 id);
}
/// The port's other half, which SwarmDuel implements: only the game's adapter calls it, only for the pending id.
interface ISwarmOracleClient {
/// The swarm's move for ask `id` (Chess.sol encoding; legality is SwarmDuel's to check) and how many of the panel
/// gave it (`agreed`, kept for the record only).
function answered(bytes32 id, uint16 move, uint16 agreed) external;
/// Ask `id` gave no move; `cause` is one of SwarmCause.
function failed(bytes32 id, uint8 cause) external;
}
/// Why an ask gave no move. SwarmDuel's breaker counts the causes that say the oracle is broken (DECLINED, REFUSED,
/// INVALID, LATE) and never the panel's own choices (SPLIT, ILLEGAL).
library SwarmCause {
uint8 internal constant DECLINED = 1; // the ask reverted or was declined before paying
uint8 internal constant REFUSED = 2; // IMD refused the question after payment (or any status it doesn't explain)
uint8 internal constant SPLIT = 3; // the panel disagreed: no move reached the quorum
uint8 internal constant INVALID = 4; // an answer our checks reject (signer, hash, settings, format)
uint8 internal constant LATE = 5; // no answer within the hour
uint8 internal constant ILLEGAL = 6; // a signed move that is not legal here
}
src/swarm/PositionRing.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// A game's last sixteen positions as 64-bit keys (Chess.positionKey), four to a word: lane (ply % 16) holds the position
/// after that half-move, even lanes in words 0-1 and odd lanes in words 2-3, so each side's eight are two reads. The
/// main duel's ring as a library for Swarm Duel; the live hook keeps its own frozen copy (IMDuelHook `recentPositions`,
/// `_laneAt`, `_key`, `_history`, `_repeated`).
library PositionRing {
/// The word and bit offset of the lane of half-move `ply`.
function laneAt(uint256 ply) internal pure returns (uint256 word, uint256 shift) {
uint256 l = ply % 16;
uint256 k = l >> 1;
(word, shift) = ((l & 1) * 2 + (k >> 2), (k & 3) * 64);
}
/// The k-th (0-7) key of the lanes with the parity of `ply`.
function key(uint256[4] memory ring, uint256 ply, uint256 k) internal pure returns (uint64) {
uint256 w = (ply & 1) * 2 + (k >> 2);
return uint64(ring[w] >> ((k & 3) * 64));
}
/// Writes `k` into the lane of half-move `ply`, over the key sixteen half-moves older.
function write(uint256[4] memory ring, uint256 ply, uint64 k) internal pure {
(uint256 w, uint256 shift) = laneAt(ply);
ring[w] = (ring[w] & ~(uint256(type(uint64).max) << shift)) | (uint256(k) << shift);
}
/// The side to move's last eight positions, most recent first, as the engine takes them (`previous`). None can
/// repeat until four reversible half-moves have passed, so they are left empty before that.
function previous(uint256[4] memory ring, uint256 ply, uint256 quiet) internal pure returns (uint64[8] memory p) {
if (quiet < 3) return p;
for (uint256 i; i < 8; i++) p[i] = key(ring, ply, ((ply + 14 - i * 2) % 16) >> 1);
}
/// Whether position `k`, just reached at half-move count `ply` (after the move), is there for the third time:
/// counting itself, the ring's eight positions with the same side to move (up to sixteen half-moves back, the
/// oldest written over only after this check), and the game's start position from any distance (`atStart`).
function repeated(uint256[4] memory ring, uint256 ply, uint256 quiet, uint64 k, bool atStart)
internal
pure
returns (bool)
{
// a position needs four reversible half-moves to recur, and nothing before the last capture or pawn move can
if (quiet < 4) return false;
uint256 seen = atStart ? 1 : 0;
// the key's side to move is `ply`'s; those positions were made by half-moves of the other parity
for (uint256 i; i < 8; i++) {
if (key(ring, ply + 1, i) == k && ++seen == 2) return true;
}
return false;
}
}
src/swarm/SwarmRules.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Bitboard} from "../Bitboard.sol";
import {Chess} from "../Chess.sol";
import {Rules} from "../Rules.sol";
import {PositionRing} from "./PositionRing.sol";
/// Swarm Duel's chess, stateless, called by staticcall.
/// The main duel's rules (Rules, Bitboard; encoding in Chess.sol) and its draw rules, with two differences: a game
/// may start with odds, and a game's own start position is the one that counts for repetition from any distance.
/// Fixed: a changeable rules contract would be power over the game.
contract SwarmRules {
/// A game as SwarmDuel keeps it, before the move.
struct Game {
uint256 board;
uint32 white; // side states (Chess.sol)
uint32 black;
uint16 ply; // half-moves played; White moves on even plies
uint16 quiet; // half-moves since the last capture or pawn move
uint32 gameNo; // in every position key, so no game repeats another's positions
uint8 level; // the swarm's odds this game (start)
}
/// A game after a move.
struct Outcome {
uint256 board;
uint32 white;
uint32 black;
uint16 quiet;
bool check; // the side now to move is in check
uint8 result; // 0 the game goes on, 1 White wins, 2 Black wins, 3 a draw
uint8 reason; // a draw's: 1 stalemate, 2 too few pieces to mate, 3 a third repetition, 4 the quiet limit, 5 the move cap
uint256[4] ring; // the positions the next move is judged against (PositionRing); kept as it was once the game ends
}
/// The highest odds level: the swarm without its f7 pawn, b8 knight, a8 rook and queen.
uint8 public constant MAX_LEVEL = 4;
/// The squares the swarm gives up, level by level: f7, b8, a8, d8.
uint256 internal constant F7 = 53;
uint256 internal constant B8 = 57;
uint256 internal constant A8 = 56;
uint256 internal constant D8 = 59;
/// Black's queen-side rook flag (Bitboard: a flagged rook byte never castles).
uint32 internal constant NO_LONG_CASTLE = 0x80000000;
error BadLevel();
error NoLegalMove();
/// The start position for odds `level` (0 none, then one more piece of the swarm's at each level up to 4). With
/// the a8 rook gone, Black can't castle long.
function start(uint8 level) public pure returns (uint256 board, uint32 white, uint32 black) {
if (level > MAX_LEVEL) revert BadLevel();
(board, white, black) = (Chess.START_BOARD, Chess.START_WHITE, Chess.START_BLACK);
if (level >= 1) board = _clear(board, F7);
if (level >= 2) board = _clear(board, B8);
if (level >= 3) (board, black) = (_clear(board, A8), black | NO_LONG_CASTLE);
if (level >= 4) board = _clear(board, D8);
}
/// The side to move's legal moves, in Bitboard's order (by from-square); a promotion is one move (to a queen).
function legalMoves(uint256 board, uint32 white, uint32 black, bool blackToMove)
external
pure
returns (uint16[] memory)
{
return Bitboard.legalMoves(Bitboard.fromBoard(board, white, black), !blackToMove);
}
/// Whether `m` is legal for the side to move.
function isLegal(uint256 board, uint32 white, uint32 black, bool blackToMove, uint16 m) public pure returns (bool) {
return m < 4096 && Bitboard.isLegal(Bitboard.fromBoard(board, white, black), m, !blackToMove);
}
/// A legal move chosen by `seed`, for when neither the swarm nor the engine gives one: it can't fail on a position
/// that has a move (a game without one has already ended).
function pick(uint256 board, uint32 white, uint32 black, bool blackToMove, uint256 seed)
external
pure
returns (uint16)
{
uint16[] memory moves = Bitboard.legalMoves(Bitboard.fromBoard(board, white, black), !blackToMove);
if (moves.length == 0) revert NoLegalMove();
return moves[seed % moves.length];
}
/// Plays `m` for the side to move of `g` and judges the game, in the main duel's order: mate, stalemate, too few
/// pieces, a third repetition, the quiet limit, the move cap. An illegal move returns `legal` false and changes
/// nothing, so the caller never has to tell a rejected move from a failed call.
function play(Game calldata g, uint256[4] calldata ring, uint16 m)
external
pure
returns (bool legal, Outcome memory o)
{
bool black = g.ply & 1 == 1;
Bitboard.Pos memory p = Bitboard.fromBoard(g.board, g.white, g.black);
if (m >= 4096 || !Bitboard.isLegal(p, m, !black)) return (false, o);
Rules.Played memory r = Rules.playLegal(g.board, p, m, black);
(o.board, o.check, o.ring) = (r.board, r.check, ring);
(o.white, o.black) = black ? (r.other, r.mover) : (r.mover, r.other);
o.quiet = _captured(g.board, m) != 0 || Chess.typeAt(g.board, m >> 6) == 1 ? 0 : g.quiet + 1;
uint16 ply = g.ply + 1;
if (r.status == 2) {
o.result = black ? 2 : 1;
return (true, o);
}
uint64 k = Chess.positionKey(o.board, o.white, o.black, ply & 1 == 1, g.gameNo);
if (r.status == 1) o.reason = 1;
else if (r.insufficient) o.reason = 2;
else if (PositionRing.repeated(o.ring, ply, o.quiet, k, _atStart(o, ply, g.level))) o.reason = 3;
else if (o.quiet >= Chess.MAX_QUIET_PLY) o.reason = 4;
else if (ply >= Chess.MAX_PLY) o.reason = 5;
if (o.reason != 0) o.result = 3;
else PositionRing.write(o.ring, ply - 1, k); // the position after this move joins the memory, in its half-move's lane
legal = true;
}
/// Whether the game stands at its own start position, White to move.
function _atStart(Outcome memory o, uint16 ply, uint8 level) private pure returns (bool) {
if (ply & 1 == 1) return false;
(uint256 board, uint32 white, uint32 black) = start(level);
return o.board == board && o.white == white && o.black == black;
}
/// The piece type `move` captures on `board`: the piece on the target square, or a pawn taken en passant. (The
/// hook's `_captured`, frozen there.)
function _captured(uint256 board, uint16 move) private pure returns (uint8) {
uint256 from = move >> 6;
uint256 to = move & 63;
uint8 target = Chess.typeAt(board, to);
if (target != 0) return target;
if (Chess.typeAt(board, from) == 1 && (from & 7) != (to & 7)) return 1; // a pawn's diagonal step to an empty square
return 0;
}
function _clear(uint256 board, uint256 sq) private pure returns (uint256) {
return board & ~(uint256(0xf) << (sq << 2));
}
}
src/swarm/SwarmText.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {SwarmRules} from "./SwarmRules.sol";
/// The swarm's question, written on chain: IMD's request
/// body for one move, in one preallocated buffer. The body opens with IMD's question document exactly as IMD hashes
/// it (compact JSON, keys sorted, ASCII only, nothing to escape), so the question hash is the keccak of that prefix;
/// the members IMD doesn't hash follow. Encoding of boards, side states and moves: Chess.sol.
/// The writing is unchecked arithmetic: every value is bounded (squares under 64, plies at most 200, lengths under
/// CAPACITY) and `_room` guards the buffer before every write. Moves and hex go out a word at a time.
library SwarmText {
/// A text being written: the buffer and how much of it is used.
struct Text {
bytes buf;
uint256 n;
}
/// What a question needs: the position now with Black's legal moves, the game so far, the odds start, the block
/// the window names and the chain.
struct Ask {
SwarmRules.Game g;
uint16[] legal;
uint256[] history; // sixteen moves a word: bits 0-11 the move, bit 12 a promotion
uint256 startBoard; // the game's start; only written when g.level > 0
uint32 startWhite;
uint32 startBlack;
uint256 windowBlock;
uint256 chainId;
}
/// The written body, its question hash, and the lengths IMD limits.
struct Written {
bytes body;
bytes32 questionHash;
uint256 questionLength; // IMD: at most 2,000 characters
uint256 longestDefinition; // IMD: at most 512 characters a value
}
error TextTooLong();
uint256 internal constant CAPACITY = 24_576; // past IMD's 16 KiB body limit, so any position fits before the check
uint256 internal constant PLIES_PER_KEY = 60; // a history definition: 30 numbered pairs, at most 510 characters
bytes16 internal constant PIECES = ".PBNRQK..pbnrqk."; // Chess.sol codes: type in the low three bits, +8 for Black
bytes32 internal constant ZEROS = "00000000000000000000000000000000"; // half of a bytes32 in hex
// Fixed definitions (IMD: 1-512 characters each). Sorted with the others by key when written.
bytes internal constant ANSWER = "One of guards.allow: your move in UCI, lowercase (from square, to square, and q when a pawn promotes), "
"without the x mark, as ASCII bytes left-aligned and zero-padded to 32 bytes; the format, shown with a White "
"move: e2e4 is 0x6532653400000000000000000000000000000000000000000000000000000000.";
bytes internal constant NOTATION = "Moves are in UCI. In the game so far, White moves first in each numbered pair. "
"Castling is written as the king's move: e8g8 is Black castling short, e8c8 long. In Black's legal moves, a "
"capture is followed by x and the piece it takes, White's in capitals: a6b5xN takes a White knight.";
bytes internal constant POSITION = "The FEN (drawn in definitions board) and the game so far are the whole game. The "
"block window only dates the question; no chain data or outside source is needed.";
bytes internal constant BOARD = "Rank 8 to rank 1, files a to h; White in capitals, Black in lower case, a dot for an "
"empty square:";
bytes internal constant RULES = "Chess rules, with these differences: a pawn always promotes to a queen; the game is "
"drawn by stalemate, too few pieces to mate (kings with at most one bishop or knight), a position's third "
"appearance within the last 16 half-moves (the game's first position counts at any distance; a position just "
"after a pawn's two-square move never repeats), 60 half-moves without a capture or pawn move, or 200 half-moves in "
"all.";
/// Writes the body for `a` and hashes its question document.
function write(Ask memory a) internal pure returns (Written memory w) {
Text memory t = Text(new bytes(CAPACITY), 0);
SwarmRules.Game memory g = a.g;
uint256 keys = (g.ply + PLIES_PER_KEY - 1) / PLIES_PER_KEY; // history definitions, moves1 ...
put(t, '{"answerType":"bytes32","chainId":');
num(t, a.chainId);
put(t, ',"definitions":{"answer":"');
put(t, ANSWER);
w.longestDefinition = ANSWER.length;
put(t, '","board":"');
_board(t, g.board);
for (uint256 k; k < keys; k++) {
put(t, '","moves');
num(t, k + 1);
put(t, '":"');
uint256 from = t.n;
_moves(t, a.history, k * PLIES_PER_KEY, _min(g.ply, (k + 1) * PLIES_PER_KEY));
w.longestDefinition = _max(w.longestDefinition, t.n - from);
}
put(t, '","notation":"');
put(t, NOTATION);
put(t, '","position":"');
put(t, POSITION);
put(t, '","rules":"');
put(t, RULES);
w.longestDefinition = _max(w.longestDefinition, RULES.length);
if (g.level > 0) {
put(t, '","start":"');
fen(t, a.startBoard, a.startWhite, a.startBlack, false, 0, 0, new uint16[](0));
}
put(t, '"},"evidence":"panel","question":"Swarm Duel game ');
uint256 question = t.n - 16; // from "Swarm Duel game "
num(t, g.gameNo);
put(t, ", move ");
num(t, g.ply / 2 + 1);
put(t, ". You play Black against human players, who play White. Decide by your own reasoning: no chess engine, opening book or other tool.");
if (g.level > 0) put(t, " You gave odds: the game started from the position in definitions start.");
if (keys > 0) {
put(t, " The game so far is in definitions moves1");
if (keys > 1) {
put(t, " to moves");
num(t, keys);
}
put(t, ".");
}
put(t, " Position now (FEN): ");
fen(t, g.board, g.white, g.black, g.ply & 1 == 1, g.quiet, g.ply, a.legal);
put(t, ". Black's legal moves:");
for (uint256 i; i < a.legal.length; i++) {
char(t, " ");
uci(t, a.legal[i], _promotes(g.board, a.legal[i]));
_taken(t, g.board, a.legal[i]);
}
put(t, ". What is your move for Black?");
w.questionLength = t.n - question;
put(t, '","v":1,"window":{"fromBlock":');
num(t, a.windowBlock);
put(t, ',"toBlock":');
num(t, a.windowBlock);
put(t, "}}");
w.questionHash = _hash(t);
// the members IMD doesn't hash: the document's closing brace becomes a comma
t.buf[t.n - 1] = ",";
put(t, '"allowAmbiguous":true,"guards":{"allow":[');
for (uint256 i; i < a.legal.length; i++) {
if (i > 0) char(t, ",");
char(t, '"');
allowed(t, a.legal[i], _promotes(g.board, a.legal[i]));
char(t, '"');
}
put(t, ']},"panelSize":7,"quorum":3,"validForSeconds":86400}');
w.body = close(t);
}
/// FEN of a position: placement, side to move, castling rights (a rook byte without its flag, Bitboard), the en
/// passant square only when a legal move takes there (as chess.js and python-chess write it), the quiet count
/// and the move number.
function fen(
Text memory t,
uint256 board,
uint32 white,
uint32 black,
bool blackToMove,
uint256 quiet,
uint256 ply,
uint16[] memory legal
) internal pure {
unchecked {
for (uint256 rank = 8; rank > 0; rank--) {
uint256 empty;
for (uint256 file; file < 8; file++) {
uint256 p = (board >> ((((rank - 1) << 3) | file) << 2)) & 15;
if (p == 0) {
empty++;
continue;
}
if (empty != 0) char(t, bytes1(uint8(48 + empty)));
empty = 0;
char(t, PIECES[p]);
}
if (empty != 0) char(t, bytes1(uint8(48 + empty)));
if (rank > 1) char(t, "/");
}
put(t, blackToMove ? bytes(" b ") : bytes(" w "));
uint256 rights = t.n;
if ((white >> 16) & 0xff < 64) char(t, "K");
if ((white >> 24) & 0xff < 64) char(t, "Q");
if ((black >> 16) & 0xff < 64) char(t, "k");
if ((black >> 24) & 0xff < 64) char(t, "q");
if (t.n == rights) char(t, "-");
char(t, " ");
uint256 ep = (blackToMove ? white : black) & 0xff; // the square behind the other side's double step
if (ep < 64 && _takes(board, legal, ep)) square(t, ep);
else char(t, "-");
char(t, " ");
num(t, quiet);
char(t, " ");
num(t, ply / 2 + 1);
}
}
/// The position as eight rows after BOARD, rank 8 first: "8 rnbqkbnr, 7 pppppppp, ..., 1 RNBQKBNR." (a fixed length).
function _board(Text memory t, uint256 board) private pure {
unchecked {
put(t, BOARD);
for (uint256 rank = 8; rank > 0; rank--) {
char(t, " ");
char(t, bytes1(uint8(48 + rank)));
char(t, " ");
for (uint256 file; file < 8; file++) {
uint256 p = (board >> ((((rank - 1) << 3) | file) << 2)) & 15;
char(t, p == 0 ? bytes1(".") : PIECES[p]);
}
char(t, rank > 1 ? bytes1(",") : bytes1("."));
}
}
}
/// After a capture in Black's legal moves: x and the White piece it takes (en passant: a pawn); nothing otherwise.
function _taken(Text memory t, uint256 board, uint16 m) private pure {
uint256 from = (m >> 6) & 63;
uint256 to = m & 63;
uint256 p = (board >> (to << 2)) & 15;
if (p == 0 && (board >> (from << 2)) & 7 == 1 && (from & 7) != (to & 7)) p = 1; // a pawn moving aside: en passant
if (p == 0) return;
char(t, "x");
char(t, PIECES[p]);
}
/// `m` in UCI: from, to, and q for a promotion (one word written).
function uci(Text memory t, uint16 m, bool promotes) internal pure {
_word(t, _uciWord(m, promotes), promotes ? 5 : 4);
}
/// `m` as the oracle's bytes32 answer, in hex: its UCI's ASCII left-aligned, zero-padded (four words written).
function allowed(Text memory t, uint16 m, bool promotes) internal pure {
unchecked {
uint256 len = promotes ? 5 : 4;
uint256 ascii = _uciWord(m, promotes);
uint256 hex_;
for (uint256 i; i < len; i++) {
uint256 b = (ascii >> (248 - 8 * i)) & 0xff;
hex_ |= (uint256(uint8(_hex(b >> 4))) << (248 - 16 * i)) | (uint256(uint8(_hex(b & 15))) << (240 - 16 * i));
}
_word(t, uint256(bytes32("0x")), 2);
_word(t, hex_, 2 * len);
_word(t, uint256(ZEROS), 32);
_word(t, uint256(ZEROS), 32 - 2 * len);
}
}
function square(Text memory t, uint256 sq) internal pure {
unchecked {
_word(t, ((97 + (sq & 7)) << 248) | ((49 + (sq >> 3)) << 240), 2);
}
}
function num(Text memory t, uint256 v) internal pure {
unchecked {
uint256 digits = 1;
for (uint256 x = v; x >= 10; x /= 10) digits++;
_room(t, digits);
bytes memory buf = t.buf;
uint256 end = t.n + digits;
for (uint256 i = end; i > t.n; i--) {
uint256 d = 48 + v % 10;
assembly ("memory-safe") {
mstore8(add(add(buf, 31), i), d)
}
v /= 10;
}
t.n = end;
}
}
function put(Text memory t, bytes memory s) internal pure {
_copy(t, s, s.length);
}
function char(Text memory t, bytes1 c) internal pure {
unchecked {
uint256 n = t.n;
_room(t, 1);
bytes memory buf = t.buf;
assembly ("memory-safe") {
mstore8(add(add(buf, 32), n), shr(248, c))
}
t.n = n + 1;
}
}
/// The written bytes (the buffer shortened in place).
function close(Text memory t) internal pure returns (bytes memory b) {
b = t.buf;
uint256 n = t.n;
assembly ("memory-safe") {
mstore(b, n)
}
}
/// The game's moves from half-move `from` up to `to` (exclusive), numbered: "1. e2e4 e7e5 2. g1f3".
function _moves(Text memory t, uint256[] memory history, uint256 from, uint256 to) private pure {
unchecked {
for (uint256 k = from; k < to; k++) {
if (k > from) char(t, " ");
if (k & 1 == 0) {
num(t, k / 2 + 1);
_word(t, uint256(bytes32(". ")), 2);
}
uint256 m = (history[k >> 4] >> ((k & 15) << 4)) & 0xffff;
uci(t, uint16(m & 4095), m & 4096 != 0);
}
}
}
/// Whether a pawn of the side to move takes en passant on `ep` by one of the legal moves.
function _takes(uint256 board, uint16[] memory legal, uint256 ep) private pure returns (bool) {
unchecked {
for (uint256 i; i < legal.length; i++) {
if (legal[i] & 63 == ep && (board >> ((legal[i] >> 6) << 2)) & 7 == 1) return true;
}
return false;
}
}
/// Whether `m` on `board` is a pawn reaching the last rank.
function _promotes(uint256 board, uint16 m) private pure returns (bool) {
unchecked {
uint256 to = m & 63;
return (board >> ((m >> 6) << 2)) & 7 == 1 && (to < 8 || to >= 56);
}
}
function _hash(Text memory t) private pure returns (bytes32 h) {
bytes memory buf = t.buf;
uint256 n = t.n;
assembly ("memory-safe") {
h := keccak256(add(buf, 32), n)
}
}
function _room(Text memory t, uint256 len) private pure {
if (t.n + len > t.buf.length) revert TextTooLong();
}
/// A move's UCI characters, left-aligned in a word.
function _uciWord(uint16 m, bool promotes) private pure returns (uint256) {
unchecked {
uint256 from = (m >> 6) & 63;
uint256 to = m & 63;
return ((97 + (from & 7)) << 248) | ((49 + (from >> 3)) << 240) | ((97 + (to & 7)) << 232)
| ((49 + (to >> 3)) << 224) | (promotes ? uint256(113) << 216 : 0);
}
}
/// The first `len` bytes of word `w` (the whole word is stored; the rest is written over by what follows).
function _word(Text memory t, uint256 w, uint256 len) private pure {
unchecked {
uint256 n = t.n;
_room(t, 32);
bytes memory buf = t.buf;
assembly ("memory-safe") {
mstore(add(add(buf, 32), n), w)
}
t.n = n + len;
}
}
function _hex(uint256 v) private pure returns (bytes1) {
unchecked {
return bytes1(uint8(v < 10 ? 48 + v : 87 + v));
}
}
/// The first `len` bytes of `s`.
function _copy(Text memory t, bytes memory s, uint256 len) private pure {
unchecked {
uint256 n = t.n;
_room(t, len);
bytes memory buf = t.buf;
assembly ("memory-safe") {
mcopy(add(add(buf, 32), n), add(s, 32), len)
}
t.n = n + len;
}
}
function _min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
function _max(uint256 a, uint256 b) private pure returns (uint256) {
return a > b ? a : b;
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"v4-core/=lib/v4-core/",
"@uniswap/v4-core/=lib/v4-core/",
"forge-std/=lib/v4-core/lib/forge-std/src/",
"solmate/=lib/v4-core/lib/solmate/",
"@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
"openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.