Verified contractExactLGPL-3.0-only
VirtualMachine
Address0xcc7c0ef5d0cfb0e9adf64da3729e386d0e5f6e22
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 10,000 runs
- EVM version
- osaka
- Via IR
- yes
- License
- LGPL-3.0-only
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,392,175
- Creation transaction
- 0xaf4d02bd66…6ece31fcb6
17 files
- src/VirtualMachine.solmain9.62 KB
- lib/solady/src/utils/SafeTransferLib.sol32.86 KB
- src/BlueprintEncoder.sol51.16 KB
- src/CommandPacking.sol34.07 KB
- src/DataModel.sol6.37 KB
- src/DepositApproved.sol4.23 KB
- src/Explode.sol4.49 KB
- src/MemoryUtils.sol1.81 KB
- src/RegisterFile.sol5 KB
- src/RegisterHelpers.sol1.27 KB
- src/SafeTransferLib.sol1.3 KB
- src/StorageSlots.sol344 B
- src/SurgeryOPS.sol3.42 KB
- src/VMLogLib.sol6.94 KB
- src/VmConstants.sol1.03 KB
- src/VmErrors.sol3.45 KB
- src/interfaces/IERC20.sol457 B
src/VirtualMachine.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;
import './DataModel.sol';
import './RegisterFile.sol';
import './CommandPacking.sol';
import './BlueprintEncoder.sol';
import './SurgeryOPS.sol';
import './DepositApproved.sol';
import './VMLogLib.sol';
import './SafeTransferLib.sol';
import './Explode.sol';
import './VmErrors.sol';
import './RegisterHelpers.sol';
/// @title VirtualMachine
/// @custom:version 1.2.0
/// @notice Main VM execution engine that interprets and executes command sequences with register-based state management
contract VirtualMachine {
using RegisterHelpers for uint8;
using RegisterHelpers for uint256;
using RegisterHelpers for bytes;
using RegisterFile for bytes[];
/* ───────────────────────── PUBLIC ENTRYPOINTS ───────────────────── */
/// @notice Executes a command sequence and returns the output from a RETURN opcode.
/// @dev Commands execute sequentially with shared register state until RETURN or completion.
function runVM(VMCommand[] calldata commands, VMState memory initialState) public payable returns (bytes memory) {
return _run(commands, initialState);
}
/// @notice Executes commands with state introspection capabilities.
/// @dev Returns both the final state snapshot and execution output for debugging/analysis.
function runWithState(
VMCommand[] calldata commands,
VMState memory initialState
)
public
payable
returns (VMState memory, bytes memory)
{
bytes memory out = _run(commands, initialState); // state mutated in‑place
return (initialState, out);
}
/* ────────────────────────── CORE EXECUTION ENGINE ─────────────────────── */
/// @dev Primary execution loop with inline opcode handlers for maximum efficiency.
/// All opcodes are handled within this function to eliminate call overhead and
/// maintain optimal register access patterns.
function _run(VMCommand[] calldata commands, VMState memory vmState) internal returns (bytes memory) {
uint256 len = commands.length;
for (uint256 i; i < len;) {
VMCommand calldata cmd = commands[i];
OP op = cmd.op;
bytes32 data = cmd.data;
if (op == OP.CALL) {
// External contract invocation with configurable call semantics
Call memory c = CommandPacking.unpackCall(data);
bytes memory callData = vmState.registers.get(c.srcReg.idx());
uint256 carried = callData.length;
// Check that calldata length is at least 32 bytes (32 for the length word + 0+ bytes for the selector)
if (carried < 32) revert VmErrors.InvalidCallDataLength();
// Skip the first 32 bytes (length prefix) by adjusting the pointer
assembly {
callData := add(callData, 0x20)
}
// The length word is data, not a trusted bound: a callee can plant it through setDynamic. Reject a
// length that runs past the register, or the call would send the VM memory that follows it.
if (callData.length > carried - 32) revert VmErrors.InvalidCallDataLength();
uint256 value;
if (c.callType == uint8(CallType.VALUECALL)) {
bytes memory v = vmState.registers.getStatic(c.valueReg.idx());
assembly {
value := mload(add(v, 32))
}
}
(bool success, bytes memory ret) = _performCall(c.target, CallType(c.callType), callData, value);
if (!success) {
// Bubble up the exact revert data from the failed call
assembly ('memory-safe') {
let p := mload(0x40)
returndatacopy(p, 0, returndatasize())
revert(p, returndatasize())
}
}
// Dynamic register allocation flag (MSB) determines storage strategy
if (c.destReg.isDyn()) {
vmState.registers.setDynamic(c.destReg.idx(), ret);
} else {
vmState.registers.set(c.destReg.idx(), ret);
}
} else if (op == OP.CALLDATA_BUILD) {
// Template-based calldata construction from blueprint specification
CallDataBuild memory cdb = CommandPacking.unpackCallDataBuild(data);
bytes memory built =
BlueprintEncoder.encodeFromBlueprint(cdb.selector, cdb.blueprint, vmState.registers);
vmState.registers.set(cdb.destReg.idx(), built);
} else if (op == OP.EXPLODE) {
// Structured data decomposition into individual register slots
// e.g: (uint,uint,uint) into (r0, r1, r2)
Explode memory e = CommandPacking.unpackExplode(data);
ExplodeLib.execute(vmState.registers, e);
} else if (op == OP.DEPOSIT_APPROVED) {
// ERC20 allowance verification and transfer
DepositApproved memory d = CommandPacking.unpackDepositApproved(data);
// Read the max deposit value from the register
bytes memory maxDepositBytes = vmState.registers.getStatic(d.maxDepositReg.idx());
uint256 maxDeposit;
assembly {
maxDeposit := mload(add(maxDepositBytes, 32))
}
uint256 depositedAmount = DepositApprovedLib.depositApproved(d, maxDeposit);
vmState.registers.set(d.destReg.idx(), RegisterHelpers.encUint(depositedAmount));
} else if (op == OP.CALLDATA_SURGERY) {
// In-place calldata modification via targeted byte operations
CallDataSurgery memory s = CommandPacking.unpackCallDataSurgery(data);
SurgeryOps.performSurgery(vmState.registers, s.sourceReg, s.surgeries, s.surgeryCount);
} else if (op == OP.RETURN) {
// Immediate execution termination with register data output
Return memory r = CommandPacking.unpackReturn(data);
return vmState.registers.get(r.sourceReg.idx());
} else if (op == OP.ABI_ENCODE) {
// Direct ABI encoding from register data via blueprint template
AbiEncode memory ae = CommandPacking.unpackAbiEncode(data);
bytes memory enc = BlueprintEncoder.encodeData(ae.blueprint, vmState.registers);
vmState.registers.set(ae.destReg.idx(), enc);
} else if (op == OP.REMAINING_GAS) {
// Store current remaining gas in register as raw uint256
RemainingGas memory rg = CommandPacking.unpackRemainingGas(data);
vmState.registers.set(rg.destReg.idx(), RegisterHelpers.encUint(gasleft()));
} else if (op == OP.NATIVE_BALANCE) {
// Store current native token balance in register as raw uint256
NativeBalance memory nb = CommandPacking.unpackNativeBalance(data);
address targetAddress = vmState.registers.get(nb.addrReg.idx()).asAddress();
vmState.registers.set(nb.destReg.idx(), RegisterHelpers.encUint(targetAddress.balance));
} else if (op == OP.LOG) {
// Emit log events with data from registers
Log memory log = CommandPacking.unpackLog(data);
VMLogLib.execute(vmState, log);
} else if (op == OP.SAFE_TRANSFER) {
// Safely transfer ERC20 tokens using Solady
SafeTransfer memory safeTransfer = CommandPacking.unpackSafeTransfer(data);
SafeTransferVMLib.execute(vmState.registers, safeTransfer);
} else {
revert VmErrors.InvalidOpcode(uint8(op));
}
unchecked {
++i;
}
}
// Execution completed without explicit RETURN - return empty bytes
return '';
}
/* ────────────────────────── CALL DISPATCH LAYER ────────────────────── */
/// @dev Low-level call dispatcher supporting all EVM call semantics.
/// Centralizes call logic to ensure consistent error handling and gas management.
function _performCall(
address target,
CallType t,
bytes memory data,
uint256 value
)
internal
returns (bool ok, bytes memory ret)
{
// Removing this altogether would require changing the CALL
// variants and compiler implementation.
if (t == CallType.DELEGATECALL) revert VmErrors.Disallowed();
if (t == CallType.CALL) return target.call(data);
if (t == CallType.STATICCALL) return target.staticcall(data);
// VALUECALL
return target.call{ value: value }(data);
}
/* ───────────────────────── ETHER HANDLING ───────────────────── */
/// @dev Accept direct ether transfers for value call operations
fallback() external payable { }
receive() external payable { }
}
lib/solady/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ETH transfer has failed.
error ETHTransferFailed();
/// @dev The ERC20 `transferFrom` has failed.
error TransferFromFailed();
/// @dev The ERC20 `transfer` has failed.
error TransferFailed();
/// @dev The ERC20 `approve` has failed.
error ApproveFailed();
/// @dev The ERC20 `totalSupply` query has failed.
error TotalSupplyQueryFailed();
/// @dev The Permit2 operation has failed.
error Permit2Failed();
/// @dev The Permit2 amount must be less than `2**160 - 1`.
error Permit2AmountOverflow();
/// @dev The Permit2 approve operation has failed.
error Permit2ApproveFailed();
/// @dev The Permit2 lockdown operation has failed.
error Permit2LockdownFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
/// @dev Suggested gas stipend for contract receiving ETH to perform a few
/// storage reads and writes, but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/// @dev The unique EIP-712 domain separator for the DAI token contract.
bytes32 internal constant DAI_DOMAIN_SEPARATOR =
0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
/// @dev The address for the WETH9 contract on Ethereum mainnet.
address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @dev The canonical Permit2 address.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
/// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
/// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ETH OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
//
// The regular variants:
// - Forwards all remaining gas to the target.
// - Reverts if the target reverts.
// - Reverts if the current contract has insufficient balance.
//
// The force variants:
// - Forwards with an optional gas stipend
// (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
// - If the target reverts, or if the gas stipend is exhausted,
// creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
// Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
// - Reverts if the current contract has insufficient balance.
//
// The try variants:
// - Forwards with a mandatory gas stipend.
// - Instead of reverting, returns whether the transfer succeeded.
/// @dev Sends `amount` (in wei) ETH to `to`.
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Sends all the ETH in the current contract to `to`.
function safeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer all the ETH and check if it succeeded or not.
if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// forgefmt: disable-next-item
if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
function trySafeTransferAllETH(address to, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
/// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
/// and upon failure, deploys a minimal vault to accrue the ETH.
function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
/// @solidity memory-safe-assembly
assembly {
to := shr(96, shl(96, to)) // Clean upper 96 bits.
for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
let selfBalanceBefore := selfbalance()
if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if extcodesize(mover) {
let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
mstore(0x00, to)
pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
// If `address(to).balance >= amount + balanceBefore`, skip vault workflow.
if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
// Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
if lt(selfBalanceBefore, selfbalance()) { invalid() }
}
let m := mload(0x40)
// If the mover is missing or bricked, deploy a minimal vault
// that withdraws all ETH to `to` when being called only by `to`.
// forgefmt: disable-next-item
mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
// Compute and store the bytecode hash.
mstore8(0x00, 0xff) // Write the prefix.
mstore(0x35, keccak256(m, 0x40))
mstore(0x01, shl(96, address())) // Deployer.
mstore(0x15, 0) // Salt.
vault := keccak256(0x00, 0x55)
pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
// The vault returns a single word on success. Failure reverts with empty data.
if iszero(returndatasize()) {
if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation.
}
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for
/// the current contract to manage.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function trySafeTransferFrom(address token, address from, address to, uint256 amount)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends all of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have their entire balance approved for the current contract to manage.
function safeTransferAllFrom(address token, address from, address to)
internal
returns (uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
)
) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransfer(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sends all of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransferAll(address token, address to) internal returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
mstore(0x20, address()) // Store the address of the current contract.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
)
) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, to) // Store the `to` argument.
amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// Reverts upon failure.
function safeApprove(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
/// then retries the approval again (some tokens, e.g. USDT, requires this).
/// Reverts upon failure.
function safeApproveWithRetry(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, retrying upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x34, 0) // Store 0 for the `amount`.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
mstore(0x34, amount) // Store back the original `amount`.
// Retry the approval, reverting upon failure.
success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
// Check the `extcodesize` again just in case the token selfdestructs lol.
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Returns the amount of ERC20 `token` owned by `account`.
/// Returns zero if the `token` does not exist.
function balanceOf(address token, address account) internal view returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
amount :=
mul( // The arguments of `mul` are evaluated from right to left.
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
)
}
}
/// @dev Performs a `token.balanceOf(account)` check.
/// `implemented` denotes whether the `token` does not implement `balanceOf`.
/// `amount` is zero if the `token` does not implement `balanceOf`.
function checkBalanceOf(address token, address account)
internal
view
returns (bool implemented, uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
implemented :=
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
amount := mul(mload(0x20), implemented)
}
}
/// @dev Returns the total supply of the `token`.
/// Reverts if the token does not exist or does not implement `totalSupply()`.
function totalSupply(address token) internal view returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x18160ddd) // `totalSupply()`.
if iszero(
and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
) {
mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
revert(0x1c, 0x04)
}
result := mload(0x00)
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// If the initial attempt fails, try to use Permit2 to transfer the token.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
if (!trySafeTransferFrom(token, from, to, amount)) {
permit2TransferFrom(token, from, to, amount);
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
/// Reverts upon failure.
function permit2TransferFrom(address token, address from, address to, uint256 amount)
internal
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(add(m, 0x74), shr(96, shl(96, token)))
mstore(add(m, 0x54), amount)
mstore(add(m, 0x34), to)
mstore(add(m, 0x20), shl(96, from))
// `transferFrom(address,address,uint160,address)`.
mstore(m, 0x36c78516000000000000000000000000)
let p := PERMIT2
let exists := eq(chainid(), 1)
if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
if iszero(
and(
call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
)
) {
mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
}
}
}
/// @dev Permit a user to spend a given amount of
/// another user's tokens via native EIP-2612 permit if possible, falling
/// back to Permit2 if native permit fails or is not implemented on the token.
function permit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
for {} shl(96, xor(token, WETH9)) {} {
mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
// Gas stipend to limit gas burn for tokens that don't refund gas when
// an non-existing function is called. 5K should be enough for a SLOAD.
staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
)
) { break }
// After here, we can be sure that token is a contract.
let m := mload(0x40)
mstore(add(m, 0x34), spender)
mstore(add(m, 0x20), shl(96, owner))
mstore(add(m, 0x74), deadline)
if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
mstore(0x14, owner)
mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
mstore(
add(m, 0x94),
lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
)
mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
// `nonces` is already at `add(m, 0x54)`.
// `amount != 0` is already stored at `add(m, 0x94)`.
mstore(add(m, 0xb4), and(0xff, v))
mstore(add(m, 0xd4), r)
mstore(add(m, 0xf4), s)
success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
break
}
mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
mstore(add(m, 0x54), amount)
mstore(add(m, 0x94), and(0xff, v))
mstore(add(m, 0xb4), r)
mstore(add(m, 0xd4), s)
success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
break
}
}
if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
}
/// @dev Simple permit on the Permit2 contract.
function simplePermit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0x927da105) // `allowance(address,address,address)`.
{
let addressMask := shr(96, not(0))
mstore(add(m, 0x20), and(addressMask, owner))
mstore(add(m, 0x40), and(addressMask, token))
mstore(add(m, 0x60), and(addressMask, spender))
mstore(add(m, 0xc0), and(addressMask, spender))
}
let p := mul(PERMIT2, iszero(shr(160, amount)))
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
)
) {
mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(p))), 0x04)
}
mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
// `owner` is already `add(m, 0x20)`.
// `token` is already at `add(m, 0x40)`.
mstore(add(m, 0x60), amount)
mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
// `nonce` is already at `add(m, 0xa0)`.
// `spender` is already at `add(m, 0xc0)`.
mstore(add(m, 0xe0), deadline)
mstore(add(m, 0x100), 0x100) // `signature` offset.
mstore(add(m, 0x120), 0x41) // `signature` length.
mstore(add(m, 0x140), r)
mstore(add(m, 0x160), s)
mstore(add(m, 0x180), shl(248, v))
if iszero( // Revert if token does not have code, or if the call fails.
mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) {
mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
internal
{
/// @solidity memory-safe-assembly
assembly {
let addressMask := shr(96, not(0))
let m := mload(0x40)
mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
mstore(add(m, 0x20), and(addressMask, token))
mstore(add(m, 0x40), and(addressMask, spender))
mstore(add(m, 0x60), and(addressMask, amount))
mstore(add(m, 0x80), and(0xffffffffffff, expiration))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Revokes an approval for `token` and `spender` for `address(this)`.
function permit2Lockdown(address token, address spender) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0xcc53287f) // `Permit2.lockdown`.
mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
mstore(add(m, 0x40), 1) // `approvals.length`.
mstore(add(m, 0x60), shr(96, shl(96, token)))
mstore(add(m, 0x80), shr(96, shl(96, spender)))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
revert(0x1c, 0x04)
}
}
}
}
src/BlueprintEncoder.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;
import './RegisterHelpers.sol';
import './RegisterFile.sol';
/// @title BlueprintEncoder
/// @custom:version 1.1.0
///
/// @notice A specialized, gas-efficient ABI encoder that uses a custom Domain
/// Specific Language (DSL) called a "blueprint" to construct calldata.
/// @dev This library is not a general-purpose ABI encoder. It is designed for
/// applications where the structure of the calldata is
/// known in advance. The caller must prepare all data in `registers`
/// beforehand and provide a `blueprint` that dictates the final layout.
///
/// CONCEPT OVERVIEW:
///
/// 1. Blueprint: A `bytes` array that acts as a set of instructions. It contains
/// a sequence of tokens that define the structure of the output.
///
/// 2. Registers: An array of `bytes` (`bytes[]`) that serves as a data source.
/// The blueprint references items in this array by their index. Each register
/// must be pre-formatted according to its type (static or dynamic).
///
/// 3. Tokens: The blueprint is composed of two categories of tokens (bytes):
///
/// A. Register Tokens (0x00 - 0x79): These bytes are indices into the
/// `registers` array. The 7th bit acts as a flag:
/// - Bit 7 clear (0b0...): The token points to a *static* register, which
/// is expected to be exactly 32 bytes long.
/// - Bit 7 set (0b1...): The token points to a *dynamic* register. The
/// register itself must be a self-contained, length-prefixed ABI blob
/// (i.e., `length | data | padding`).
///
/// B. Container Tokens (0x7B - 0x7F): These are control tokens that define
/// the start and end of tuples and arrays, allowing for nested data
/// structures.
///
/// ENCODING PROCESS:
///
/// The encoder uses a two-pass system:
///
/// - Fast Path (Flat Blueprint): If the blueprint contains no container tokens,
/// the encoder performs a single pass. It calculates the total size and writes
/// the data in one go, minimizing overhead.
///
/// - General Case (Nested Blueprint): For blueprints with nested structures,
/// a two-pass "measure-then-write" approach is used:
/// 1. Measure Pass (`_measure`): Traverses the blueprint to calculate the
/// exact size of the head and tail sections of the final payload without
/// writing any data. It uses a stack to handle nested containers and
/// records the dimensions of dynamic structures.
/// 2. Encode Pass (`_encodeCore`): Allocates a single buffer of the exact
/// required size and then performs a second traversal of the blueprint to
/// write the data, using the measurements from the first pass to correctly
/// place all pointers and data.
///
/// This two-pass system ensures that the entire payload can be constructed with
/// a single memory allocation.
///
/// HOW TO USE THE BLUEPRINT DSL:
///
/// The blueprint DSL is designed for applications where you need to construct
/// ABI-encoded calldata or data blobs from pre-prepared register values. Here's
/// how to use it effectively:
///
/// 1. **Prepare Your Data in Registers**: Before creating a blueprint, store all
/// your data in the `registers` array. Each register must be properly formatted:
/// - Static registers: Exactly 32 bytes (e.g., `abi.encode(uint256)`)
/// - Dynamic registers: First `abi.encode()` the data, then use `setDynamic()`
/// to create the length-prefixed blob
///
/// 2. **Construct the Blueprint**: Create a byte sequence using tokens:
/// - `0x00-0x79`: Static register indices (bit 7 clear)
/// - `0x80-0xF9`: Dynamic register indices (bit 7 set, actual index = value & 0x7F)
/// - `0x7F`: Start static tuple `(...)`
/// - `0x7E`: Start dynamic tuple `(...)`
/// - `0x7D`: Start static array `[...]`
/// - `0x7C`: Start dynamic array `[...]`
/// - `0x7B`: End any container
///
/// **Example 1 - Simple Function Call:**
/// ```solidity
/// // Function: transfer(address to, uint256 amount)
/// bytes[] memory registers = new bytes[](2);
/// registers[0] = abi.encode(address(0x123...)); // to address
/// registers[1] = abi.encode(uint256(1000)); // amount
///
/// bytes memory blueprint = abi.encodePacked(
/// uint8(0), // static register 0 (address)
/// uint8(1) // static register 1 (amount)
/// );
///
/// bytes memory calldata = BlueprintEncoder.encodeFromBlueprint(
/// bytes4(keccak256("transfer(address,uint256)")),
/// blueprint,
/// registers
/// );
/// ```
///
/// **Example 2 - Dynamic Data with Nested Structures:**
/// ```solidity
/// // Function: processData(uint256 id, (uint256 value, bytes data), uint256[] amounts)
/// bytes[] memory registers = new bytes[](6);
/// registers[0] = abi.encode(uint256(42)); // id
/// registers[1] = abi.encode(uint256(100)); // tuple.value
/// registers.setDynamic(2, abi.encode(bytes("hello"))); // tuple.data (note: setDynamic after abi.encode)
/// registers[3] = abi.encode(uint256(10)); // amounts[0]
/// registers[4] = abi.encode(uint256(20)); // amounts[1]
/// registers[5] = abi.encode(uint256(30)); // amounts[2]
///
/// bytes memory blueprint = abi.encodePacked(
/// uint8(0), // static register 0 (id)
/// uint8(0x7E), // START_TUPLE_DYNAMIC (tuple begins)
/// uint8(1), // static register 1 (tuple.value)
/// uint8(0x82), // dynamic register 2 (tuple.data, 2 | 0x80)
/// uint8(0x7B), // END_DYNAMIC (tuple ends)
/// uint8(0x7C), // START_ARRAY_DYNAMIC (array begins)
/// uint8(3), // static register 3 (amounts[0])
/// uint8(4), // static register 4 (amounts[1])
/// uint8(5), // static register 5 (amounts[2])
/// uint8(0x7B) // END_DYNAMIC (array ends)
/// );
/// ```
///
/// FIXED-SIZE ARRAYS WITH DYNAMIC ELEMENTS
///
/// ABI rule: A fixed-size array T[k] is encoded exactly like a k-tuple of T.
/// If T is dynamic (bytes, string, or a tuple containing any dynamic), then T[k]
/// is a dynamic container: the parent stores a pointer; the child region holds a
/// tuple head of k element heads followed by element tails. There is NO array
/// length word. Spec: https://docs.soliditylang.org/en/latest/abi-spec.html
///
/// Offset bases:
/// - Tuple (and fixed array encoded-as-tuple): element offsets are relative to the
/// start of the tuple head (the start of the child region the pointer targets).
/// - Dynamic array: element offsets are relative to the start of the array head
/// AFTER the 32-byte length word.
///
/// ENCODER DESIGN (DIVERGES FROM ABI WHEN REQUESTED BY BLUEPRINT)
/// - START_ARRAY_STATIC: always inlines in the parent head, treating contents as static
/// regardless of element tokens. Using this with dynamic elements is NON-ABI and
/// will not match Solidity's abi.encode.
/// - START_TUPLE_DYNAMIC: encodes via a pointer (child region in parent's tail),
/// matching ABI for fixed-size arrays whose element type is dynamic and for tuples
/// that contain dynamics.
///
/// Guidance:
/// - To match ABI for T[k] where T is dynamic (e.g., bytes[2], string[3], (bytes,uint)[k]),
/// use START_TUPLE_DYNAMIC ... END, not START_ARRAY_STATIC.
///
/// CONTAINER ENCODING REFERENCE
///
/// Legend:
/// - Parent head: what is written at the container's slot in the parent.
/// - Child region: content at the pointer target (if any).
/// - Offset base: where element offsets are measured from.
///
/// | Kind | Parent head | Child region start | Pointer | Length word | Offset base | Notes |
/// |-----------------------------------|------------------------------|---------------------------------------------|---------|-------------|-------------------------------------------|-------|
/// | Static tuple (all static types) | Inline (no pointer, no tail) | — | No | No | n/a | e.g., (uint,address) |
/// | Dynamic tuple (any dynamic type) | 32-byte pointer | Tuple head (k element head words) | Yes | No | Tuple head start | |
/// | Static array of static T[k] | Inline (no pointer, no tail) | — | No | No | n/a | e.g., uint[3] |
/// | Static array of dynamic T[k] | 32-byte pointer | Tuple head of k element heads | Yes | No | Tuple head start | ABI = k-tuple of T |
/// | Dynamic array of static T[] | 32-byte pointer | [length][elements inline] | Yes | Yes (first) | n/a (no per-element heads) | |
/// | Dynamic array of dynamic T[] | 32-byte pointer | [length][k element head words] | Yes | Yes (first) | Array head start + 32 (after length) | |
/// | Dynamic scalar (bytes/string) | 32-byte pointer (as element) | [length][data] | Yes* | Yes | n/a | *Top-level abi.encode = [0x20][length][data] |
///
/// Notes:
/// - "Inline (no pointer, no tail)" means the entire encoding is the fixed head words written in place.
/// - bytes/string always carry their own 32-byte length before data.
/// - Fixed arrays of dynamic types are encoded exactly like tuples of the same arity.
/// - In this encoder, START_ARRAY_STATIC always inlines, even if children are dynamic. For ABI parity,
/// use START_TUPLE_DYNAMIC for fixed arrays of dynamic types.
///
/// MEMORY LAYOUT EXAMPLES (annotated bases)
///
/// 1) Dynamic array of static uint256[] = [10, 20]
/// 0x00: [0x20] pointer to array region (base A = 0x20)
/// A+0x00: [0x02] length = 2
/// A+0x20: [10] element 0 (inline)
/// A+0x40: [20] element 1 (inline)
///
/// 2) Dynamic array of dynamic string[] = ["hello","world"]
/// 0x00: [0x20] pointer to array region (base A = 0x20)
/// A+0x00: [0x02] length = 2
/// (element offset base = A+0x20)
/// A+0x20: [0x40] off elem0 -> (A+0x20)+0x40 = A+0x60 = 0x80
/// A+0x40: [0x80] off elem1 -> (A+0x20)+0x80 = A+0xA0 = 0xC0
/// A+0x60: [0x05]["hello"...] string payload (length + data)
/// A+0xA0: [0x05]["world"...] string payload (length + data)
///
/// 3) Static array of dynamic bytes[2] = [0x1234, 0x5678] (ABI form = tuple)
/// 0x00: [0x20] pointer to tuple region (base B = 0x20)
/// (element offset base = B)
/// B+0x00: [0x40] off elem0 -> B+0x40 = 0x60
/// B+0x20: [0x80] off elem1 -> B+0x80 = 0xA0
/// B+0x40: [0x02][0x1234..] bytes payload (length + data)
/// B+0x80: [0x02][0x5678..] bytes payload (length + data)
/// (No array length word, unlike dynamic arrays)
///
/// 4) Dynamic scalar bytes = 0xdeadbeef (as an element in a parent)
/// Parent writes: [offset] pointer to bytes data
/// At offset: [0x04][0xdeadbeef000...] length=4, data padded to 32 bytes
/// (Top-level abi.encode(bytes): [0x20][0x04][0xdeadbeef000...])
///
/// 5) Dynamic tuple (string,uint256) = ("hello", 42)
/// 0x00: [0x20] pointer to tuple region (base T = 0x20)
/// T+0x00: [0x40] off "hello" (relative to T) -> T+0x40 = 0x60
/// T+0x20: [0x2a] uint256 = 42 (static in head)
/// T+0x40: [0x05]["hello"...] string payload (length + data)
///
/// 6) Static array uint256[2] = [10, 20]
/// Parent head words: [uint256=10][uint256=20]; no pointer; no child region or length word.
///
/// 7) Static tuple (uint256,address) = (100, 0x1234…7890)
/// Parent head words: [uint256=100][address=0x1234…7890]; no pointer; no child region or length word.
///
/// KEY POINTS
/// - Static containers (*_STATIC) encode inline here by design. If you place dynamic
/// elements inside them, the result diverges from abi.encode on purpose.
/// - Dynamic containers (*_DYNAMIC) emit a 32-byte pointer in the parent head and
/// place the child region in the parent's tail.
/// - Only START_ARRAY_DYNAMIC prepends a 32-byte length word to its child region.
/// - For ABI-compliant fixed arrays of dynamic types, use START_TUPLE_DYNAMIC.
/// - Offset bases: tuple/fixed-array-as-tuple -> tuple head start; dynamic array → array head start + 32.
library BlueprintEncoder {
using RegisterHelpers for uint8;
using RegisterFile for bytes[];
/*//////////////////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////////////////*/
// A word in the EVM is 32 bytes.
uint8 internal constant LEN_WORD = 32;
// --- ABI encoding constants ---
// Size of a function selector in bytes.
uint8 internal constant SELECTOR_SIZE = 4;
// Offset for writing data after length word + first data word (32 + 32 bytes).
uint8 internal constant DATA_OFFSET = 0x40;
// --- Register token boundaries ---
// Maximum token value for static register indices (0x00 - 0x7A).
uint8 internal constant MAX_STATIC_REGISTER_TOKEN = 0x7A;
// --- Temporary buffer limits ---
// Maximum number of dynamic containers that can be tracked in tmpDynHeads.
uint8 internal constant MAX_DYN_HEADS = 10;
// --- Bit-packing constants for `tmpDynHeads` and dynamic array metadata ---
// The measurement pass needs to store metadata about dynamic containers. For
// dynamic arrays, it must store both the head length and the element count.
// To save space, these are packed into a single uint256 word.
// Shift for element count: we shift the count left by 96 bits.
uint8 internal constant SHIFT_CNT = 96;
// Mask for head length: a 96-bit mask to extract the head length.
uint256 internal constant MASK_LEN = (1 << 96) - 1;
// --- Sizing Frame bit positions (for packed uint256 during measurement pass) ---
// Shift amount for tail length field in Sizing Frame.
uint8 internal constant SHIFT_SIZING_TAIL = 96;
// Shift amount for ContainerKind field in Sizing Frame.
uint8 internal constant SHIFT_SIZING_KIND = 192;
// --- Encoding Frame bit positions (for packed uint256 during encoding pass) ---
// Shift amount for current head offset field in Encoding Frame.
uint8 internal constant SHIFT_FRAME_CUR_HEAD = 48;
// Shift amount for tail start field in Encoding Frame.
uint8 internal constant SHIFT_FRAME_TAIL_START = 96;
// Shift amount for current tail offset field in Encoding Frame.
uint8 internal constant SHIFT_FRAME_CUR_TAIL = 144;
// Shift amount for ContainerKind field in Encoding Frame.
uint8 internal constant SHIFT_FRAME_KIND = 192;
/*//////////////////////////////////////////////////////////////////////////
BLUEPRINT TOKENS
//////////////////////////////////////////////////////////////////////////*/
/// Bit mask to check the "dynamic" flag on a register token (0x80 = 10000000).
/// If `(token & REG_DYNAMIC_MASK) != 0`, it's a dynamic register.
uint8 internal constant REG_DYNAMIC_MASK = 0x80;
// --- Container Tokens (0x7B-0x7F) ---
// These tokens control the opening and closing of tuples and arrays.
// They are ordered to simplify range checks (e.g., `t >= START_ARRAY_DYNAMIC`).
// Opening tokens for containers.
uint8 internal constant START_TUPLE_STATIC = 0x7F; // "(...)" - encoded inline, no pointer.
uint8 internal constant START_TUPLE_DYNAMIC = 0x7E; // "(...)" - pointer to tail data.
// NOTE: START_ARRAY_STATIC always encodes inline, treating the structure as static.
// For ABI-compliant encoding of T[k] where T is dynamic (e.g., bytes[2]),
// use START_TUPLE_DYNAMIC which encodes with a pointer as per ABI specification.
uint8 internal constant START_ARRAY_STATIC = 0x7D; // "[...]" - fixed-size, encoded inline.
uint8 internal constant START_ARRAY_DYNAMIC = 0x7C; // "[...]" - pointer to tail data with length prefix.
/// A single, shared token to close any container type.
uint8 internal constant END_DYNAMIC = 0x7B;
/*//////////////////////////////////////////////////////////////////////////
LIMITS & MASKS
//////////////////////////////////////////////////////////////////////////*/
/// A safety limit to prevent excessively deep nesting, which could lead to
/// stack exhaustion or denial-of-service. 12 levels is a generous limit.
uint8 internal constant MAX_STACK_DEPTH = 12;
// Masks for unpacking the Encoding Frame struct. The fields are 48 bits wide.
uint256 internal constant MASK_48 = (1 << 48) - 1;
// Mask for unpacking the Sizing Frame struct. The fields are 96 bits wide.
uint256 internal constant MASK_96 = (1 << 96) - 1;
/*//////////////////////////////////////////////////////////////////////////
TYPES
//////////////////////////////////////////////////////////////////////////*/
/**
* @dev Identifies the type of container currently being processed on the stack
* during either the measurement or encoding pass.
*/
enum ContainerKind {
NONE, // Root of the blueprint, not inside any container.
DYNAMIC_ARRAY, // A dynamic array, e.g., `uint[]`. Encoded with a pointer and length.
DYNAMIC_TUPLE, // A dynamic tuple. Encoded with a pointer.
STATIC_ARRAY, // A fixed-size array, e.g., `uint[3]`. Encoded inline.
STATIC_TUPLE // A static tuple. Encoded inline.
}
/*//////////////////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////////////////*/
error StackOverflow(); // Nesting depth exceeds MAX_STACK_DEPTH.
error StackUnderflow(); // Encountered a closing token (END_DYNAMIC) without a matching opener.
error DynHeadBufOverflow(); // The temporary buffer for dynamic head sizes is too small.
error InvalidToken(); // Encountered a byte in the blueprint that is not a valid token.
error UnclosedContainer(); // The blueprint ended while inside an open container.
error BufferTooSmall(uint256 required, uint256 provided); // The output buffer is smaller than the required size.
error BadStaticFormat(uint8 index); // A static register's length was not exactly 32 bytes.
error BadDynamicFormat(uint8 index); // A dynamic register's length was less than 32 bytes (must be length-prefixed).
/*//////////////////////////////////////////////////////////////////////////
PACKED SIZING FRAME (uint256) HELPERS
//////////////////////////////////////////////////////////////////////////*/
// During the measurement pass (`_measure`), a stack of `uint256` is used to
// track the sizes of nested containers. Each `uint256` is a packed struct
// representing a "Sizing Frame". This avoids stack-too-deep errors.
//
// Sizing Frame Layout (uint256):
// | Bits 255 - 192 (64) | Bits 191 - 96 (96) | Bits 95 - 0 (96) |
// |---------------------|--------------------|------------------|
// | ContainerKind | tailLength | headLength |
/// @dev Constructs a packed Sizing Frame.
function _mkSizing(uint256 headLen, uint256 tailLen, ContainerKind ct) internal pure returns (uint256 p) {
assembly {
p := or(or(headLen, shl(SHIFT_SIZING_TAIL, tailLen)), shl(SHIFT_SIZING_KIND, ct))
}
}
/// @dev Extracts the head length from a Sizing Frame.
function _szHead(uint256 p) internal pure returns (uint256) {
return p & MASK_96;
}
/// @dev Extracts the tail length from a Sizing Frame.
function _szTail(uint256 p) internal pure returns (uint256) {
return (p >> SHIFT_SIZING_TAIL) & MASK_96;
}
/// @dev Extracts the ContainerKind from a Sizing Frame.
function _szKind(uint256 p) internal pure returns (ContainerKind) {
return ContainerKind(uint8(p >> SHIFT_SIZING_KIND));
}
/// @dev Increments the head length in a Sizing Frame.
function _szAddHead(uint256 p, uint256 inc) internal pure returns (uint256) {
return p + inc;
}
/// @dev Increments the tail length in a Sizing Frame.
function _szAddTail(uint256 p, uint256 inc) internal pure returns (uint256) {
return p + (inc << SHIFT_SIZING_TAIL);
}
/*//////////////////////////////////////////////////////////////////////////
PACKED ENCODING FRAME (uint256) HELPERS
//////////////////////////////////////////////////////////////////////////*/
// During the encoding pass (`_encodeCore`), a similar packed struct is used
// for the "Encoding Frame" stack. It tracks the memory offsets for writing
// both the head and tail parts of each nested container.
//
// Encoding Frame Layout (uint256):
// | Bits 255-192 | Bits 191-144 | Bits 143-96 | Bits 95-48 | Bits 47-0 |
// |--------------|--------------|--------------|--------------|--------------|
// | ContainerKind| curTailOff | tailStart | curHeadOff | headStart |
// | (64 bits) | (48 bits) | (48 bits ) | (48 bits) | (48 bits) |
/// @dev Constructs a packed Encoding Frame.
function _mkFrame(
ContainerKind ct,
uint256 headStart,
uint256 curHeadOff,
uint256 tailStart,
uint256 curTailOff
)
internal
pure
returns (uint256 p)
{
assembly {
p := or(
or(
or(or(headStart, shl(SHIFT_FRAME_CUR_HEAD, curHeadOff)), shl(SHIFT_FRAME_TAIL_START, tailStart)),
shl(SHIFT_FRAME_CUR_TAIL, curTailOff)
),
shl(SHIFT_FRAME_KIND, ct)
)
}
}
/// @dev Extracts the absolute start offset of the head.
function _fHeadStart(uint256 p) internal pure returns (uint256) {
return p & MASK_48;
}
/// @dev Extracts the current relative offset within the head.
function _fHeadOff(uint256 p) internal pure returns (uint256) {
return (p >> SHIFT_FRAME_CUR_HEAD) & MASK_48;
}
/// @dev Extracts the absolute start offset of the tail.
function _fTailStart(uint256 p) internal pure returns (uint256) {
return (p >> SHIFT_FRAME_TAIL_START) & MASK_48;
}
/// @dev Extracts the current relative offset within the tail.
function _fTailOff(uint256 p) internal pure returns (uint256) {
return (p >> SHIFT_FRAME_CUR_TAIL) & MASK_48;
}
/// @dev Extracts the ContainerKind.
function _fKind(uint256 p) internal pure returns (ContainerKind) {
return ContainerKind(uint8(p >> SHIFT_FRAME_KIND));
}
/// @dev Bumps the current head offset.
function _fBumpHead(uint256 p, uint256 inc) internal pure returns (uint256) {
return p + (inc << SHIFT_FRAME_CUR_HEAD);
}
/// @dev Bumps the current tail offset.
function _fBumpTail(uint256 p, uint256 inc) internal pure returns (uint256) {
return p + (inc << SHIFT_FRAME_CUR_TAIL);
}
/*//////////////////////////////////////////////////////////////////////////
FLAT-BLUEPRINT HELPERS
//////////////////////////////////////////////////////////////////////////*/
/// @dev Checks if a blueprint has no container tokens. This allows using the
/// more efficient single-pass encoding path.
function _isFlat(bytes memory bp) private pure returns (bool flat) {
uint256 len = bp.length;
for (uint256 i; i < len;) {
uint8 t = uint8(bp[i]);
// Any container token immediately means the blueprint is not flat.
if (t == END_DYNAMIC || (t >= START_ARRAY_DYNAMIC && t <= START_TUPLE_STATIC)) return false;
unchecked {
++i;
}
}
return true;
}
/// @dev Single-pass measurement for a flat blueprint.
function _measureFlat(
bytes memory bp,
bytes[] memory regs
)
private
pure
returns (uint256 headBytes, uint256 tailBytes)
{
uint256 len = bp.length;
for (uint256 i; i < len;) {
uint8 tok = uint8(bp[i]);
// Every item in a flat blueprint contributes one 32-byte slot to the head part.
headBytes += LEN_WORD;
if (tok.isDyn()) {
// Dynamic register: its data goes into the tail.
uint8 idx = tok.idx();
uint256 blobLen = regs.get(idx).length;
// Dynamic registers must be pre-formatted (length-prefixed), hence >= 32 bytes.
if (blobLen < LEN_WORD) revert BadDynamicFormat(idx);
tailBytes += blobLen;
} else {
// Static register: its data is part of the head, size already counted.
// Just need to validate the token and register format.
if (tok > MAX_STATIC_REGISTER_TOKEN) revert InvalidToken();
if (regs.get(tok).length != LEN_WORD) revert BadStaticFormat(tok);
}
unchecked {
++i;
}
}
}
/// @dev Single-pass encoder for a flat blueprint, including a function selector.
function _encodeFlat(
bytes4 selector,
bytes memory bp,
bytes[] memory regs,
uint256 headBytes,
uint256 tailBytes
)
private
pure
returns (bytes memory out)
{
// Allocate the full buffer with length prefix for selector + head + tail.
uint256 payloadLen = SELECTOR_SIZE + headBytes + tailBytes;
out = _allocWithLength(payloadLen);
assembly {
mstore(add(out, DATA_OFFSET), selector)
} // write selector after length word
// Delegate to the core flat encoder, offsetting by 32 (length) + SELECTOR_SIZE bytes.
_encodeFlatCoreInto(out, bp, regs, headBytes, LEN_WORD + SELECTOR_SIZE);
return out;
}
/// @dev Core logic for flat encoding, writing into a pre-allocated buffer.
function _encodeFlatCoreInto(
bytes memory out,
bytes memory bp,
bytes[] memory regs,
uint256 headBytes,
uint256 startOffset
)
private
pure
{
// `headPtr` tracks the write position in the head section (relative to `headBase`).
uint256 headPtr = 0;
// `tailPtr` tracks the write position in the tail section (relative to `headBase`).
uint256 tailPtr = headBytes;
uint256 len = bp.length;
// The absolute memory offset where the ABI data begins.
uint256 headBase = startOffset;
for (uint256 i; i < len;) {
uint8 tok = uint8(bp[i]);
// --- STATIC REGISTER ---
if ((tok & REG_DYNAMIC_MASK) == 0) {
if (tok > MAX_STATIC_REGISTER_TOKEN) revert InvalidToken();
uint8 idx = tok;
if (regs.get(idx).length != LEN_WORD) revert BadStaticFormat(idx);
// Copy the 32-byte word directly into the head.
_copyWord(out, headBase + headPtr, regs.get(idx));
headPtr += LEN_WORD;
}
// --- DYNAMIC REGISTER ---
else {
uint8 idx = tok.idx();
bytes memory reg = regs.get(idx);
uint256 dataLen = reg.length;
if (dataLen < LEN_WORD) revert BadDynamicFormat(idx);
// Calculate the absolute memory address for the tail data.
uint256 absTail = headBase + tailPtr;
// Write the pointer to the head section.
_writeUint(out, headBase + headPtr, tailPtr);
// Copy the entire dynamic blob (length-prefixed) to the tail section.
uint256 written = _copyDyn(out, absTail, reg);
headPtr += LEN_WORD;
tailPtr += written;
}
unchecked {
++i;
}
}
}
/*//////////////////////////////////////////////////////////////////////////
PASS 1 - SIZE MEASUREMENT
//////////////////////////////////////////////////////////////////////////*/
/// @dev First pass for nested blueprints. Traverses the blueprint to calculate
/// the total size and gather metadata about dynamic containers.
function _measure(
bytes memory blueprint,
bytes[] memory registers,
uint256[MAX_DYN_HEADS] memory tmpDynHeads
)
private
pure
returns (uint256 totalBytes, uint256 headBytes, uint256 dynHeadCount)
{
// `stack` holds Sizing Frames to track container dimensions at each nesting level.
uint256[MAX_STACK_DEPTH] memory stack;
// `elemCount` tracks the number of elements in arrays at each nesting level.
uint256[MAX_STACK_DEPTH] memory elemCount;
// `metaIndex` tracks which slot in tmpDynHeads each container should use.
uint256[MAX_STACK_DEPTH] memory metaIndex;
uint256 sp; // stack pointer
uint256 nextMetaIdx; // next available slot in tmpDynHeads
// Initialize the stack with a root frame.
stack[0] = _mkSizing(0, 0, ContainerKind.NONE);
elemCount[0] = 0;
uint256 bpLen = blueprint.length;
uint256 regCount = registers.length;
for (uint256 i; i < bpLen;) {
uint8 tok = uint8(blueprint[i]);
ContainerKind open = _decodeKind(tok);
/*> open a new container */
if (open != ContainerKind.NONE) {
if (sp + 1 >= MAX_STACK_DEPTH) revert StackOverflow();
// Reserve slot for dynamic containers
if (open == ContainerKind.DYNAMIC_ARRAY || open == ContainerKind.DYNAMIC_TUPLE) {
if (nextMetaIdx >= tmpDynHeads.length) revert DynHeadBufOverflow();
metaIndex[sp + 1] = nextMetaIdx++;
}
// Push a new, empty Sizing Frame onto the stack for the new container.
stack[++sp] = _mkSizing(0, 0, open);
elemCount[sp] = 0; // Reset element count for the new level.
}
/*> close the current container */
else if (tok == END_DYNAMIC) {
if (sp == 0) revert StackUnderflow();
// Pop the completed child container's frame from the stack.
uint256 child = stack[sp];
uint256 childElemCount = elemCount[sp];
sp--;
ContainerKind ck = _szKind(child);
uint256 childHeadLen = _szHead(child);
uint256 childTailLen = _szTail(child);
// If the parent is an array, the child we just closed counts as one element.
ContainerKind parent = _szKind(stack[sp]);
if (parent == ContainerKind.DYNAMIC_ARRAY || parent == ContainerKind.STATIC_ARRAY) {
unchecked {
elemCount[sp]++;
}
}
bool dynamic = (ck == ContainerKind.DYNAMIC_TUPLE || ck == ContainerKind.DYNAMIC_ARRAY);
if (dynamic) {
// For dynamic containers, we add a 32-byte pointer to the parent's head.
// The container's content becomes part of the parent's tail.
uint256 idx = metaIndex[sp + 1];
// Store metadata for the encoding pass. For dynamic arrays, we pack
// the head length and element count together.
if (ck == ContainerKind.DYNAMIC_ARRAY) {
uint256 packed = childHeadLen | (childElemCount << SHIFT_CNT);
tmpDynHeads[idx] = packed;
} else {
// Tuple
tmpDynHeads[idx] = childHeadLen;
}
stack[sp] = _szAddHead(stack[sp], LEN_WORD); // Add pointer slot to parent head.
uint256 bytesChild = childHeadLen + childTailLen;
// Dynamic arrays also have a 32-byte length word.
if (ck == ContainerKind.DYNAMIC_ARRAY) {
stack[sp] = _szAddTail(
stack[sp],
bytesChild + LEN_WORD /*length word*/
);
} else {
stack[sp] = _szAddTail(stack[sp], bytesChild);
}
} else {
// For static containers, their head and tail are merged directly
// into the parent's head and tail. No pointers are needed.
// NOTE: This interprets STATIC_ARRAY as always inline, regardless of element types.
// For ABI-compliant encoding of T[k] where T is dynamic, use DYNAMIC_TUPLE
// which will encode with a pointer as specified in the ABI.
stack[sp] = _szAddHead(stack[sp], childHeadLen);
stack[sp] = _szAddTail(stack[sp], childTailLen);
}
}
/*> static register */
else if (tok <= MAX_STATIC_REGISTER_TOKEN) {
// A static register adds 32 bytes to the current container's head.
stack[sp] = _szAddHead(stack[sp], LEN_WORD);
ContainerKind here = _szKind(stack[sp]);
if (here == ContainerKind.DYNAMIC_ARRAY || here == ContainerKind.STATIC_ARRAY) {
unchecked {
elemCount[sp]++;
} // It's one element of an array.
}
}
/*> dynamic register */
else if (tok.isDyn()) {
uint8 idx = tok.idx();
// The void index reads as ZERO_VALUE at any file length, so it measures as one length word. An index
// past the register file measures as 0 so that pass 2 reverts RegisterIndexOOB.
uint256 blobLen = idx == VmConstants.VOID_REG ? LEN_WORD : (idx < regCount ? registers[idx].length : 0);
// A dynamic register adds a 32-byte pointer to the head and its
// blob length to the tail.
stack[sp] = _szAddHead(stack[sp], LEN_WORD);
stack[sp] = _szAddTail(stack[sp], blobLen);
ContainerKind here = _szKind(stack[sp]);
if (here == ContainerKind.DYNAMIC_ARRAY || here == ContainerKind.STATIC_ARRAY) {
unchecked {
elemCount[sp]++;
} // It's one element of an array.
}
} else {
revert InvalidToken();
}
unchecked {
++i;
}
}
if (sp != 0) revert UnclosedContainer();
// The final dimensions are in the root frame.
headBytes = _szHead(stack[0]);
totalBytes = headBytes + _szTail(stack[0]);
dynHeadCount = nextMetaIdx;
}
/*//////////////////////////////////////////////////////////////////////////
PASS 2 - ENCODING (ENTRY POINT)
//////////////////////////////////////////////////////////////////////////*/
/**
* @notice Encodes a full ABI payload, prepending a 4-byte function selector.
* @param selector The function selector.
* @param blueprint The byte-level layout description.
* @param registers Caller-supplied data referenced by the blueprint.
* @return out A (4 + N)-byte ABI blob suitable for a low-level `call`.
*/
function encodeFromBlueprint(
bytes4 selector,
bytes memory blueprint,
bytes[] memory registers
)
internal
pure
returns (bytes memory out)
{
/* fast path #0: empty blueprint */
if (blueprint.length == 0) {
// Nothing to encode, just return the selector with length prefix.
out = _allocWithLength(SELECTOR_SIZE);
assembly {
mstore(add(out, DATA_OFFSET), selector)
} // 0x20 (len) + 0x20 (first data word)
return out;
}
/* fast path #1: flat blueprint (no containers) */
if (_isFlat(blueprint)) {
(uint256 headB, uint256 tailB) = _measureFlat(blueprint, registers);
// Delegate to the specialized flat encoder.
return _encodeFlat(selector, blueprint, registers, headB, tailB);
}
/* general case: two-pass measure/encode for nested blueprints */
// Use a small, fixed-size buffer on the stack for performance.
uint256[MAX_DYN_HEADS] memory tmpHeads;
(uint256 total, uint256 headBytes, uint256 dynCnt) = _measure(blueprint, registers, tmpHeads);
// Copy the metadata from the temporary stack buffer to a properly-sized heap array.
// The data is needed in FIFO order for the encoding pass.
uint256[] memory dynHead = new uint256[](dynCnt);
for (uint256 j; j < dynCnt;) {
dynHead[j] = tmpHeads[j];
unchecked {
++j;
}
}
// Allocate the final buffer for the entire payload with length prefix.
uint256 payloadLen = SELECTOR_SIZE + total;
out = _allocWithLength(payloadLen);
assembly {
mstore(add(out, DATA_OFFSET), selector)
}
// Call the core encoder, starting after the length word + SELECTOR_SIZE.
_encodeCore(blueprint, registers, dynHead, out, LEN_WORD + SELECTOR_SIZE, headBytes);
return out;
}
/*//////////////////////////////////////////////////////////////////////////
MODULAR ENCODING
//////////////////////////////////////////////////////////////////////////*/
/**
* @notice Encodes an ABI data blob *without* a function selector.
* @param blueprint Layout description.
* @param registers Caller-supplied registers.
* @return out ABI-encoded data blob.
*/
function encodeData(bytes memory blueprint, bytes[] memory registers) internal pure returns (bytes memory out) {
/* fast path #0: empty blueprint */
if (blueprint.length == 0) return _allocWithLength(0); // just the 32-byte length word (value = 0)
/* fast path #1: flat blueprint */
if (_isFlat(blueprint)) {
(uint256 headB, uint256 tailB) = _measureFlat(blueprint, registers);
uint256 payloadLen = headB + tailB;
out = _allocWithLength(payloadLen);
_encodeFlatCoreInto(out, blueprint, registers, headB, LEN_WORD);
return out;
}
/* general case: two-pass measure/encode for nested blueprints */
uint256[MAX_DYN_HEADS] memory tmpHeads;
(uint256 total, uint256 headBytes, uint256 dynCnt) = _measure(blueprint, registers, tmpHeads);
uint256[] memory dynHead = new uint256[](dynCnt);
for (uint256 j; j < dynCnt;) {
dynHead[j] = tmpHeads[j];
unchecked {
++j;
}
}
out = _allocWithLength(total);
// Start writing at offset LEN_WORD (after length word), as there is no selector.
_encodeCore(blueprint, registers, dynHead, out, LEN_WORD, headBytes);
return out;
}
/**
* @dev Core encoding logic for nested blueprints (Pass 2).
* @param dynHead Pre-computed metadata for dynamic containers (FIFO).
* @param out The pre-allocated output buffer.
* @param startOffset Where to begin writing in `out` (32 or 36 bytes).
* @param headBytes Pre-measured size of the head section.
*/
function _encodeCore(
bytes memory blueprint,
bytes[] memory registers,
uint256[] memory dynHead,
bytes memory out,
uint256 startOffset,
uint256 headBytes
)
private
pure
{
// The head section starts at `startOffset`.
uint256 headStart = startOffset;
// The tail section starts immediately after the head section.
uint256 tailStart = startOffset + headBytes;
// `fs` is the "Frame Stack", holding packed Encoding Frames.
uint256[MAX_STACK_DEPTH] memory fs;
// Initialize the stack with the root frame, with offsets set up.
fs[0] = _mkFrame(ContainerKind.NONE, headStart, 0, tailStart, 0);
uint256 sp; // stack pointer
uint256 dynPop; // index for popping from `dynHead` metadata array
uint256 bpLen = blueprint.length;
for (uint256 i; i < bpLen;) {
uint8 tok = uint8(blueprint[i]);
uint256 frame = fs[sp];
/*> open a new container */
if (tok >= START_ARRAY_DYNAMIC && tok <= START_TUPLE_STATIC) {
if (sp + 1 >= MAX_STACK_DEPTH) revert StackOverflow();
ContainerKind ck = _decodeKind(tok);
uint256 childHeadStart;
uint256 childTailStart;
uint256 childHeadOff; // Used only by dynamic arrays for the length slot.
if (ck == ContainerKind.DYNAMIC_TUPLE || ck == ContainerKind.DYNAMIC_ARRAY) {
// This container is dynamic. Write a pointer to it in the parent's head.
// The pointer's target is the current end of the parent's tail.
uint256 absPtr = _fTailStart(frame) + _fTailOff(frame);
// If parent is a dynamic array, element head pointers are relative to headStart + 32
uint256 base = _fHeadStart(frame);
if (_fKind(frame) == ContainerKind.DYNAMIC_ARRAY) {
unchecked {
base += LEN_WORD;
}
}
uint256 relPtr = absPtr - base;
_writeUint(out, _fHeadStart(frame) + _fHeadOff(frame), relPtr);
// The pointer itself occupies 32 bytes in the parent's head.
frame = _fBumpHead(frame, LEN_WORD);
// Retrieve the pre-measured metadata for this container (in FIFO order).
if (dynPop >= dynHead.length) revert DynHeadBufOverflow();
uint256 meta = dynHead[dynPop++];
uint256 childHeadLen = meta & MASK_LEN;
// The child's data starts where the pointer points.
childHeadStart = absPtr;
if (ck == ContainerKind.DYNAMIC_ARRAY) {
// Dynamic arrays need their element count written first.
uint256 arrLen = meta >> SHIFT_CNT;
_writeUint(out, childHeadStart, arrLen);
// The child's head starts after its length word.
childHeadOff = LEN_WORD;
childTailStart = childHeadStart + LEN_WORD + childHeadLen;
// The child occupies `32 (len) + head + tail` bytes in the parent's tail.
frame = _fBumpTail(frame, LEN_WORD + childHeadLen);
} else {
// Dynamic Tuple
childTailStart = childHeadStart + childHeadLen;
// The child occupies `head + tail` bytes in the parent's tail.
frame = _fBumpTail(frame, childHeadLen);
}
} else {
// This container is static. It's encoded inline. Its head starts at the
// current position in the parent's head.
// NOTE: STATIC_ARRAY tokens always encode inline regardless of element types.
// For ABI-compliant encoding of T[k] where T is dynamic, use DYNAMIC_TUPLE
// which encodes with a pointer as per the ABI specification.
childHeadStart = _fHeadStart(frame) + _fHeadOff(frame);
childTailStart = _fTailStart(frame) + _fTailOff(frame);
}
fs[sp] = frame; // Save the updated parent frame.
++sp; // Push.
// Create the new child frame on the stack.
fs[sp] = _mkFrame(ck, childHeadStart, childHeadOff, childTailStart, 0);
}
/*> close the current container */
else if (tok == END_DYNAMIC) {
if (sp == 0) revert StackUnderflow();
// Pop the child frame that we just finished encoding.
uint256 closed = fs[sp--];
// Propagate the written lengths up to the new parent frame.
if (_fKind(closed) == ContainerKind.DYNAMIC_TUPLE || _fKind(closed) == ContainerKind.DYNAMIC_ARRAY) {
// Dynamic containers only grow the parent's tail.
fs[sp] = _fBumpTail(fs[sp], _fTailOff(closed));
} else {
// Static container
// Static containers grow both the parent's head and tail.
fs[sp] = _fBumpHead(fs[sp], _fHeadOff(closed));
fs[sp] = _fBumpTail(fs[sp], _fTailOff(closed));
}
}
/*> static register */
else if (tok <= MAX_STATIC_REGISTER_TOKEN) {
uint8 idx = tok;
if (registers.get(idx).length != LEN_WORD) revert BadStaticFormat(idx);
// Copy the 32-byte word directly into the current head position.
uint256 dst = _fHeadStart(frame) + _fHeadOff(frame);
_copyWord(out, dst, registers.get(idx));
// Advance the head offset for the current frame.
fs[sp] = _fBumpHead(frame, LEN_WORD);
}
/*> dynamic register */
else if (tok.isDyn()) {
uint8 idx = tok.idx();
if (registers.get(idx).length < LEN_WORD) revert BadDynamicFormat(idx);
// Write pointer to head.
uint256 absPtr = _fTailStart(frame) + _fTailOff(frame);
// For dynamic arrays, element head pointers are relative to the start of the
// array head AFTER the 32-byte length word. For other containers, pointers are
// relative to the container's head start as usual.
uint256 base = _fHeadStart(frame);
if (_fKind(frame) == ContainerKind.DYNAMIC_ARRAY) {
unchecked {
base += LEN_WORD;
} // skip array length word
}
uint256 relPtr = absPtr - base;
_writeUint(out, _fHeadStart(frame) + _fHeadOff(frame), relPtr);
// Copy data to tail.
uint256 bytesW = _copyDyn(out, absPtr, registers.get(idx));
// Advance head offset (for the pointer) and tail offset (for the data).
fs[sp] = _fBumpHead(frame, LEN_WORD);
fs[sp] = _fBumpTail(fs[sp], bytesW);
} else {
revert InvalidToken();
}
unchecked {
++i;
}
}
if (sp != 0) revert UnclosedContainer();
}
/*//////////////////////////////////////////////////////////////////////////
MEMORY COPY HELPERS
//////////////////////////////////////////////////////////////////////////*/
/// @dev Copies a 32-byte word from a `bytes` register to the output buffer.
function _copyWord(bytes memory out, uint256 dst, bytes memory srcReg) private pure {
if (dst + LEN_WORD > out.length) revert BufferTooSmall(dst + LEN_WORD, out.length);
assembly {
// `mstore` to `out + LEN_WORD (length) + dst`, from `srcReg + LEN_WORD (length)`.
mstore(add(add(out, LEN_WORD), dst), mload(add(srcReg, LEN_WORD)))
}
}
/// @dev Copies a dynamic, length-prefixed register blob.
function _copyDyn(bytes memory out, uint256 dst, bytes memory reg) private pure returns (uint256 written) {
// The register `reg` is a pre-encoded ABI blob: `<length><data>`.
// The first word of a `bytes` variable in memory holds its length.
uint256 blobLen;
assembly {
blobLen := mload(reg)
}
if (dst + blobLen > out.length) revert BufferTooSmall(dst + blobLen, out.length);
// Copy whole words, then restore the word after the blob, so exactly `blobLen` bytes change. A non-aligned
// blob's last word runs past `dst + blobLen`, which can lie outside `out`, on the encoder's frame stack.
// `reg` is allocated before `out`, so neither the copy nor the restore touches the source.
assembly {
let srcPtr := add(reg, LEN_WORD)
let dstPtr := add(add(out, LEN_WORD), dst)
let end := add(dstPtr, blobLen)
let after := mload(end)
for { let off := 0 } lt(off, blobLen) { off := add(off, LEN_WORD) } {
mstore(add(dstPtr, off), mload(add(srcPtr, off)))
}
mstore(end, after)
}
return blobLen;
}
/*//////////////////////////////////////////////////////////////////////////
UTILITY HELPERS
//////////////////////////////////////////////////////////////////////////*/
/// @dev Decodes a container token byte into its `ContainerKind`.
function _decodeKind(uint8 tok) private pure returns (ContainerKind kind) {
if (tok == START_TUPLE_DYNAMIC) return ContainerKind.DYNAMIC_TUPLE;
if (tok == START_ARRAY_DYNAMIC) return ContainerKind.DYNAMIC_ARRAY;
if (tok == START_TUPLE_STATIC) return ContainerKind.STATIC_TUPLE;
if (tok == START_ARRAY_STATIC) return ContainerKind.STATIC_ARRAY;
return ContainerKind.NONE;
}
/// @dev Writes a `uint` value into the output buffer at a given offset.
function _writeUint(bytes memory buf, uint256 off, uint256 val) private pure {
if (off + LEN_WORD > buf.length) revert BufferTooSmall(off + LEN_WORD, buf.length);
assembly {
// `mstore` to `buf + LEN_WORD (length) + off`.
mstore(add(add(buf, LEN_WORD), off), val)
}
}
/// @dev Allocates `LEN_WORD + payloadLen` bytes and writes `payloadLen` as the
/// first 32-byte word of the returned buffer's data area.
function _allocWithLength(uint256 payloadLen) private pure returns (bytes memory out) {
out = new bytes(LEN_WORD + payloadLen);
_writeUint(out, 0, payloadLen);
}
}
src/CommandPacking.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;
import './DataModel.sol';
import './VmErrors.sol';
import './VmConstants.sol';
/// @title CommandPacking
/// @custom:version 1.1.0
/// @notice Library for packing and unpacking VM commands into/from 32-byte words for efficient storage and transmission
library CommandPacking {
/// @dev Upper bound on an EXPLODE command's destination count, fixed by the byte layout: bytes
/// 2-27 of the packed word hold one destination register each, and bytes 28-31 are reserved
/// padding. The off-chain compiler mirrors this ceiling
/// (`MAX_EXPLODE_OUTPUTS` in `rs/lifi_vm_edsl/src/ir/isa/command/types/explode.rs`); the two
/// must agree or the compiler emits words this library rejects.
uint8 internal constant MAX_EXPLODE_DESTS = 26; // Max destination count for Explode
/// @dev Right-shift amount that lands byte 2 — the first destination-register byte — in the low
/// byte of a packed EXPLODE word. Destination `i` is read as
/// `uint8(packedDests >> (EXPLODE_DESTS_SHIFT_BASE - i * 8))`, since byte 2 occupies bits
/// 232-239 of the 32-byte word.
///
/// Why it exists as a named constant: `Explode.packedDests` deliberately carries the raw
/// command word rather than a decoded `uint8[]`, so that unpacking an EXPLODE does not
/// allocate a 26-word memory array. The cost of that choice is that the destination bytes
/// are re-derived at every read site — `unpackExplode`'s reserved-region check below,
/// `ExplodeLib.execute`, and `ExplodeLib._resolveDynamicEnd` — and each site needs the same
/// base shift. Naming it once keeps those readers provably in agreement; four copies of the
/// literal `232` could drift, and a drifted copy would read a neighbouring register index
/// rather than fail loudly.
uint256 internal constant EXPLODE_DESTS_SHIFT_BASE = 232;
/**
* @notice Packs a CALL command into a single 32-byte word.
* @dev Format:
* Byte 0: Call type (uint8) - variant/sub-opcode
* Bytes 1–20: Target address (20 bytes)
* Byte 21: Destination register (uint8) with dynamic flag in high bit.
* Byte 22: Source register (uint8) with dynamic flag in high bit.
* Byte 23: Value register (uint8) with dynamic flag in high bit.
* Bytes 24–31: Padding (8 bytes, available for future use)
* @param target The external contract address.
* @param callType The call type (0: DELEGATECALL, 1: CALL, etc.).
* @param destReg The destination register (with dynamic flag in high bit).
* @param srcReg The source register (with dynamic flag in high bit).
* @param valueReg The value register (with dynamic flag in high bit).
* @return packed The packed 32-byte command.
*/
function packCall(
address target,
uint8 callType,
uint8 destReg,
uint8 srcReg,
uint8 valueReg
)
internal
pure
returns (bytes32 packed)
{
assembly {
// Insert call type (byte 0, shift left by 248 bits) - variant at front like LOG
packed := shl(248, callType)
// Insert target address (bytes 1-20, shift left by 88 bits)
packed := or(packed, shl(88, target))
// Insert destination register (byte 21, shift left by 80 bits)
packed := or(packed, shl(80, destReg))
// Insert source register (byte 22, shift left by 72 bits)
packed := or(packed, shl(72, srcReg))
// Insert value register (byte 23, shift left by 64 bits)
packed := or(packed, shl(64, valueReg))
}
}
/**
* @notice Packs a CALLDATA_BUILD command into a single 32-byte word.
* @dev Format:
* Bytes 0–3: Function selector (bytes4)
* Byte 4: Destination register (uint8) with dynamic flag in high bit
* Byte 5: Blueprint length (uint8)
* Bytes 6–27: Blueprint (up to 22 bytes)
* Bytes 28-31: Padding (must be zero)
* @param selector The 4-byte function selector.
* @param destReg The destination register (with dynamic flag in high bit).
* @param blueprint The blueprint defining the structure of the calldata.
* @return packed The packed 32-byte command.
*/
function packCallDataBuild(
bytes4 selector,
uint8 destReg,
bytes memory blueprint
)
internal
pure
returns (bytes32 packed)
{
if (blueprint.length > VmConstants.MAX_CDB_BP) {
revert VmErrors.BlueprintTooLarge();
}
// Pack function selector into bytes 0-3.
packed = bytes32(uint256(uint32(selector))) << 224;
// Pack destination register into byte 4.
packed |= bytes32(uint256(destReg)) << 216;
// Pack blueprint length into byte 5.
packed |= bytes32(uint256(blueprint.length)) << 208;
// Pack each blueprint byte into subsequent bytes starting at byte 6.
for (uint256 i = 0; i < blueprint.length;) {
// Each blueprint byte occupies one byte at position (6 + i).
// Shift left by (32 - (6 + i + 1)) * 8 = (25 - i) * 8 bits.
unchecked {
packed |= bytes32(uint256(uint8(blueprint[i]))) << ((25 - i) * 8);
++i;
}
}
}
/**
* @notice Unpacks a CALL command from a 32-byte word.
* @dev Expects format:
* Byte 0: Call type (uint8) - variant/sub-opcode for consistency with LOG
* Bytes 1–20: Target address (20 bytes)
* Byte 21: Destination register (uint8) with dynamic flag in high bit.
* Byte 22: Source register (uint8) with dynamic flag in high bit.
* Byte 23: Value register (uint8) with dynamic flag in high bit.
* Bytes 24–31: Padding (ignored)
* @param packed The packed 32-byte command.
* @return callCmd A Call struct with the unpacked fields.
*/
function unpackCall(bytes32 packed) internal pure returns (Call memory callCmd) {
// Extract call type from byte 0.
callCmd.callType = uint8(uint256(packed >> 248));
// Extract target address from bytes 1-20.
callCmd.target = address(uint160(uint256(packed >> 88)));
// Extract destination register from byte 21.
callCmd.destReg = uint8(uint256(packed >> 80));
// Extract source register from byte 22.
callCmd.srcReg = uint8(uint256(packed >> 72));
// Extract value register from byte 23.
callCmd.valueReg = uint8(uint256(packed >> 64));
}
/**
* @notice Unpacks a CALLDATA_BUILD command from a 32-byte word.
* @dev Expects format:
* Bytes 0–3: Function selector (bytes4)
* Byte 4: Destination register (uint8) with dynamic flag in high bit
* Byte 5: Blueprint length (uint8)
* Bytes 6–27: Blueprint (up to 22 bytes)
* Bytes 28-31: Padding (ignored)
* @param packed The packed 32-byte command.
* @return cdb A CallDataBuild struct with the unpacked fields.
*/
function unpackCallDataBuild(bytes32 packed) internal pure returns (CallDataBuild memory cdb) {
// Extract function selector from bytes 0-3.
cdb.selector = bytes4(uint32(uint256(packed >> 224)));
// Extract destination register from byte 4.
cdb.destReg = uint8(uint256(packed >> 216));
// Extract blueprint length from byte 5.
uint8 blueprintLength = uint8(uint256(packed >> 208));
// Validate blueprint length to prevent resource exhaustion
if (blueprintLength > VmConstants.MAX_CDB_BP) {
revert VmErrors.BlueprintTooLarge();
}
// Create the blueprint bytes array.
cdb.blueprint = new bytes(blueprintLength);
for (uint256 i = 0; i < blueprintLength;) {
unchecked {
cdb.blueprint[i] = bytes1(uint8(uint256(packed >> ((25 - i) * 8))));
++i;
}
}
}
/**
* @notice Packs an EXPLODE command into a single 32-byte word.
* @dev Canonical format (every reserved bit MUST be zero so pack/unpack stay symmetric):
* Byte 0: Source register index (low 7 bits). The high bit (0x80) is reserved and
* must be zero – it is a dead flag that no read path consumes.
* Byte 1: Destination register count (uint8) – number of destination registers (1–26).
* Bytes 2–27: Destination registers (up to 26 one-byte values).
* Each destination uses its high bit as a dynamic flag (0x80); the low 7 bits
* specify the index. Bytes beyond the last used destination must be zero.
* Bytes 28–31: Padding – reserved, must be zero.
* @param sourceReg The source register index (high bit must be clear).
* @param destCount The number of destination registers.
* @param destRegs An array of destination registers (max 26).
* @return packed The packed 32-byte command.
*/
function packExplode(
uint8 sourceReg,
uint8 destCount,
uint8[] memory destRegs
)
internal
pure
returns (bytes32 packed)
{
if (destCount == 0 || destCount > MAX_EXPLODE_DESTS) {
revert VmErrors.DestinationCountOutOfBounds(destCount);
}
if (destRegs.length < uint256(destCount)) {
revert VmErrors.DestinationCountMismatch(destCount, destRegs.length);
}
// Why this invariant: byte 0's high bit is a reserved bit that `unpackExplode` rejects (see
// the note there). If `packExplode` accepted a flagged `sourceReg` and emitted it, the two
// functions would stop being inverses — the packer would mint words its own unpacker
// refuses, so `unpackExplode(packExplode(x)) == x` (Halmos property E-1) would be false for
// half the `sourceReg` domain, and the only place the mistake would surface is an on-chain
// revert. Rejecting here makes `packExplode` total over exactly the inputs `unpackExplode`
// accepts, which is what lets the roundtrip be stated as an unconditional property.
if (sourceReg & VmConstants.DYN_MASK != 0) revert VmErrors.NonZeroPadding();
assembly {
// Insert sourceReg into byte 0 (shift left by 248 bits).
packed := shl(248, sourceReg)
// Insert destCount into byte 1 (shift left by 240 bits).
packed := or(packed, shl(240, destCount))
// Insert each destination register into bytes 2-27.
// For dynamic arrays, the pointer 'destRegs' points to the length slot.
// So the first element is at offset 0x20.
for { let i := 0 } lt(i, destCount) { i := add(i, 1) } {
let elementPtr := add(add(destRegs, 0x20), mul(i, 0x20))
let regVal := and(mload(elementPtr), 0xFF)
let shiftAmount := sub(EXPLODE_DESTS_SHIFT_BASE, mul(i, 8))
packed := or(packed, shl(shiftAmount, regVal))
}
}
}
/**
* @notice Unpacks an EXPLODE command from a 32-byte word.
* @dev Enforces the canonical encoding; any word with a reserved bit set is rejected as
* malleable (`NonZeroPadding`):
* Byte 0: Source register index (low 7 bits). The high bit (0x80) is reserved and must
* be zero – it is a dead flag with no read path.
* Byte 1: Destination register count (uint8), validated to 1–26.
* Bytes 2..(1+destCount): destination registers (each may carry its own 0x80 dynamic flag).
* Bytes (2+destCount)..31: reserved – all bits below the last used destination byte (the
* unused destination bytes plus the 28–31 padding) must be zero.
* @param packed The packed 32-byte command.
* @return explodeCmd An Explode struct with the unpacked fields.
*/
function unpackExplode(bytes32 packed) internal pure returns (Explode memory explodeCmd) {
// Extract sourceReg from byte 0.
uint8 sourceReg = uint8(uint256(packed >> 248));
// Extract destCount from byte 1.
uint8 destCount = uint8(uint256(packed >> 240));
if (destCount == 0 || destCount > MAX_EXPLODE_DESTS) {
revert VmErrors.DestinationCountOutOfBounds(destCount);
}
// "Malleable" here means: two distinct 32-byte words that decode to the same `Explode` struct
// and therefore execute identically. Byte 0's high bit is the clearest instance —
// `ExplodeLib.execute` reads the source through `.idx()`, which masks bit 0x80 off, so
// `0x80 | reg` and `reg` are the same program. Accepting both would make the packed word a
// non-canonical encoding of the command: the on-the-wire form would no longer be the
// command's identity, so equality, hashing, caching or golden-artifact comparison over
// command words (compiler snapshot tests, off-chain simulation replay, blueprint dedup)
// would silently compare representations instead of behaviour.
if (uint256(packed >> 248) & VmConstants.DYN_MASK != 0) revert VmErrors.NonZeroPadding();
// Correctness concern or hygiene? Hygiene, deliberately. `ExplodeLib.execute` reads exactly
// `destCount` destination bytes and never touches the region below them, so no bit pattern
// rejected here could have changed execution — this check turns no exploitable input into a
// revert. What it buys is (a) the canonical encoding described above, and (b) a reserved
// region that is provably unused on-chain, so a later version can give bytes 28-31 or the
// trailing destination slots a meaning without having to honour already-accepted nonzero
// words. EXPLODE is the only command that pays for this; `docs/isa.md` ("Padding and
// Reserved-Bit Policy") records the asymmetry so the inconsistency is not read as a bug.
//
// Mechanics: destination i is read as `uint8(packedDests >> (EXPLODE_DESTS_SHIFT_BASE - i*8))`,
// so the final destination (i = destCount - 1) occupies the byte whose low bit sits at
// `lastDestShift`. Everything strictly below that bit — the unused destination bytes
// [2+destCount .. 27] plus the 28-31 padding — is the reserved region. At destCount = 26 it
// collapses to exactly the 4 padding bytes (lastDestShift = 32).
uint256 lastDestShift = EXPLODE_DESTS_SHIFT_BASE - (uint256(destCount) - 1) * 8;
if (uint256(packed) & ((uint256(1) << lastDestShift) - 1) != 0) {
revert VmErrors.NonZeroPadding();
}
explodeCmd.sourceReg = sourceReg;
explodeCmd.destCount = destCount;
// Carry the entire packed word; consumers extract each destination register inline via
// `uint8(packedDests >> (EXPLODE_DESTS_SHIFT_BASE - i * 8))`. The reserved-bit checks above
// guarantee every bit below the last destination byte (unused dests + padding) is zero.
explodeCmd.packedDests = uint256(packed);
}
/**
* @notice Packs a DEPOSIT_APPROVED command into a single 32-byte word.
* @dev Format:
* Bytes 0-19: ERC20 token address (20 bytes)
* Byte 20: Destination register index (uint8)
* Byte 21: Max deposit register index (uint8)
* Bytes 22-31: Unused (must be zero)
* @param deposit The DepositApproved struct containing the token address, destination register, and max deposit register.
* @return packed The packed 32-byte word.
*/
function packDepositApproved(DepositApproved memory deposit) internal pure returns (bytes32 packed) {
assembly {
// Load the token (an address is stored right-aligned in a 32-byte word)
let token := and(mload(deposit), 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff)
// Shift the token left by 96 bits to place it in bytes 0-19.
packed := shl(96, token)
// Load the destination register (stored as a uint8 in the next 32 bytes).
let reg := and(mload(add(deposit, 32)), 0xFF)
// Shift the destination register left by 88 bits to place it in byte 20.
packed := or(packed, shl(88, reg))
// Load the max deposit register (stored as a uint8 in the next 32 bytes).
let maxDepositReg := and(mload(add(deposit, 64)), 0xFF)
// Shift the max deposit register left by 80 bits to place it in byte 21.
packed := or(packed, shl(80, maxDepositReg))
}
}
/**
* @notice Unpacks a DEPOSIT_APPROVED command from a 32-byte word.
* @dev Expects format:
* Bytes 0-19: ERC20 token address (20 bytes)
* Byte 20: Destination register index (uint8)
* Byte 21: Max deposit register index (uint8)
* Bytes 22-31: Unused (ignored)
* @param packed The packed 32-byte word.
* @return deposit The unpacked DepositApproved struct.
*/
function unpackDepositApproved(bytes32 packed) internal pure returns (DepositApproved memory deposit) {
assembly {
// Allocate memory for the struct (3 fields now).
deposit := mload(0x40)
mstore(0x40, add(deposit, 96))
// Extract token: shift right by 96 bits.
let token := shr(96, packed)
// Ensure we only keep the lower 20 bytes.
token := and(token, 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff)
mstore(deposit, token)
// Extract the destination register:
// Shift right by 88 bits. Note that packed = (token << 96) OR (reg << 88),
// so shifting right by 88 gives: (token << 8) OR reg.
// Because (token << 8) is divisible by 256, its lowest 8 bits are zero.
let reg := and(shr(88, packed), 0xFF)
mstore(add(deposit, 32), reg)
// Extract the max deposit register:
// Shift right by 80 bits to get the value in byte 21.
let maxDepositReg := and(shr(80, packed), 0xFF)
mstore(add(deposit, 64), maxDepositReg)
}
}
/**
* @notice Packs a CALLDATA_SURGERY command into a single 32-byte word.
* @dev Format:
* Byte 0: Source register (uint8)
* Byte 1: Surgery count (uint8) - Number of surgeries to perform (1-6, must not be 0)
* Bytes 2-25: Surgery descriptors (up to 6 × 4 bytes)
* For each surgery descriptor:
* - 2 bytes: offset (uint16, big-endian)
* - 1 byte: length (uint8)
* - 1 byte: replacementReg (uint8)
* Bytes 26-31: Padding (must be zero)
* @param surgery The CallDataSurgery struct to pack.
* @return packed The packed 32-byte command.
*/
function packCallDataSurgery(CallDataSurgery memory surgery) internal pure returns (bytes32 packed) {
if (surgery.surgeryCount > 6) {
revert VmErrors.TooManySurgeries();
}
// Pack source register into byte 0
packed = bytes32(uint256(surgery.sourceReg)) << 248;
// Pack surgery count into byte 1
packed |= bytes32(uint256(surgery.surgeryCount)) << 240;
// Pack each surgery descriptor - each takes 4 bytes starting at byte 2
for (uint256 i = 0; i < surgery.surgeryCount;) {
unchecked {
// Calculate byte position for this descriptor
uint256 bytePos = 2 + (i * 4);
uint256 bitPos = 248 - (bytePos * 8);
// Pack offset high byte (first byte of the u16)
packed |= bytes32(uint256(surgery.surgeries[i].offset >> 8) & 0xFF) << bitPos;
// Pack offset low byte (second byte of the u16)
packed |= bytes32(uint256(surgery.surgeries[i].offset & 0xFF)) << (bitPos - 8);
// Pack length (1 byte)
packed |= bytes32(uint256(surgery.surgeries[i].length)) << (bitPos - 16);
// Pack replacement register (1 byte)
packed |= bytes32(uint256(surgery.surgeries[i].replacementReg)) << (bitPos - 24);
++i;
}
}
return packed;
}
/**
* @notice Unpacks a CALLDATA_SURGERY command from a 32-byte word.
* @dev Expects format:
* Byte 0: Source register (uint8)
* Byte 1: Surgery count (uint8)
* Bytes 2-25: Surgery descriptors (up to 6 × 4 bytes)
* Bytes 26-31: Padding (ignored)
* @param packed The packed 32-byte command.
* @return surgery The unpacked CallDataSurgery struct.
*/
function unpackCallDataSurgery(bytes32 packed) internal pure returns (CallDataSurgery memory surgery) {
// Extract source register from byte 0
surgery.sourceReg = uint8(uint256(packed >> 248));
// Extract surgery count from byte 1
surgery.surgeryCount = uint8(uint256(packed >> 240));
if (surgery.surgeryCount > 6) {
revert VmErrors.TooManySurgeries();
}
// Extract each surgery descriptor - each takes 4 bytes starting at byte 2
for (uint256 i = 0; i < surgery.surgeryCount;) {
unchecked {
// Calculate byte position for this descriptor (each takes 4 bytes)
uint256 bytePos = 2 + (i * 4);
uint256 bitPos = 248 - (bytePos * 8);
// Extract offset (2 bytes = 16 bits)
// First byte is high byte (>> 8), second byte is low byte
uint16 highByte = uint16(uint256(packed >> (bitPos)) & 0xFF);
uint16 lowByte = uint16(uint256(packed >> (bitPos - 8)) & 0xFF);
surgery.surgeries[i].offset = (highByte << 8) | lowByte;
// Extract length (1 byte = 8 bits) from the 3rd byte of descriptor
surgery.surgeries[i].length = uint8(uint256(packed >> (bitPos - 16)));
// Extract replacement register (1 byte = 8 bits) from the 4th byte of descriptor
surgery.surgeries[i].replacementReg = uint8(uint256(packed >> (bitPos - 24)));
++i;
}
}
// Initialize any unused descriptors to zero
for (uint256 i = surgery.surgeryCount; i < 6;) {
surgery.surgeries[i].offset = 0;
surgery.surgeries[i].length = 0;
surgery.surgeries[i].replacementReg = 0;
unchecked {
++i;
}
}
return surgery;
}
/**
* @notice Packs a RETURN command into a single 32-byte word.
* @dev Format:
* Byte 0: Source register (uint8) containing the data to be returned.
* Bytes 1-31: Unused (must be zero)
* @param sourceReg The source register containing the data to be returned.
* @return packed The packed 32-byte command.
*/
function packReturn(uint8 sourceReg) internal pure returns (bytes32 packed) {
assembly {
// Insert sourceReg into byte 0 (shift left by 248 bits).
packed := shl(248, sourceReg)
}
}
/**
* @notice Unpacks a RETURN command from a 32-byte word.
* @dev Expects format:
* Byte 0: Source register (uint8) containing the data to be returned.
* Bytes 1-31: Unused (ignored)
* @param packed The packed 32-byte command.
* @return returnCmd A Return struct with the unpacked fields.
*/
function unpackReturn(bytes32 packed) internal pure returns (Return memory returnCmd) {
// Extract sourceReg from byte 0.
returnCmd.sourceReg = uint8(uint256(packed >> 248));
}
/**
* @notice Packs an ABI_ENCODE command into a single 32-byte word.
* @dev Format:
* Byte 0: Destination register (uint8) with dynamic flag in high bit.
* Byte 1: Blueprint length (uint8)
* Bytes 2-28: Blueprint (up to 27 bytes).
* Bytes 29-31: Padding (must be zero)
* @param destReg The destination register (with dynamic flag in high bit).
* @param blueprint The blueprint defining the structure of the data to encode.
* @return packed The packed 32-byte command.
*/
function packAbiEncode(uint8 destReg, bytes memory blueprint) internal pure returns (bytes32 packed) {
if (blueprint.length > VmConstants.MAX_ABI_BP) {
revert VmErrors.BlueprintTooLarge();
}
// Pack destination register into byte 0.
packed = bytes32(uint256(destReg)) << 248;
// Pack blueprint length into byte 1.
packed |= bytes32(uint256(blueprint.length)) << 240;
// Pack each blueprint byte into subsequent bytes starting at byte 2.
for (uint256 i = 0; i < blueprint.length;) {
// Each blueprint byte occupies one byte at position (2 + i).
// Shift left by (32 - (2 + i + 1)) * 8 = (29 - i) * 8 bits.
unchecked {
packed |= bytes32(uint256(uint8(blueprint[i]))) << ((29 - i) * 8);
++i;
}
}
}
/**
* @notice Unpacks an ABI_ENCODE command from a 32-byte word.
* @dev Expects format:
* Byte 0: Destination register (uint8) with dynamic flag in high bit.
* Byte 1: Blueprint length (uint8)
* Bytes 2-28: Blueprint (up to 27 bytes).
* Bytes 29-31: Padding (ignored)
* @param packed The packed 32-byte command.
* @return abiEncode An AbiEncode struct with the unpacked fields.
*/
function unpackAbiEncode(bytes32 packed) internal pure returns (AbiEncode memory abiEncode) {
// Extract destination register from byte 0.
abiEncode.destReg = uint8(uint256(packed >> 248));
// Extract blueprint length from byte 1.
uint8 blueprintLength = uint8(uint256(packed >> 240));
// Revert if blueprint length exceeds maximum
if (blueprintLength > 27) {
revert VmErrors.BlueprintTooLarge();
}
// Create the blueprint bytes array.
abiEncode.blueprint = new bytes(blueprintLength);
for (uint256 i = 0; i < blueprintLength;) {
unchecked {
abiEncode.blueprint[i] = bytes1(uint8(uint256(packed >> ((29 - i) * 8))));
++i;
}
}
}
/**
* @notice Packs a REMAINING_GAS command into a single 32-byte word.
* @dev Format:
* Byte 0: Destination register (uint8) with dynamic flag in high bit.
* Bytes 1-31: Unused (must be zero)
* @param destReg The destination register (with dynamic flag in high bit).
* @return packed The packed 32-byte command.
*/
function packRemainingGas(uint8 destReg) internal pure returns (bytes32 packed) {
assembly {
// Insert destReg into byte 0 (shift left by 248 bits).
packed := shl(248, destReg)
}
}
/**
* @notice Unpacks a REMAINING_GAS command from a 32-byte word.
* @dev Expects format:
* Byte 0: Destination register (uint8) with dynamic flag in high bit.
* Bytes 1-31: Unused (ignored)
* @param packed The packed 32-byte command.
* @return remainingGas A RemainingGas struct with the unpacked fields.
*/
function unpackRemainingGas(bytes32 packed) internal pure returns (RemainingGas memory remainingGas) {
// Extract destination register from byte 0.
remainingGas.destReg = uint8(uint256(packed >> 248));
}
/**
* @notice Packs a NATIVE_BALANCE command into a single 32-byte word.
* @dev Format:
* Byte 0: Address register (uint8) containing the address to get balance of
* Byte 1: Destination register (uint8) with dynamic flag in high bit.
* Bytes 2-31: Unused (must be zero)
* @param addrReg Register containing the target address to retrieve native balance of.
* @param destReg The destination register (with dynamic flag in high bit).
* @return packed The packed 32-byte command.
*/
function packNativeBalance(uint8 addrReg, uint8 destReg) internal pure returns (bytes32 packed) {
assembly {
// Insert addrReg into byte 0 (shift left by 248 bits).
packed := shl(248, addrReg)
// Insert destReg into byte 1 (shift left by 240 bits).
packed := or(packed, shl(240, destReg))
}
}
/**
* @notice Unpacks a NATIVE_BALANCE command from a 32-byte word.
* @dev Expects format:
* Byte 0: Address register (uint8) containing the address to get balance of
* Byte 1: Destination register (uint8) with dynamic flag in high bit.
* Bytes 2-31: Unused (ignored)
* @param packed The packed 32-byte command.
* @return nativeBalance A NativeBalance struct with the unpacked fields.
*/
function unpackNativeBalance(bytes32 packed) internal pure returns (NativeBalance memory nativeBalance) {
// Extract address register from byte 0 (shift right by 248 bits)
nativeBalance.addrReg = uint8(uint256(packed >> 248));
// Extract destination register from byte 1 (shift right by 240 bits and mask)
nativeBalance.destReg = uint8(uint256(packed >> 240));
}
/**
* @notice Packs a LOG command into a single 32-byte word.
* @dev Format:
* Byte 0: Log variant (uint8) - specifies which type of log to emit (0-5).
* Bytes 1-26: Source registers packed as uint208 - contains up to 26 register indices.
* For STATIC_1 (variant=0): only byte 1 is used (1 register).
* For STATIC_2 (variant=1): only bytes 1-2 are used (2 registers).
* For STATIC_3 (variant=2): only bytes 1-3 are used (3 registers).
* For STATIC_4 (variant=3): only bytes 1-4 are used (4 registers).
* For STATIC_5 (variant=4): only bytes 1-5 are used (5 registers).
* For DYNAMIC (variant=5): only byte 1 is used (points to dynamic array).
* Each byte represents a register with high bit as dynamic flag (0x80) and low 7 bits as index.
* Unused bytes must be zero.
* Bytes 27-31: Padding (must be zero)
* @param variant The log variant (0: STATIC_1, 1: STATIC_2, ..., 5: DYNAMIC).
* @param sourceRegs The packed register indices (only low 208 bits used).
* @return packed The packed 32-byte command.
*/
function packLog(uint8 variant, uint256 sourceRegs) internal pure returns (bytes32 packed) {
if (variant > uint8(LogVariant.DYNAMIC)) {
revert VmErrors.InvalidLogVariant();
}
if (sourceRegs > type(uint208).max) {
revert VmErrors.SourceRegistersExceed208Bits();
}
assembly {
// Pack variant into byte 0 (shift left by 248 bits)
packed := shl(248, variant)
// Pack sourceRegs into bytes 1-26 (shift left by 40 bits to align with bytes 1-26)
packed := or(packed, shl(40, sourceRegs))
}
}
/**
* @notice Unpacks a LOG command from a 32-byte word.
* @dev Expects format:
* Byte 0: Log variant (uint8)
* Bytes 1-26: Source registers packed as uint208
* Bytes 27-31: Padding (ignored)
* @param packed The packed 32-byte command.
* @return log A Log struct with the unpacked fields.
*/
function unpackLog(bytes32 packed) internal pure returns (Log memory log) {
// Extract variant from byte 0
log.variant = uint8(uint256(packed >> 248));
// Extract sourceRegs from bytes 1-26 (shift right by 40 bits and mask to 208 bits)
log.sourceRegs = uint256((uint256(packed >> 40) & ((1 << 208) - 1)));
}
/**
* @notice Packs a SAFE_TRANSFER command into a single 32-byte word.
* @dev Format:
* Bytes 0-19: Token address (20 bytes)
* Byte 20: To register (uint8)
* Byte 21: Amount register (uint8)
* Bytes 22-31: Padding (10 bytes, available for future use)
* @param token The ERC20 token contract address.
* @param toReg The register containing recipient address.
* @param amountReg The register containing transfer amount.
* @return packed The packed 32-byte command.
*/
function packSafeTransfer(address token, uint8 toReg, uint8 amountReg) internal pure returns (bytes32 packed) {
assembly {
// Insert token address (bytes 0-19, shift left by 96 bits)
packed := shl(96, token)
// Insert toReg (byte 20, shift left by 88 bits)
packed := or(packed, shl(88, toReg))
// Insert amountReg (byte 21, shift left by 80 bits)
packed := or(packed, shl(80, amountReg))
}
}
/**
* @notice Unpacks a SAFE_TRANSFER command from a 32-byte word.
* @dev Expects format:
* Bytes 0-19: Token address (20 bytes)
* Byte 20: To register (uint8)
* Byte 21: Amount register (uint8)
* Bytes 22-31: Padding (ignored)
* @param packed The packed 32-byte command.
* @return safeTransfer A SafeTransfer struct with the unpacked fields.
*/
function unpackSafeTransfer(bytes32 packed) internal pure returns (SafeTransfer memory safeTransfer) {
// Extract token address from bytes 0-19
safeTransfer.token = address(uint160(uint256(packed >> 96)));
// Extract toReg from byte 20
safeTransfer.toReg = uint8(uint256(packed >> 88));
// Extract amountReg from byte 21
safeTransfer.amountReg = uint8(uint256(packed >> 80));
}
}
src/DataModel.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;
/// @notice The register file that holds all registers used by the VM.
struct VMState {
bytes[] registers;
}
/// @notice Enum representing the different call types supported.
enum CallType {
DELEGATECALL,
CALL,
STATICCALL,
VALUECALL
}
/// @notice Enum representing the VM command operations.
enum OP {
CALL, // External call using pre-built calldata.
CALLDATA_BUILD, // Build calldata from registers.
EXPLODE, // Splits an ABI-encoded tuple into multiple registers.
DEPOSIT_APPROVED, // Deposits ERC20 tokens from an address that previously approved tokens.
CALLDATA_SURGERY, // Performs replace-by-offset operations on a given calldata.
RETURN, // Halts execution and returns the contents of a register.
ABI_ENCODE, // Encodes data into ABI format from a blueprint.
REMAINING_GAS, // Stores the current remaining gas in a register.
NATIVE_BALANCE, // Gets the native token balance for an address and stores it in a register.
LOG, // Emits a VMLog event with opcode and data from a register.
SAFE_TRANSFER // Safely transfers ERC20 tokens using Solady's SafeTransferLib.
}
/// @notice A CALL command structure.
/// @dev For the packed bytes32 layout, see CommandPacking.packCall/unpackCall
struct Call {
address target;
uint8 callType;
uint8 destReg; // High bit (0x80) indicates dynamic; lower 7 bits are the register index.
uint8 srcReg; // High bit (0x80) indicates dynamic; lower 7 bits are the register index.
uint8 valueReg; // High bit (0x80) indicates dynamic; lower 7 bits are the register index.
}
/// @notice A CALLDATA_BUILD command structure.
/// @dev For the packed bytes32 layout, see CommandPacking.packCallDataBuild/unpackCallDataBuild
struct CallDataBuild {
bytes4 selector;
uint8 destReg; // High bit = dynamic flag; low 7 bits = register index.
bytes blueprint; // Blueprint defining the structure of the calldata (max 22 bytes)
}
/// @notice An EXPLODE command structure.
/// @dev For the packed bytes32 layout, see CommandPacking.packExplode/unpackExplode.
/// `packedDests` carries the entire original command word; the i-th destination
/// register is extracted as `uint8(packedDests >> (CommandPacking.EXPLODE_DESTS_SHIFT_BASE - i * 8))`.
/// Bytes 0-1 hold `sourceReg`/`destCount`. unpackExplode validates that every reserved bit is
/// zero — the `sourceReg` high bit, the unused destination bytes below `2+destCount`, and the
/// 28-31 padding — so the surrounding bits never collide with destination-byte extraction.
struct Explode {
uint8 sourceReg; // Lower 7 bits are the register index; the high bit is a reserved dead flag and
// must be zero (rejected by CommandPacking.unpackExplode/packExplode — no read path consumes it).
uint8 destCount;
uint256 packedDests; // Raw command word with up to 26 dest regs at bytes 2..27.
}
/// @notice A DEPOSIT_APPROVED command structure.
/// @dev For the packed bytes32 layout, see CommandPacking.packDepositApproved/unpackDepositApproved
struct DepositApproved {
address token;
uint8 destReg;
uint8 maxDepositReg;
}
/// @notice A VM command structure.
/// @dev Each command type has its own packing format within the 32 bytes.
struct VMCommand {
OP op;
bytes32 data;
}
/**
* @dev A surgery descriptor describing how to replace a portion of calldata.
* @param offset The byte offset in the source data at which to perform the replacement.
* @param length The number of bytes to replace.
* @param replacementReg The register index containing the replacement bytes.
*/
struct SurgeryDescriptor {
uint16 offset;
uint8 length;
uint8 replacementReg;
}
/**
* @dev The CALLDATA_SURGERY command structure.
* @notice For the packed bytes32 layout, see CommandPacking.packCallDataSurgery/unpackCallDataSurgery
* @param sourceReg The register index containing the template calldata.
* @param surgeryCount The number of surgery operations to perform (1–6).
* @param surgeries A fixed-size array (length 6) of surgery descriptors;
* only the first `surgeryCount` are used.
*/
struct CallDataSurgery {
uint8 sourceReg;
uint8 surgeryCount;
SurgeryDescriptor[6] surgeries;
}
/// @notice A RETURN command structure.
/// @dev For the packed bytes32 layout, see CommandPacking.packReturn/unpackReturn
struct Return {
uint8 sourceReg;
}
/// @notice An ABI_ENCODE command structure.
/// @dev For the packed bytes32 layout, see CommandPacking.packAbiEncode/unpackAbiEncode
struct AbiEncode {
uint8 destReg; // High bit = dynamic flag; low 7 bits = register index.
bytes blueprint; // Blueprint defining the structure of the data to encode (max 27 bytes)
}
/// @notice A REMAINING_GAS command structure.
/// @dev For the packed bytes32 layout, see CommandPacking.packRemainingGas/unpackRemainingGas
struct RemainingGas {
uint8 destReg; // High bit = dynamic flag; low 7 bits = register index.
}
/// @notice A NATIVE_BALANCE command structure.
/// @dev For the packed bytes32 layout, see CommandPacking.packNativeBalance/unpackNativeBalance
struct NativeBalance {
uint8 addrReg; // Register containing the address
uint8 destReg; // High bit = dynamic flag; low 7 bits = register index.
}
/// @notice Enum representing the different log variants supported.
enum LogVariant {
STATIC_1, // Log 1 static register (32 bytes)
STATIC_2, // Log 2 static registers (64 bytes)
STATIC_3, // Log 3 static registers (96 bytes)
STATIC_4, // Log 4 static registers (128 bytes)
STATIC_5, // Log 5 static registers (160 bytes)
DYNAMIC // Log dynamic data from a register
}
/// @notice A LOG command structure.
/// @dev For the packed bytes32 layout, see CommandPacking.packLog/unpackLog
struct Log {
uint8 variant; // LogVariant enum value
uint256 sourceRegs; // Packed register indices (only low 208 bits used)
}
/// @notice A SAFE_TRANSFER command structure.
/// @dev For the packed bytes32 layout, see CommandPacking.packSafeTransfer/unpackSafeTransfer
struct SafeTransfer {
address token; // ERC20 token address (20 bytes)
uint8 toReg; // Register containing recipient address
uint8 amountReg; // Register containing transfer amount
}
src/DepositApproved.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;
import './DataModel.sol';
import './RegisterFile.sol';
import './interfaces/IERC20.sol';
import './VmErrors.sol';
import './VmConstants.sol';
import { StorageSlots } from './StorageSlots.sol';
import { SafeTransferLib } from 'solady/utils/SafeTransferLib.sol';
/// @title DepositApproved Library
/// @custom:version 1.0.0
/// @notice Library for handling the DEPOSIT_APPROVED operation in the virtual machine
library DepositApprovedLib {
using SafeTransferLib for address;
/// @dev Storage slot for the owner address, shared with MinimalProxy.
uint256 private constant _OWNER_SLOT = StorageSlots.OWNER_SLOT;
/// @notice Executes the deposit approved operation, which deposits ERC20 tokens from the proxy owner
/// @param depositCmd The DEPOSIT_APPROVED command parameters
/// @param maxDeposit The maximum amount that can be deposited
function depositApproved(DepositApproved memory depositCmd, uint256 maxDeposit) internal returns (uint256) {
address token = depositCmd.token;
uint256 approvedAmount;
uint256 userBalance;
uint256 amount;
uint256 pre;
uint256 post;
address tokenOwner;
uint256 ownerSlot = _OWNER_SLOT;
assembly {
// Load the owner from the dedicated storage slot.
// Falls back to caller() when not in proxy context (slot is zero).
tokenOwner := sload(ownerSlot)
if iszero(tokenOwner) { tokenOwner := caller() }
// Check if token contract exists
if iszero(extcodesize(token)) {
// revert CallToNonContract()
mstore(0, 0xba18390000000000000000000000000000000000000000000000000000000000)
revert(0, 4)
}
// Reserve ABI buffer [ptr .. ptr+0x7f]
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x80))
// Prepare allowance call: allowance(owner, address(this))
mstore(ptr, 0xdd62ed3e00000000000000000000000000000000000000000000000000000000)
mstore(add(ptr, 0x04), tokenOwner)
mstore(add(ptr, 0x24), address())
let ok := staticcall(gas(), token, ptr, 0x44, ptr, 0x20)
if and(ok, eq(returndatasize(), 0x20)) { approvedAmount := mload(ptr) }
// Prepare balanceOf call: balanceOf(owner)
mstore(ptr, 0x70a0823100000000000000000000000000000000000000000000000000000000)
mstore(add(ptr, 0x04), tokenOwner)
ok := staticcall(gas(), token, ptr, 0x24, ptr, 0x20)
if and(ok, eq(returndatasize(), 0x20)) { userBalance := mload(ptr) }
// Transfer the minimum of approved amount and user balance
amount := approvedAmount
if gt(amount, userBalance) { amount := userBalance }
// Apply maxDeposit limit
if gt(amount, maxDeposit) { amount := maxDeposit }
// FOT support: get current balance
mstore(ptr, 0x70a0823100000000000000000000000000000000000000000000000000000000)
mstore(add(ptr, 0x04), address())
ok := staticcall(gas(), token, ptr, 0x24, ptr, 0x20)
ok := and(ok, eq(returndatasize(), 0x20))
if ok { pre := mload(ptr) }
if iszero(ok) {
// revert GetBalanceFailed()
mstore(0, 0xda20f3fb00000000000000000000000000000000000000000000000000000000)
revert(0, 4)
}
}
if (amount == 0) return 0;
// Handles non-standard ERC20s.
token.safeTransferFrom(tokenOwner, address(this), amount);
assembly {
// Reserve a fresh ABI buffer [ptr .. ptr+0x7f]
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x80))
// FOT support: measure actual received
mstore(ptr, 0x70a0823100000000000000000000000000000000000000000000000000000000)
mstore(add(ptr, 0x04), address())
let ok := staticcall(gas(), token, ptr, 0x24, ptr, 0x20)
if and(ok, eq(returndatasize(), 0x20)) { post := mload(ptr) }
}
return post - pre;
}
}
src/Explode.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;
import './DataModel.sol';
import './CommandPacking.sol';
import './MemoryUtils.sol';
import './RegisterFile.sol';
import './RegisterHelpers.sol';
import './VmErrors.sol';
import './VmConstants.sol';
/// @title Explode Library
/// @custom:version 1.0.0
/// @notice Library for handling the EXPLODE operation in the virtual machine
library ExplodeLib {
using RegisterFile for bytes[];
using RegisterHelpers for uint8;
/// @notice Executes the EXPLODE opcode's logic.
/// @dev Splits an ABI tuple block into register-shaped ABI field blobs, one per destination.
/// The source is read once up front, so a destination may alias the source register.
/// @dev A dynamic slice runs from this destination's head offset to the next dynamic
/// destination's head offset (intervening static destinations do not terminate it), or to
/// the end of `source`. The length word the field carries at its own start is never
/// compared against that extent, so a callee-controlled source can yield a
/// non-canonical register. Deliberate, see docs/isa.md "Register Canonicality": do not
/// hash, sign, or byte-compare such a register's payload without re-validating it;
/// decode it instead.
/// @param registers The VM register array.
/// @param e The unpacked Explode command parameters.
function execute(bytes[] memory registers, Explode memory e) internal pure {
bytes memory source = registers.get(e.sourceReg.idx());
uint256 sourceLen = source.length;
if ((sourceLen & (VmConstants.WORD_SIZE - 1)) != 0) revert VmErrors.InvalidRegisterLength();
uint256 destCount = e.destCount;
uint256 packedDests = e.packedDests;
uint256 headLen = destCount * VmConstants.WORD_SIZE;
if (sourceLen < headLen) revert VmErrors.OutOfBounds();
for (uint256 i; i < destCount;) {
uint8 destReg = uint8(packedDests >> (CommandPacking.EXPLODE_DESTS_SHIFT_BASE - i * 8));
if (destReg.isDyn()) {
uint256 start = _readWord(source, i * VmConstants.WORD_SIZE);
_validateDynamicOffset(start, headLen, sourceLen);
uint256 end = _resolveDynamicEnd(source, packedDests, i, destCount, headLen, sourceLen);
// invariant: end > start (validated below) so slice length is positive.
if (end <= start) revert VmErrors.OutOfBounds();
registers.set(destReg.idx(), MemoryUtils.slice(source, start, end - start));
} else {
registers.set(
destReg.idx(), MemoryUtils.slice(source, i * VmConstants.WORD_SIZE, VmConstants.WORD_SIZE)
);
}
unchecked {
++i;
}
}
}
/// @dev Locates the next dynamic destination after `i`; its head word is the slice end
/// for destination `i`. If no later dynamic destination exists, the slice extends
/// to the end of `source`. The scan stops at the first dynamic destination it finds,
/// so successive scans never overlap: across one command the loop below runs at most
/// `destCount - 1` times in total (25 under `MAX_EXPLODE_DESTS`), not `O(destCount^2)`.
function _resolveDynamicEnd(
bytes memory source,
uint256 packedDests,
uint256 i,
uint256 destCount,
uint256 headLen,
uint256 sourceLen
)
private
pure
returns (uint256 end)
{
end = sourceLen;
for (uint256 j = i + 1; j < destCount;) {
if (uint8(packedDests >> (CommandPacking.EXPLODE_DESTS_SHIFT_BASE - j * 8)).isDyn()) {
end = _readWord(source, j * VmConstants.WORD_SIZE);
_validateDynamicOffset(end, headLen, sourceLen);
break;
}
unchecked {
++j;
}
}
}
function _readWord(bytes memory data, uint256 offset) private pure returns (uint256 word) {
assembly {
word := mload(add(add(data, 0x20), offset))
}
}
function _validateDynamicOffset(uint256 offset, uint256 headLen, uint256 sourceLen) private pure {
if (offset < headLen || offset >= sourceLen || (offset & (VmConstants.WORD_SIZE - 1)) != 0) {
revert VmErrors.OutOfBounds();
}
}
}
src/MemoryUtils.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;
import './VmErrors.sol';
/// @custom:version 1.1.1
library MemoryUtils {
function slice(bytes memory data, uint256 start, uint256 length) internal pure returns (bytes memory result) {
// Wrapped in `unchecked`: the first clause proves `start <= data.length`, so `data.length - start`
// cannot underflow. `start + length` is avoided because it would panic on overflow instead of
// reverting OutOfBounds.
unchecked {
if (start > data.length || length > data.length - start) revert VmErrors.OutOfBounds();
}
assembly {
result := mload(0x40) // Get free memory pointer
mstore(result, length) // Store length at start of result
let src := add(add(data, 32), start) // Calculate source offset
let dest := add(result, 32) // Destination starts at result + 32
// Copy 32 bytes at a time
{
// copy full 32-byte words
let end := add(dest, and(length, not(31)))
for { } lt(dest, end) {
dest := add(dest, 32)
src := add(src, 32)
} { mstore(dest, mload(src)) }
// copy remaining bytes (if any) with masking
let rem := and(length, 31)
if rem {
// keep only the top `rem` bytes from src; low bytes become zero
let lowMask := sub(shl(mul(8, sub(32, rem)), 1), 1)
mstore(dest, and(mload(src), not(lowMask)))
}
}
// Update free memory pointer
mstore(0x40, add(add(result, 32), and(add(length, 31), not(31)))) // Update free memory pointer
}
}
}
src/RegisterFile.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;
import './DataModel.sol';
import './VmConstants.sol';
/// @title Register file utilities for the VM
/// @custom:version 1.0.0
library RegisterFile {
/*//////////////////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////////////////*/
/// @dev ABI‑encoded `uint256(0)` for the void register.
bytes internal constant ZERO_VALUE = hex'0000000000000000000000000000000000000000000000000000000000000000';
/*//////////////////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when `index` ≥ `registers.length`.
error RegisterIndexOOB();
/// @notice Thrown when provided data is not a dynamic abi-encoded field.
error InvalidDynamicData();
/// @notice Thrown when provided data is not a static abi-encoded field (32 bytes).
error InvalidStaticData();
/*//////////////////////////////////////////////////////////////////////////
READS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Returns the raw data stored in a register.
/// @dev The void register always returns `ZERO_VALUE`.
function get(bytes[] memory registers, uint8 index) internal pure returns (bytes memory) {
if (index == VmConstants.VOID_REG) return ZERO_VALUE;
if (index >= registers.length) revert RegisterIndexOOB();
return registers[index];
}
/// @notice Returns the raw data stored in a register and checks its 32 bytes.
/// @dev The void register always returns `ZERO_VALUE`.
function getStatic(bytes[] memory registers, uint8 index) internal pure returns (bytes memory out) {
if (index == VmConstants.VOID_REG) return ZERO_VALUE;
if (index >= registers.length) revert RegisterIndexOOB();
uint256 len;
assembly {
// slot = registers.data + index * 32
let slot := add(add(registers, 0x20), shl(5, index))
out := mload(slot) // bytes pointer
len := mload(out) // bytes length
}
if (len != 32) revert InvalidStaticData();
}
/*//////////////////////////////////////////////////////////////////////////
WRITES
//////////////////////////////////////////////////////////////////////////*/
/// @notice Stores raw `data` into `register[index]`.
function set(bytes[] memory registers, uint8 index, bytes memory data) internal pure {
if (index == VmConstants.VOID_REG) return;
if (index >= registers.length) revert RegisterIndexOOB();
registers[index] = data;
}
/// @notice Stores `data` into `register[index]`, dropping the leading
/// 0x20 pointer word expected in ABI‑encoded structures. Re-tags the data as bytes by also
/// rewriting the data length as the raw-bytes length (bytes and strings are unchanged).
/// (e.g. `abi.encode(string)`).
/// @dev This function does not work for dynamic tuples and will generate garbage in that case.
function setDynamic(bytes[] memory registers, uint8 index, bytes memory data) internal pure {
if (index == VmConstants.VOID_REG) return;
if (index >= registers.length) revert RegisterIndexOOB();
// The `data` is expected to be a single dynamic field abi-encoded. It must thus contain an
// initial 32-byte `0x20` offset, followed by a 32-byte length descriptor.
if (data.length < 0x40) {
revert InvalidDynamicData();
}
uint256 abiOffset;
assembly {
abiOffset := mload(add(data, 0x20)) // Add 0x20 to point to the first 32-byte word
}
if (abiOffset != 0x20) {
revert InvalidDynamicData();
}
bytes memory view_;
// WARNING - This is an in-place modification (length correction)
// Any reference to data will ALSO be affected
assembly {
view_ := add(data, 0x20) // skip the ABI offset
mstore(view_, sub(mload(data), 0x20)) // correct byte length
}
registers[index] = view_;
}
/*//////////////////////////////////////////////////////////////////////////
INITIALISATION
//////////////////////////////////////////////////////////////////////////*/
/// @notice Allocates `numRegisters` empty registers.
/// @dev Zero‑initialised memory is already valid empty `bytes`, so we
/// simply return a new array—no per‑slot writes needed.
function initialize(uint256 numRegisters) internal pure returns (bytes[] memory) {
return new bytes[](numRegisters);
}
}
src/RegisterHelpers.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;
import './VmConstants.sol';
import './VmErrors.sol';
/// @title RegisterHelpers
/// @custom:version 1.0.0
/// @notice Helper functions for VM register manipulation, including index extraction, dynamic flag checking, and type conversions
library RegisterHelpers {
/// @dev Extract register index (lower 7 bits)
function idx(uint8 r) internal pure returns (uint8) {
return r & VmConstants.IDX_MASK;
}
/// @dev Check if register uses dynamic allocation (high bit set)
function isDyn(uint8 r) internal pure returns (bool) {
return (r & VmConstants.DYN_MASK) != 0;
}
/// @dev Encode uint256 as 32-byte array for register storage
function encUint(uint256 x) internal pure returns (bytes memory b) {
b = new bytes(32);
assembly {
mstore(add(b, 32), x)
}
}
/// @dev Extract address from bytes (expects abi.encode(address) format)
function asAddress(bytes memory b) internal pure returns (address a) {
if (b.length != 32) revert VmErrors.InvalidAddressBytes();
assembly {
a := and(mload(add(b, 32)), 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff)
}
}
}
src/SafeTransferLib.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;
import './DataModel.sol';
import './RegisterFile.sol';
import './RegisterHelpers.sol';
import './VmErrors.sol';
import { SafeTransferLib } from 'solady/utils/SafeTransferLib.sol';
/// @title SafeTransferLib
/// @custom:version 1.0.0
/// @notice Library for handling the SAFE_TRANSFER operation in the virtual machine
library SafeTransferVMLib {
using SafeTransferLib for address;
using RegisterFile for bytes[];
using RegisterHelpers for uint8;
using RegisterHelpers for bytes;
/// @notice Executes the SAFE_TRANSFER opcode's logic.
/// @param registers The VM register array.
/// @param cmd The unpacked SafeTransfer command parameters.
function execute(bytes[] memory registers, SafeTransfer memory cmd) internal {
// Get recipient address from register
bytes memory toRegData = registers.get(cmd.toReg.idx());
address to = toRegData.asAddress();
// Get amount from register
bytes memory amountRegData = registers.getStatic(cmd.amountReg.idx());
uint256 amount;
assembly {
amount := mload(add(amountRegData, 0x20))
}
// Execute transfer - will revert on failure
cmd.token.safeTransfer(to, amount);
}
}
src/StorageSlots.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;
/// @title StorageSlots
/// @notice Shared storage-slot constants used by MinimalProxy and VM libraries.
library StorageSlots {
/// @dev Storage slot for the proxy owner address.
uint256 internal constant OWNER_SLOT = uint256(keccak256('lifi.minimal-proxy.owner'));
}
src/SurgeryOPS.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;
import './DataModel.sol';
import './VmErrors.sol';
import './RegisterHelpers.sol';
import './RegisterFile.sol';
/// @title SurgeryOps
/// @custom:version 1.0.0
/// @notice Library for performing byte-level surgery operations on calldata
library SurgeryOps {
using RegisterHelpers for uint8;
using RegisterFile for bytes[];
/// @notice Performs surgery operations on calldata, replacing specific byte ranges with new content in place
/// @param registers The register array containing register data (in-memory)
/// @param sourceReg Register index containing the template calldata (which will be modified in place)
/// @param surgeries Array of surgery descriptors defining the replacements to perform
/// @param surgeryCount Number of valid surgery operations in the array
function performSurgery(
bytes[] memory registers,
uint8 sourceReg,
SurgeryDescriptor[6] memory surgeries,
uint8 surgeryCount
)
internal
pure
{
// Mask register indices to get actual register index
uint8 srcRegIndex = sourceReg.idx();
// Get source calldata (to be modified in place)
bytes memory sourceData = registers.get(srcRegIndex);
uint256 sourceLength = sourceData.length;
// Apply surgeries directly to the source buffer
for (uint256 i = 0; i < surgeryCount;) {
SurgeryDescriptor memory desc = surgeries[i];
uint8 replacementRegIndex = desc.replacementReg.idx();
bytes memory replacement = registers.get(replacementRegIndex);
uint256 replacementLength = replacement.length;
uint256 surgeryLength = desc.length;
// Extract values before assembly block
uint256 offset = desc.offset;
// Bounds checking - ensure the surgery doesn't go beyond the source data
if (offset + surgeryLength > sourceLength) {
revert VmErrors.OutOfBounds();
}
// Check if replacement length is greater than surgery length
// We must revert rather than truncate in this case
if (replacementLength > surgeryLength) {
revert VmErrors.ReplacementTooLarge();
}
// Apply the replacement directly to the source buffer
assembly {
// Compute source memory addresses
let targetPtr := add(add(sourceData, 0x20), offset)
let replacementPtr := add(replacement, 0x20)
// If surgery length > replacement length, we'll need to pad with zeros
// Right-align the data (for ABI compatibility)
let padLength := sub(surgeryLength, replacementLength)
// Fill the zero padding first
let targetReplacementPtr := add(targetPtr, padLength)
for { } lt(targetPtr, targetReplacementPtr) { targetPtr := add(targetPtr, 1) } { mstore8(targetPtr, 0) }
// Then copy the replacement data to the end for right alignment
for { let j := 0 } lt(j, replacementLength) { j := add(j, 1) } {
mstore8(add(targetPtr, j), byte(0, mload(add(replacementPtr, j))))
}
}
unchecked {
++i;
}
}
}
}
src/VMLogLib.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;
import './DataModel.sol';
import './RegisterFile.sol';
import './VmErrors.sol';
import './RegisterHelpers.sol';
/// @title VMLogLib
/// @custom:version 1.0.0
/// @notice Library for handling the LOG operation that emits events with raw bytes data.
library VMLogLib {
using RegisterHelpers for uint8;
using RegisterFile for bytes[];
/// @notice Event emitted for static data with 1 register (32 bytes)
event VMLogStatic1(bytes32 data1);
/// @notice Event emitted for static data with 2 registers (64 bytes)
event VMLogStatic2(bytes32 data1, bytes32 data2);
/// @notice Event emitted for static data with 3 registers (96 bytes)
event VMLogStatic3(bytes32 data1, bytes32 data2, bytes32 data3);
/// @notice Event emitted for static data with 4 registers (128 bytes)
event VMLogStatic4(bytes32 data1, bytes32 data2, bytes32 data3, bytes32 data4);
/// @notice Event emitted for static data with 5 registers (160 bytes)
event VMLogStatic5(bytes32 data1, bytes32 data2, bytes32 data3, bytes32 data4, bytes32 data5);
/// @notice Event emitted for dynamic data from a register
event VMLogDyn(bytes data);
/// @notice Executes the LOG opcode's logic.
/// @param vmState The current VM state (in memory).
/// @param cmd The unpacked Log command parameters.
function execute(VMState memory vmState, Log memory cmd) internal {
// Check if variant is valid before casting to enum
if (cmd.variant > uint8(LogVariant.DYNAMIC)) {
revert VmErrors.InvalidLogVariant();
}
LogVariant variant = LogVariant(cmd.variant);
if (variant == LogVariant.STATIC_1) {
executeStatic1(vmState.registers, cmd.sourceRegs);
} else if (variant == LogVariant.STATIC_2) {
executeStatic2(vmState.registers, cmd.sourceRegs);
} else if (variant == LogVariant.STATIC_3) {
executeStatic3(vmState.registers, cmd.sourceRegs);
} else if (variant == LogVariant.STATIC_4) {
executeStatic4(vmState.registers, cmd.sourceRegs);
} else if (variant == LogVariant.STATIC_5) {
executeStatic5(vmState.registers, cmd.sourceRegs);
} else if (variant == LogVariant.DYNAMIC) {
executeDynamic(vmState.registers, cmd.sourceRegs);
}
}
/// @notice Extracts a register index from packed sourceRegs at the given byte position
function extractRegister(uint256 sourceRegs, uint8 position) private pure returns (uint8) {
// Each register is 1 byte, shift to get the byte at position
return uint8((sourceRegs >> ((25 - position) * 8)));
}
/// @notice Executes LOG for 1 static register
function executeStatic1(bytes[] memory registers, uint256 sourceRegs) private {
uint8 reg1 = extractRegister(sourceRegs, 0);
bytes memory regData = registers.getStatic(reg1.idx());
bytes32 data1;
assembly {
data1 := mload(add(regData, 0x20))
}
emit VMLogStatic1(data1);
}
/// @notice Executes LOG for 2 static registers
function executeStatic2(bytes[] memory registers, uint256 sourceRegs) private {
uint8 reg1 = extractRegister(sourceRegs, 0);
uint8 reg2 = extractRegister(sourceRegs, 1);
bytes memory regData1 = registers.getStatic(reg1.idx());
bytes memory regData2 = registers.getStatic(reg2.idx());
bytes32 data1;
bytes32 data2;
assembly {
data1 := mload(add(regData1, 0x20))
data2 := mload(add(regData2, 0x20))
}
emit VMLogStatic2(data1, data2);
}
/// @notice Executes LOG for 3 static registers
function executeStatic3(bytes[] memory registers, uint256 sourceRegs) private {
uint8 reg1 = extractRegister(sourceRegs, 0);
uint8 reg2 = extractRegister(sourceRegs, 1);
uint8 reg3 = extractRegister(sourceRegs, 2);
bytes memory regData1 = registers.getStatic(reg1.idx());
bytes memory regData2 = registers.getStatic(reg2.idx());
bytes memory regData3 = registers.getStatic(reg3.idx());
bytes32 data1;
bytes32 data2;
bytes32 data3;
assembly {
data1 := mload(add(regData1, 0x20))
data2 := mload(add(regData2, 0x20))
data3 := mload(add(regData3, 0x20))
}
emit VMLogStatic3(data1, data2, data3);
}
/// @notice Executes LOG for 4 static registers
function executeStatic4(bytes[] memory registers, uint256 sourceRegs) private {
uint8 reg1 = extractRegister(sourceRegs, 0);
uint8 reg2 = extractRegister(sourceRegs, 1);
uint8 reg3 = extractRegister(sourceRegs, 2);
uint8 reg4 = extractRegister(sourceRegs, 3);
bytes memory regData1 = registers.getStatic(reg1.idx());
bytes memory regData2 = registers.getStatic(reg2.idx());
bytes memory regData3 = registers.getStatic(reg3.idx());
bytes memory regData4 = registers.getStatic(reg4.idx());
bytes32 data1;
bytes32 data2;
bytes32 data3;
bytes32 data4;
assembly {
data1 := mload(add(regData1, 0x20))
data2 := mload(add(regData2, 0x20))
data3 := mload(add(regData3, 0x20))
data4 := mload(add(regData4, 0x20))
}
emit VMLogStatic4(data1, data2, data3, data4);
}
/// @notice Executes LOG for 5 static registers
function executeStatic5(bytes[] memory registers, uint256 sourceRegs) private {
uint8 reg1 = extractRegister(sourceRegs, 0);
uint8 reg2 = extractRegister(sourceRegs, 1);
uint8 reg3 = extractRegister(sourceRegs, 2);
uint8 reg4 = extractRegister(sourceRegs, 3);
uint8 reg5 = extractRegister(sourceRegs, 4);
bytes memory regData1 = registers.getStatic(reg1.idx());
bytes memory regData2 = registers.getStatic(reg2.idx());
bytes memory regData3 = registers.getStatic(reg3.idx());
bytes memory regData4 = registers.getStatic(reg4.idx());
bytes memory regData5 = registers.getStatic(reg5.idx());
bytes32 data1;
bytes32 data2;
bytes32 data3;
bytes32 data4;
bytes32 data5;
assembly {
data1 := mload(add(regData1, 0x20))
data2 := mload(add(regData2, 0x20))
data3 := mload(add(regData3, 0x20))
data4 := mload(add(regData4, 0x20))
data5 := mload(add(regData5, 0x20))
}
emit VMLogStatic5(data1, data2, data3, data4, data5);
}
/// @notice Executes LOG for dynamic data
function executeDynamic(bytes[] memory registers, uint256 sourceRegs) private {
uint8 reg = extractRegister(sourceRegs, 0);
bytes memory data = registers.get(reg.idx());
emit VMLogDyn(data);
}
}
src/VmConstants.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;
/// @title VmConstants
/// @custom:version 1.1.0
/// @notice Shared constants for the Virtual Machine and test helpers
library VmConstants {
// Register constants
uint8 public constant DYN_MASK = 0x80;
uint8 public constant IDX_MASK = 0x7F;
uint8 public constant VOID_REG = 0x7A;
// ABI / memory word size (32 bytes).
uint256 public constant WORD_SIZE = 32;
// Surgery limits
uint8 public constant MAX_SURGERIES = 6;
// Blueprint size limits
uint8 public constant MAX_CDB_BP = 22; // CALLDATA_BUILD blueprint max size
uint8 public constant MAX_ABI_BP = 27; // ABI_ENCODE blueprint max size
// Blueprint container tokens (from BlueprintEncoder)
uint8 public constant START_TUPLE_STATIC = 0x7F;
uint8 public constant START_TUPLE_DYNAMIC = 0x7E;
uint8 public constant START_ARRAY_STATIC = 0x7D;
uint8 public constant START_ARRAY_DYNAMIC = 0x7C;
uint8 public constant END_DYNAMIC = 0x7B;
}
src/VmErrors.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;
/// @title VmErrors
/// @custom:version 1.1.0
/// @notice Shared error definitions for the Virtual Machine
library VmErrors {
/// @notice Thrown when a disallowed operation is executed
error Disallowed();
/// @notice Thrown when a read exceeds the bounds of the source data. Raised by
/// `SurgeryOPS` (surgery offset/length), `ExplodeLib` (source shorter than the head
/// region, or a dynamic offset that is unaligned, inside the head region, past the
/// source, or not strictly increasing) and `MemoryUtils.slice`.
error OutOfBounds();
/// @notice Thrown when replacement data exceeds surgery length
error ReplacementTooLarge();
/// @notice Thrown when too many surgeries are requested (maximum 6)
error TooManySurgeries();
/// @notice Thrown when an invalid log variant is provided
error InvalidLogVariant();
/// @notice Thrown when an invalid call type is provided
error InvalidCallType();
/// @notice Thrown when a blueprint exceeds the maximum allowed size
error BlueprintTooLarge();
/// @notice Thrown when source registers exceed 208 bits for log packing
error SourceRegistersExceed208Bits();
/// @notice Thrown when no tokens are approved for deposit
error NoApprovedTokens();
/// @notice Thrown when token transfer fails during deposit
error TokenTransferFailed();
/// @notice Thrown when an invalid opcode is encountered
error InvalidOpcode(uint8 opcode);
/// @notice Thrown when bytes are attempted to be read as address
error InvalidAddressBytes();
/// @notice Thrown when a CALL source register is not valid calldata: it is shorter than its 32-byte length word,
/// or its length word declares more bytes than the register carries after it
error InvalidCallDataLength();
/// @notice Thrown when value data is too short (must be at least 32 bytes)
error InvalidValueLength();
/// @notice Thrown when too many operations are requested (maximum 32)
error TooManyOperations();
/// @notice Thrown when an invalid user address (zero address) is provided
error InvalidUserAddress();
/// @notice Thrown when a proxy has already been deployed for the user
error ProxyAlreadyDeployed();
/// @notice Thrown when unauthorized access is attempted
error Unauthorized();
/// @notice Thrown when attempting to call a non-contract address
error CallToNonContract();
/// @notice Thrown when register data has invalid length
error InvalidRegisterLength();
/// @notice Thrown when destination register count is outwith allowed range
error DestinationCountOutOfBounds(uint8 count);
/// @notice Thrown when destination register count does not match the specified count
error DestinationCountMismatch(uint8 expected, uint256 found);
/// @notice Thrown when an invalid address is provided
error InvalidAddress();
/// @notice Thrown when an invalid token address is provided
error InvalidTokenAddress();
/// @notice Thrown when GetBalance call fails (in DepositApproved)
error GetBalanceFailed();
/// @notice Thrown when factoryInitialize has already been called
error AlreadyInitialized();
/// @notice Thrown when reserved padding bytes in a packed command word are non-zero
error NonZeroPadding();
}
src/interfaces/IERC20.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.30;
/// @custom:version 1.0.0
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 10000,
"enabled": true
},
"evmVersion": "osaka",
"remappings": [
"forge-std/=lib/forge-std/src/",
"@chimera/=lib/setup-helpers/lib/chimera/src/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"chimera/=lib/chimera/src/",
"ds-test/=lib/chimera/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"setup-helpers/=lib/setup-helpers/src/",
"solady/=lib/solady/src/",
"solady-test/=lib/solady/test/",
"@recon/=lib/setup-helpers/src/",
"create3-factory/=lib/create3-factory/",
"createx-forge/=lib/createx-forge/",
"solmate/=lib/create3-factory/lib/solmate/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.