Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

In this article, I explore the Permit2 contract using Bunzz's DeCipher feature.

DeCipher is a service that automatically generates smart contract documentation using AI.

For a detailed guide to using the service, see the following article.

This article reflects my personal experience with DeCipher. If you notice any inaccuracies, please let me know in the comments.

The following is the DeCipher link used in this article.

The corresponding Etherscan link is below.

Overview

The Permit2 contract enables secure and efficient token transfers on Ethereum.

Purpose It allows users to authorize token transfers on their behalf. Users can delegate transfer permissions to specified addresses without manually approving every transaction.

Responsibilities

  1. Allowance management The contract manages the Allowance, or maximum token amount authorized by a user. This allows users to control another party's authority to transfer tokens on their behalf.

  2. Signature verification The SignatureVerification library checks whether a signature provided by the user is valid. This ensures that token transfers are backed by valid authorization.

  3. Permit hash generation The PermitHash library generates a distinct hash for each signed allowance authorization. This allows the authenticity of the transfer authorization to be verified.

  4. Token transfers The contract integrates the ERC20 token interface through ERC20.sol. This allows tokens to be transferred securely between addresses.

  5. Safe transfers The SafeTransferLib library performs checks during token transfers to protect against potential vulnerabilities.

  6. EIP712 support The EIP712.sol contract provides support for secure message signing.

  7. Error handling The PermitErrors.sol contract provides errors for exceptional conditions, helping users understand failures.

  8. Interface conformance The Permit2 contract conforms to various interfaces to maintain compatibility with other contracts and systems.

Usage

Permit2 is a smart contract for token approvals and transfers on behalf of token owners. It works with the ERC20 standard and provides additional approval and signature-verification functionality.

Objective

It provides a way for token owners and authorized addresses to perform approvals and transfers securely and efficiently. Owners can manage tokens more conveniently without having to approve every operation manually.

How to use it

  1. Deploy the Permit2 contract First, deploy the Permit2 contract.

  2. Call approve Call approve to grant an allowance. This authorizes the spender (spender) to transfer tokens on behalf of the owner.

  3. Call transferFrom An authorized address can call transferFrom to transfer tokens from the owner's account to another account.

  4. Call permit For more convenient approval, permit uses a signature to authorize a spender to transfer tokens on behalf of the owner.

  5. Call transferWithSignature The original overview refers to transferWithSignature for transferring tokens from the owner's account to another account using a signature.

Functions

  • approve(address spender, uint256 amount) Authorizes an address to transfer a specified amount of tokens on behalf of the owner.

  • transferFrom(address sender, address recipient, uint256 amount) An authorized address transfers tokens from the owner's account to another account.

  • permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) Uses a signature to authorize an address to transfer tokens on behalf of the owner.

  • transferWithSignature(address sender, address recipient, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) Transfers tokens from the owner's account to another account using a signature.

Events

  • Approval(address indexed owner, address indexed spender, uint256 value) Emitted when an authorized address and allowance are set or updated.

  • Transfer(address indexed from, address indexed to, uint256 value) Emitted when tokens are transferred from one account to another.

  • Permit(address indexed owner, address indexed spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) Emitted when a signature authorizes a spender to transfer tokens on behalf of the owner.

  • TransferWithSignature(address indexed sender, address indexed recipient, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) Emitted when tokens are transferred from the owner's account to another account using a signature.

  • ERC20
    • The Permit2 contract implements the ERC20 standard for fungible tokens.

https://chaldene.net/erc20

  • ERC721
    • The Permit2 contract uses EIP-712 for signature verification.

https://chaldene.net/erc721

  • ERC1271
    • The Permit2 contract implements the IERC1271 interface for contract signature verification.

Parameters

None.

Contract

AllowanceTransfer

allowance

allowance
solidity
mapping(address => mapping(address => mapping(address => PackedAllowance))) public allowance;

Overview A mapping storing token approval information for owner and spender addresses.

Details This mapping has three levels: the first key is the owner address, the second is the token address, and the third is the spender address. This allows approval information for each spender and each token held by an owner to be retrieved. PackedAllowance is a struct packing the approved amount, expiration, and nonce.

Parameters

  • owner
    • Token owner's address.
  • token
    • Address of the token being approved.
  • spender
    • Address holding the approval.
  • PackedAllowance
    • Struct containing packed approval information.
    • Stores the permitted token amount, approval expiration, and nonce.

approve

approve
solidity
function approve(address token, address spender, uint160 amount, uint48 expiration) external {
    PackedAllowance storage allowed = allowance[msg.sender][token][spender];
    allowed.updateAmountAndExpiration(amount, expiration);
    emit Approval(msg.sender, token, spender, amount, expiration);
}

Overview Sets an approval for token spending.

Parameters

  • token
    • Address of the token being approved.
  • spender
    • Address receiving the approval.
  • amount
    • Token amount to approve.
  • expiration
    • Approval expiration.

Return value None.


permit

permit
solidity
function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external {
    if (block.timestamp > permitSingle.sigDeadline) revert SignatureExpired(permitSingle.sigDeadline);

    // Verify the signer address from the signature.
    signature.verify(_hashTypedData(permitSingle.hash()), owner);

    _updateApproval(permitSingle.details, owner, permitSingle.spender);
}

Overview Creates a single token approval.

Parameters

  • owner
    • Address of the token owner granting the approval.
  • permitSingle
    • Struct containing approval information.
  • signature
    • Signature data.

permit

permit
solidity
function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external {
    if (block.timestamp > permitBatch.sigDeadline) revert SignatureExpired(permitBatch.sigDeadline);

    // Verify the signer address from the signature.
    signature.verify(_hashTypedData(permitBatch.hash()), owner);

    address spender = permitBatch.spender;
    unchecked {
        uint256 length = permitBatch.details.length;
        for (uint256 i = 0; i < length; ++i) {
            _updateApproval(permitBatch.details[i], owner, spender);
        }
    }
}

Overview Creates multiple token approvals in a batch.

Parameters

  • owner
    • Address of the token owner granting the approvals.
  • permitBatch
    • Array of structs containing approval information.
  • signature
    • Signature data.

transferFrom

transferFrom
solidity
function transferFrom(address from, address to, uint160 amount, address token) external {
    _transfer(from, to, amount, token);
}

Overview Transfers tokens to a specified address.

Parameters

  • from
    • Recipient address.
  • to
    • Source address.
  • amount
    • Amount of tokens to transfer.
  • token
    • Address of the token to transfer.

Return value None.


transferFrom

transferFrom
solidity
function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external {
    unchecked {
        uint256 length = transferDetails.length;
        for (uint256 i = 0; i < length; ++i) {
            AllowanceTransferDetails memory transferDetail = transferDetails[i];
            _transfer(transferDetail.from, transferDetail.to, transferDetail.amount, transferDetail.token);
        }
    }
}

Overview Transfers multiple tokens in a batch.

Details

  • transferDetails
    • Array of structs containing token transfer information.

Parameters

  • transferDetails
    • Array of structs containing token transfer information.

Return value None.


_transfer

_transfer
solidity
function _transfer(address from, address to, uint160 amount, address token) private {
    PackedAllowance storage allowed = allowance[from][token][msg.sender];

    if (block.timestamp > allowed.expiration) revert AllowanceExpired(allowed.expiration);

    uint256 maxAmount = allowed.amount;
    if (maxAmount != type(uint160).max) {
        if (amount > maxAmount) {
            revert InsufficientAllowance(maxAmount);
        } else {
            unchecked {
                allowed.amount = uint160(maxAmount) - amount;
            }
        }
    }

    // Transfer the tokens from the from address to the recipient.
    ERC20(token).safeTransferFrom(from, to, amount);
}

Overview Executes a token transfer.

Parameters

  • from
    • Address sending the tokens.
  • to
    • Address receiving the tokens.
  • amount
    • Amount of tokens to transfer.
  • token
    • Address of the token to transfer.

lockdown

lockdown
solidity
function lockdown(TokenSpenderPair[] calldata approvals) external {
    address owner = msg.sender;
    // Revoke allowances for each pair of spenders and tokens.
    unchecked {
        uint256 length = approvals.length;
        for (uint256 i = 0; i < length; ++i) {
            address token = approvals[i].token;
            address spender = approvals[i].spender;

            allowance[owner][token][spender].amount = 0;
            emit Lockdown(owner, token, spender);
        }
    }
}

Overview Revokes multiple approvals to lock down token spending.

Details Revokes approvals for specified token and spender pairs. Sets the approved amount to zero and emits a Lockdown event.

Parameters

  • approvals
    • Array of token and spender pairs whose approvals are to be revoked.

invalidateNonces

invalidateNonces
solidity
function invalidateNonces(address token, address spender, uint48 newNonce) external {
    uint48 oldNonce = allowance[msg.sender][token][spender].nonce;

    if (newNonce <= oldNonce) revert InvalidNonce();

    // Limit the amount of nonces that can be invalidated in one transaction.
    unchecked {
        uint48 delta = newNonce - oldNonce;
        if (delta > type(uint16).max) revert ExcessiveInvalidation();
    }

    allowance[msg.sender][token][spender].nonce = newNonce;
    emit NonceInvalidation(msg.sender, token, spender, newNonce, oldNonce);
}

Overview Invalidates and updates a nonce (an identifier for token approval).

Details The function checks that the new nonce exceeds the old nonce, then updates it if the specified conditions are satisfied. It also emits the corresponding event.

Parameters

  • token
    • Token address.
  • spender
    • Address receiving the approval.
  • newNonce
    • New nonce value.

Return value None.


_updateApproval

_updateApproval
solidity
function _updateApproval(PermitDetails memory details, address owner, address spender) private {
    uint48 nonce = details.nonce;
    address token = details.token;
    uint160 amount = details.amount;
    uint48 expiration = details.expiration;
    PackedAllowance storage allowed = allowance[owner][token][spender];

    if (allowed.nonce != nonce) revert InvalidNonce();

    allowed.updateAll(amount, expiration, nonce);
    emit Permit(owner, token, spender, amount, expiration, nonce);
}

Overview Updates approval information.

Details Checks whether the signed nonce equals the current nonce, then updates it. Emits a Permit event.

Parameters

  • details
    • Struct containing the approval details.
  • owner
    • Address of the owner granting the approval.
  • spender
    • Address receiving the approval.

SignatureTransfer

nonceBitmapnonceBitmap

nonceBitmap
solidity
mapping(address => mapping(uint256 => uint256)) public nonceBitmap;

Overview A mapping containing bitmaps associated with address and nonce-word-position pairs. It is used to manage nonces.

Parameters

  • address
    • Address used as a key for storing nonce information associated with that address.
  • uint256
    • Integer identifying a nonce bitmap word.
    • Multiple bitmaps may be stored for each address, corresponding to different nonce word positions.
  • uint256
    • Bitmap representing nonce status.
    • Each bit corresponds to a nonce; a set bit indicates that the nonce has already been consumed.

permitTransferFrom

permitTransferFrom
solidity
function permitTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external {
        _permitTransferFrom(permit, transferDetails, owner, permit.hash(), signature);
}

Overview Transfers tokens using a signed message.

Details Receives a signed message and executes a token transfer subject to the specified conditions.

Parameters

  • permit
    • Struct containing information about the permit message.
  • transferDetails
    • Data containing transfer details.
  • owner
    • Token owner's address.
  • signature
    • Signature data.

permitWitnessTransferFrom

permitWitnessTransferFrom
solidity
function permitWitnessTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes32 witness,
        string calldata witnessTypeString,
        bytes calldata signature
    ) external {
        _permitTransferFrom(
            permit, transferDetails, owner, permit.hashWithWitness(witness, witnessTypeString), signature
        );
}

Overview Transfers tokens using a signed message that includes additional witness information.

Parameters

  • permit
    • Struct containing information about the permit message.
  • transferDetails
    • Data containing transfer details.
  • owner
    • Token owner's address.
  • witness
    • Witness hash or other witness data represented by the hash.
  • witnessTypeString
    • String specifying the witness type.
  • signature
    • Signature data.

_permitTransferFrom

_permitTransferFrom
solidity
function _permitTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes32 dataHash,
        bytes calldata signature
    ) private {
        uint256 requestedAmount = transferDetails.requestedAmount;

        if (block.timestamp > permit.deadline) revert SignatureExpired(permit.deadline);
        if (requestedAmount > permit.permitted.amount) revert InvalidAmount(permit.permitted.amount);

        _useUnorderedNonce(owner, permit.nonce);

        signature.verify(_hashTypedData(dataHash), owner);

        ERC20(permit.permitted.token).safeTransferFrom(owner, transferDetails.to, requestedAmount);
}

Overview Performs the actual token transfer.

Details Checks whether the transfer is permitted under the supplied permit data, verifies the signature, and transfers the tokens.

Parameters

  • permit
    • Struct containing information about the permit message.
  • transferDetails
    • Data containing transfer details.
  • owner
    • Token owner's address.
  • dataHash
    • Data hash used for signature verification.
  • signature
    • Signature data.

permitTransferFrom

permitTransferFrom
solidity
function permitTransferFrom(
        PermitBatchTransferFrom memory permit,
        SignatureTransferDetails[] calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external {
        _permitTransferFrom(permit, transferDetails, owner, permit.hash(), signature);
}

Overview Transfers multiple tokens in a batch using a signed permit message.

Details Performs a batch transfer of multiple tokens. Receives permission data and a signature covering multiple tokens, then performs the batch transfer subject to the specified conditions. The token owner signs the authorization; recipient and amount details are supplied for the transfers.

Parameters

  • permit
    • Struct containing information about the permit message.
  • transferDetails
    • Array containing multiple transfer details.
  • owner
    • Token owner's address.
  • signature
    • Signature data.

permitWitnessTransferFrom

permitWitnessTransferFrom
solidity
function permitWitnessTransferFrom(
        PermitBatchTransferFrom memory permit,
        SignatureTransferDetails[] calldata transferDetails,
        address owner,
        bytes32 witness,
        string calldata witnessTypeString,
        bytes calldata signature
    ) external {
        _permitTransferFrom(
            permit, transferDetails, owner, permit.hashWithWitness(witness, witnessTypeString), signature
        );
}

Overview Transfers multiple tokens in a batch using a signed permit message with witness information.

Details Performs a batch transfer of multiple tokens. Receives permission data, a signature, and witness information, then performs the batch transfer subject to the specified conditions. The token owner signs the authorization; transfer recipient and amount details, along with witness information, are supplied.

Parameters

  • permit
    • Struct containing information about the permit message.
  • transferDetails
    • Array containing multiple transfer details.
  • owner
    • Token owner's address.
  • witness
    • Witness hash or other witness data represented by the hash.
  • witnessTypeString
    • String specifying the witness type.
  • signature
    • Signature data.

_permitTransferFrom

_permitTransferFrom
solidity
function _permitTransferFrom(
        PermitBatchTransferFrom memory permit,
        SignatureTransferDetails[] calldata transferDetails,
        address owner,
        bytes32 dataHash,
        bytes calldata signature
    ) private {
        uint256 numPermitted = permit.permitted.length;

        if (block.timestamp > permit.deadline) revert SignatureExpired(permit.deadline);
        if (numPermitted != transferDetails.length) revert LengthMismatch();

        _useUnorderedNonce(owner, permit.nonce);
        signature.verify(_hashTypedData(dataHash), owner);

        unchecked {
            for (uint256 i = 0; i < numPermitted; ++i) {
                TokenPermissions memory permitted = permit.permitted[i];
                uint256 requestedAmount = transferDetails[i].requestedAmount;

                if (requestedAmount > permitted.amount) revert InvalidAmount(permitted.amount);

                if (requestedAmount != 0) {
                    // allow spender to specify which of the permitted tokens should be transferred
                    ERC20(permitted.token).safeTransferFrom(owner, transferDetails[i].to, requestedAmount);
                }
            }
        }
}

Overview Executes transfers of permitted tokens.

Details Performs a batch transfer of multiple permitted tokens. Uses the supplied permit data and signature to execute token transfers authorized by the owner. The details of the tokens being transferred in the batch are also specified.

Parameters

  • permit
    • Struct containing information about the permit message.
  • transferDetails
    • Array containing multiple transfer details.
  • owner
    • Token owner's address.
  • dataHash
    • Data hash used for signature verification.
  • signature
    • Signature data.

invalidateUnorderedNonces

invalidateUnorderedNonces
solidity
function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) external {
        nonceBitmap[msg.sender][wordPos] |= mask;

        emit UnorderedNonceInvalidation(msg.sender, wordPos, mask);
}

Overview Invalidates unordered nonces.

Details Invalidates unordered nonces using a specified word position and mask. This prevents the nonces from being reused.

What are unordered nonces? Unordered nonces allow authorizations to be consumed without enforcing a particular sequential order, while still requiring replay protection. Conventional transaction nonces are expected to increase sequentially, but relayed authorizations may not be submitted in a guaranteed order.

Replay protection for unordered nonces Without tracking consumption, the same Nonce could be reused multiple times, potentially allowing unauthorized repeated transfers. To prevent this, each nonce must authorize execution only once.

Role of invalidateUnorderedNonces The invalidateUnorderedNonces function is used to invalidate unordered nonces. Specifically, it invalidates nonces using a specified word position and mask. This prevents nonce reuse.

Execution flow

  1. invalidateUnorderedNonces takes a word position and mask as arguments.
  2. It uses the word position and mask to invalidate specific bits in a bitmap. This records the corresponding nonces as consumed, preventing reuse.

This operation strengthens security by preventing an authorization using an invalidated unordered nonce from being executed again.

Parameters

  • wordPos
    • Word position.
  • mask
    • Mask.

bitmapPositions

bitmapPositions
solidity
function bitmapPositions(uint256 nonce) private pure returns (uint256 wordPos, uint256 bitPos) {
        wordPos = uint248(nonce >> 8);
        bitPos = uint8(nonce);
}

Overview Retrieves the bitmap position of a Nonce.

Details Calculates and returns the bitmap position (word position and bit position) for the specified Nonce. The upper 248 bits of the nonce identify the bitmap word, and the lower 8 bits identify the bit position.

Parameters

  • nonce
    • Nonce value.

Return value

  • wordPos
    • Word position.
  • bitPos
    • Bit position.

_useUnorderedNonce

_useUnorderedNonce
solidity
unction _useUnorderedNonce(address from, uint256 nonce) internal {
        (uint256 wordPos, uint256 bitPos) = bitmapPositions(nonce);
        uint256 bit = 1 << bitPos;
        uint256 flipped = nonceBitmap[from][wordPos] ^= bit;

        if (flipped & bit == 0) revert InvalidNonce();
}

Overview Consumes an unordered Nonce and sets the corresponding bit in the bitmap.

Details Uses the specified address and nonce to set the corresponding bitmap bit. If the nonce has already been consumed, the operation reverts.

Parameters

  • from
    • Address.
  • nonce
    • Nonce value.

Events and errors

AllowanceExpired

AllowanceExpired
solidity
error AllowanceExpired(uint256 deadline);

Overview An error raised when a token allowance has expired.

Details Raised when the current timestamp is later than the allowance expiration set by the token owner. This prevents expired approvals from being used.

Parameters

  • deadline
    • Allowance expiration timestamp.

InsufficientAllowance

InsufficientAllowance
solidity
error InsufficientAllowance(uint256 amount);

Overview An error raised when the token allowance is insufficient.

Details Raised when token spending exceeds the allowance set by the token owner. This prevents spending beyond the approved amount.

Parameters

  • amount
    • Maximum permitted amount.

ExcessiveInvalidation

ExcessiveInvalidation
solidity
error ExcessiveInvalidation();

Overview An error raised when the number of nonce values invalidated is excessive.

Details Raised when the nonce invalidation range exceeds the permitted limit. The limit prevents excessively large nonce invalidation jumps.


NonceInvalidation

NonceInvalidation
solidity
event NonceInvalidation(
    address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce
);

Overview An event emitted when the owner invalidates nonces.

Details Emitted when the owner invalidates nonces, including the new and previous nonce values. This makes nonce invalidation observable.

Parameters

  • owner
    • Token owner's address.
  • token
    • Token address.
  • spender
    • Address authorized to transfer tokens.
  • newNonce
    • New Nonce value.
  • oldNonce
    • Previous Nonce value.

Approval

Approval
solidity
event Approval(
    address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration
);

Overview An event emitted when the owner sets a token allowance and expiration.

Details Emitted when the owner sets a token allowance and expiration, including the approved amount and expiration. This indicates how many tokens another address is authorized to use.

Parameters

  • owner
    • Token owner's address.
  • token
    • Token address.
  • spender
    • Address authorized to transfer tokens.
  • amount
    • Approved token amount.
  • expiration
    • Expiration timestamp.

Permit

Permit
solidity
event Permit(
    address indexed owner,
    address indexed token,
    address indexed spender,
    uint160 amount,
    uint48 expiration,
    uint48 nonce
);

Overview An event emitted when the owner sets a token allowance and expiration using a signed permit message.

Details Emitted when the owner sets a token allowance and expiration using a signed permit message, including the approved amount, expiration, and nonce. This indicates how many tokens another address is authorized to use.

Parameters

  • owner
    • Token owner's address.
  • token
    • Token address.
  • spender
    • Address authorized to transfer tokens.
  • amount
    • Approved token amount.
  • expiration
    • Expiration timestamp.
  • nonce
    • Nonce value.

Lockdown

Lockdown
solidity
event Lockdown(address indexed owner, address token, address spender);

Overview An event emitted when an owner sets a token allowance to 0.

Details It indicates that the corresponding allowance has been revoked.

Parameters

  • owner
    • Token owner's address.
  • token
    • Token address.
  • spender
    • Address authorized to transfer tokens.

Code

Permit2.sol

Permit2
solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;

import {SignatureTransfer} from "./SignatureTransfer.sol";
import {AllowanceTransfer} from "./AllowanceTransfer.sol";

/// @notice Permit2 handles signature-based transfers in SignatureTransfer and allowance-based transfers in AllowanceTransfer.
/// @dev Users must approve Permit2 before calling any of the transfer functions.
contract Permit2 is SignatureTransfer, AllowanceTransfer {
// Permit2 unifies the two contracts so users have maximal flexibility with their approval.
}

AllowanceTransfer.sol

AllowanceTransfer.sol
solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;

import {ERC20} from "solmate/tokens/ERC20.sol";
import {SafeTransferLib} from "solmate/utils/SafeTransferLib.sol";
import {PermitHash} from "./libraries/PermitHash.sol";
import {SignatureVerification} from "./libraries/SignatureVerification.sol";
import {EIP712} from "./EIP712.sol";
import {IAllowanceTransfer} from "../src/interfaces/IAllowanceTransfer.sol";
import {SignatureExpired, InvalidNonce} from "./PermitErrors.sol";
import {Allowance} from "./libraries/Allowance.sol";

contract AllowanceTransfer is IAllowanceTransfer, EIP712 {
    using SignatureVerification for bytes;
    using SafeTransferLib for ERC20;
    using PermitHash for PermitSingle;
    using PermitHash for PermitBatch;
    using Allowance for PackedAllowance;

    /// @notice Maps users to tokens to spender addresses and information about the approval on the token
    /// @dev Indexed in the order of token owner address, token address, spender address
    /// @dev The stored word saves the allowed amount, expiration on the allowance, and nonce
    mapping(address => mapping(address => mapping(address => PackedAllowance))) public allowance;

    /// @inheritdoc IAllowanceTransfer
    function approve(address token, address spender, uint160 amount, uint48 expiration) external {
        PackedAllowance storage allowed = allowance[msg.sender][token][spender];
        allowed.updateAmountAndExpiration(amount, expiration);
        emit Approval(msg.sender, token, spender, amount, expiration);
    }

    /// @inheritdoc IAllowanceTransfer
    function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external {
        if (block.timestamp > permitSingle.sigDeadline) revert SignatureExpired(permitSingle.sigDeadline);

        // Verify the signer address from the signature.
        signature.verify(_hashTypedData(permitSingle.hash()), owner);

        _updateApproval(permitSingle.details, owner, permitSingle.spender);
    }

    /// @inheritdoc IAllowanceTransfer
    function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external {
        if (block.timestamp > permitBatch.sigDeadline) revert SignatureExpired(permitBatch.sigDeadline);

        // Verify the signer address from the signature.
        signature.verify(_hashTypedData(permitBatch.hash()), owner);

        address spender = permitBatch.spender;
        unchecked {
            uint256 length = permitBatch.details.length;
            for (uint256 i = 0; i < length; ++i) {
                _updateApproval(permitBatch.details[i], owner, spender);
            }
        }
    }

    /// @inheritdoc IAllowanceTransfer
    function transferFrom(address from, address to, uint160 amount, address token) external {
        _transfer(from, to, amount, token);
    }

    /// @inheritdoc IAllowanceTransfer
    function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external {
        unchecked {
            uint256 length = transferDetails.length;
            for (uint256 i = 0; i < length; ++i) {
                AllowanceTransferDetails memory transferDetail = transferDetails[i];
                _transfer(transferDetail.from, transferDetail.to, transferDetail.amount, transferDetail.token);
            }
        }
    }

    /// @notice Internal function for transferring tokens using stored allowances
    /// @dev Will fail if the allowed timeframe has passed
    function _transfer(address from, address to, uint160 amount, address token) private {
        PackedAllowance storage allowed = allowance[from][token][msg.sender];

        if (block.timestamp > allowed.expiration) revert AllowanceExpired(allowed.expiration);

        uint256 maxAmount = allowed.amount;
        if (maxAmount != type(uint160).max) {
            if (amount > maxAmount) {
                revert InsufficientAllowance(maxAmount);
            } else {
                unchecked {
                    allowed.amount = uint160(maxAmount) - amount;
                }
            }
        }

        // Transfer the tokens from the from address to the recipient.
        ERC20(token).safeTransferFrom(from, to, amount);
    }

    /// @inheritdoc IAllowanceTransfer
    function lockdown(TokenSpenderPair[] calldata approvals) external {
        address owner = msg.sender;
        // Revoke allowances for each pair of spenders and tokens.
        unchecked {
            uint256 length = approvals.length;
            for (uint256 i = 0; i < length; ++i) {
                address token = approvals[i].token;
                address spender = approvals[i].spender;

                allowance[owner][token][spender].amount = 0;
                emit Lockdown(owner, token, spender);
            }
        }
    }

    /// @inheritdoc IAllowanceTransfer
    function invalidateNonces(address token, address spender, uint48 newNonce) external {
        uint48 oldNonce = allowance[msg.sender][token][spender].nonce;

        if (newNonce <= oldNonce) revert InvalidNonce();

        // Limit the amount of nonces that can be invalidated in one transaction.
        unchecked {
            uint48 delta = newNonce - oldNonce;
            if (delta > type(uint16).max) revert ExcessiveInvalidation();
        }

        allowance[msg.sender][token][spender].nonce = newNonce;
        emit NonceInvalidation(msg.sender, token, spender, newNonce, oldNonce);
    }

    /// @notice Sets the new values for amount, expiration, and nonce.
    /// @dev Will check that the signed nonce is equal to the current nonce and then incrememnt the nonce value by 1.
    /// @dev Emits a Permit event.
    function _updateApproval(PermitDetails memory details, address owner, address spender) private {
        uint48 nonce = details.nonce;
        address token = details.token;
        uint160 amount = details.amount;
        uint48 expiration = details.expiration;
        PackedAllowance storage allowed = allowance[owner][token][spender];

        if (allowed.nonce != nonce) revert InvalidNonce();

        allowed.updateAll(amount, expiration, nonce);
        emit Permit(owner, token, spender, amount, expiration, nonce);
    }
}

SignatureTransfer.sol

SignatureTransfer.sol
solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;

import {ISignatureTransfer} from "./interfaces/ISignatureTransfer.sol";
import {SignatureExpired, InvalidNonce} from "./PermitErrors.sol";
import {ERC20} from "solmate/tokens/ERC20.sol";
import {SafeTransferLib} from "solmate/utils/SafeTransferLib.sol";
import {SignatureVerification} from "./libraries/SignatureVerification.sol";
import {PermitHash} from "./libraries/PermitHash.sol";
import {EIP712} from "./EIP712.sol";

contract SignatureTransfer is ISignatureTransfer, EIP712 {
    using SignatureVerification for bytes;
    using SafeTransferLib for ERC20;
    using PermitHash for PermitTransferFrom;
    using PermitHash for PermitBatchTransferFrom;

    /// @inheritdoc ISignatureTransfer
    mapping(address => mapping(uint256 => uint256)) public nonceBitmap;

    /// @inheritdoc ISignatureTransfer
    function permitTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external {
        _permitTransferFrom(permit, transferDetails, owner, permit.hash(), signature);
    }

    /// @inheritdoc ISignatureTransfer
    function permitWitnessTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes32 witness,
        string calldata witnessTypeString,
        bytes calldata signature
    ) external {
        _permitTransferFrom(
            permit, transferDetails, owner, permit.hashWithWitness(witness, witnessTypeString), signature
        );
    }

    /// @notice Transfers a token using a signed permit message.
    /// @dev If to is the zero address, the tokens are sent to the spender.
    /// @param permit The permit data signed over by the owner
    /// @param dataHash The EIP-712 hash of permit data to include when checking signature
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails The spender's requested transfer details for the permitted token
    /// @param signature The signature to verify
    function _permitTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes32 dataHash,
        bytes calldata signature
    ) private {
        uint256 requestedAmount = transferDetails.requestedAmount;

        if (block.timestamp > permit.deadline) revert SignatureExpired(permit.deadline);
        if (requestedAmount > permit.permitted.amount) revert InvalidAmount(permit.permitted.amount);

        _useUnorderedNonce(owner, permit.nonce);

        signature.verify(_hashTypedData(dataHash), owner);

        ERC20(permit.permitted.token).safeTransferFrom(owner, transferDetails.to, requestedAmount);
    }

    /// @inheritdoc ISignatureTransfer
    function permitTransferFrom(
        PermitBatchTransferFrom memory permit,
        SignatureTransferDetails[] calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external {
        _permitTransferFrom(permit, transferDetails, owner, permit.hash(), signature);
    }

    /// @inheritdoc ISignatureTransfer
    function permitWitnessTransferFrom(
        PermitBatchTransferFrom memory permit,
        SignatureTransferDetails[] calldata transferDetails,
        address owner,
        bytes32 witness,
        string calldata witnessTypeString,
        bytes calldata signature
    ) external {
        _permitTransferFrom(
            permit, transferDetails, owner, permit.hashWithWitness(witness, witnessTypeString), signature
        );
    }

    /// @notice Transfers tokens using a signed permit messages
    /// @dev If to is the zero address, the tokens are sent to the spender
    /// @param permit The permit data signed over by the owner
    /// @param dataHash The EIP-712 hash of permit data to include when checking signature
    /// @param owner The owner of the tokens to transfer
    /// @param signature The signature to verify
    function _permitTransferFrom(
        PermitBatchTransferFrom memory permit,
        SignatureTransferDetails[] calldata transferDetails,
        address owner,
        bytes32 dataHash,
        bytes calldata signature
    ) private {
        uint256 numPermitted = permit.permitted.length;

        if (block.timestamp > permit.deadline) revert SignatureExpired(permit.deadline);
        if (numPermitted != transferDetails.length) revert LengthMismatch();

        _useUnorderedNonce(owner, permit.nonce);
        signature.verify(_hashTypedData(dataHash), owner);

        unchecked {
            for (uint256 i = 0; i < numPermitted; ++i) {
                TokenPermissions memory permitted = permit.permitted[i];
                uint256 requestedAmount = transferDetails[i].requestedAmount;

                if (requestedAmount > permitted.amount) revert InvalidAmount(permitted.amount);

                if (requestedAmount != 0) {
                    // allow spender to specify which of the permitted tokens should be transferred
                    ERC20(permitted.token).safeTransferFrom(owner, transferDetails[i].to, requestedAmount);
                }
            }
        }
    }

    /// @inheritdoc ISignatureTransfer
    function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) external {
        nonceBitmap[msg.sender][wordPos] |= mask;

        emit UnorderedNonceInvalidation(msg.sender, wordPos, mask);
    }

    /// @notice Returns the index of the bitmap and the bit position within the bitmap. Used for unordered nonces
    /// @param nonce The nonce to get the associated word and bit positions
    /// @return wordPos The word position or index into the nonceBitmap
    /// @return bitPos The bit position
    /// @dev The first 248 bits of the nonce value is the index of the desired bitmap
    /// @dev The last 8 bits of the nonce value is the position of the bit in the bitmap
    function bitmapPositions(uint256 nonce) private pure returns (uint256 wordPos, uint256 bitPos) {
        wordPos = uint248(nonce >> 8);
        bitPos = uint8(nonce);
    }

    /// @notice Checks whether a nonce is taken and sets the bit at the bit position in the bitmap at the word position
    /// @param from The address to use the nonce at
    /// @param nonce The nonce to spend
    function _useUnorderedNonce(address from, uint256 nonce) internal {
        (uint256 wordPos, uint256 bitPos) = bitmapPositions(nonce);
        uint256 bit = 1 << bitPos;
        uint256 flipped = nonceBitmap[from][wordPos] ^= bit;

        if (flipped & bit == 0) revert InvalidNonce();
    }
}

EIP712.sol

EIP712.sol
solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;

/// @notice EIP712 helpers for permit2
/// @dev Maintains cross-chain replay protection in the event of a fork
/// @dev Reference: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/EIP712.sol
contract EIP712 {
    // Cache the domain separator as an immutable value, but also store the chain id that it
    // corresponds to, in order to invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
    uint256 private immutable _CACHED_CHAIN_ID;

    bytes32 private constant _HASHED_NAME = keccak256("Permit2");
    bytes32 private constant _TYPE_HASH =
        keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");

    constructor() {
        _CACHED_CHAIN_ID = block.chainid;
        _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME);
    }

    /// @notice Returns the domain separator for the current chain.
    /// @dev Uses cached version if chainid and address are unchanged from construction.
    function DOMAIN_SEPARATOR() public view returns (bytes32) {
        return block.chainid == _CACHED_CHAIN_ID
            ? _CACHED_DOMAIN_SEPARATOR
            : _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME);
    }

    /// @notice Builds a domain separator using the current chainId and contract address.
    function _buildDomainSeparator(bytes32 typeHash, bytes32 nameHash) private view returns (bytes32) {
        return keccak256(abi.encode(typeHash, nameHash, block.chainid, address(this)));
    }

    /// @notice Creates an EIP-712 typed data hash
    function _hashTypedData(bytes32 dataHash) internal view returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR(), dataHash));
    }
}

Allowance

Allowance
solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import {IAllowanceTransfer} from "../interfaces/IAllowanceTransfer.sol";

library Allowance {
    // note if the expiration passed is 0, then it the approval set to the block.timestamp
    uint256 private constant BLOCK_TIMESTAMP_EXPIRATION = 0;

    /// @notice Sets the allowed amount, expiry, and nonce of the spender's permissions on owner's token.
    /// @dev Nonce is incremented.
    /// @dev If the inputted expiration is 0, the stored expiration is set to block.timestamp
    function updateAll(
        IAllowanceTransfer.PackedAllowance storage allowed,
        uint160 amount,
        uint48 expiration,
        uint48 nonce
    ) internal {
        uint48 storedNonce;
        unchecked {
            storedNonce = nonce + 1;
        }

        uint48 storedExpiration = expiration == BLOCK_TIMESTAMP_EXPIRATION ? uint48(block.timestamp) : expiration;

        uint256 word = pack(amount, storedExpiration, storedNonce);
        assembly {
            sstore(allowed.slot, word)
        }
    }

    /// @notice Sets the allowed amount and expiry of the spender's permissions on owner's token.
    /// @dev Nonce does not need to be incremented.
    function updateAmountAndExpiration(
        IAllowanceTransfer.PackedAllowance storage allowed,
        uint160 amount,
        uint48 expiration
    ) internal {
        // If the inputted expiration is 0, the allowance only lasts the duration of the block.
        allowed.expiration = expiration == 0 ? uint48(block.timestamp) : expiration;
        allowed.amount = amount;
    }

    /// @notice Computes the packed slot of the amount, expiration, and nonce that make up PackedAllowance
    function pack(uint160 amount, uint48 expiration, uint48 nonce) internal pure returns (uint256 word) {
        word = (uint256(nonce) << 208) | uint256(expiration) << 160 | amount;
    }
}

PermitHash

PermitHash
solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import {IAllowanceTransfer} from "../interfaces/IAllowanceTransfer.sol";
import {ISignatureTransfer} from "../interfaces/ISignatureTransfer.sol";

library PermitHash {
    bytes32 public constant _PERMIT_DETAILS_TYPEHASH =
        keccak256("PermitDetails(address token,uint160 amount,uint48 expiration,uint48 nonce)");

    bytes32 public constant _PERMIT_SINGLE_TYPEHASH = keccak256(
        "PermitSingle(PermitDetails details,address spender,uint256 sigDeadline)PermitDetails(address token,uint160 amount,uint48 expiration,uint48 nonce)"
    );

    bytes32 public constant _PERMIT_BATCH_TYPEHASH = keccak256(
        "PermitBatch(PermitDetails[] details,address spender,uint256 sigDeadline)PermitDetails(address token,uint160 amount,uint48 expiration,uint48 nonce)"
    );

    bytes32 public constant _TOKEN_PERMISSIONS_TYPEHASH = keccak256("TokenPermissions(address token,uint256 amount)");

    bytes32 public constant _PERMIT_TRANSFER_FROM_TYPEHASH = keccak256(
        "PermitTransferFrom(TokenPermissions permitted,address spender,uint256 nonce,uint256 deadline)TokenPermissions(address token,uint256 amount)"
    );

    bytes32 public constant _PERMIT_BATCH_TRANSFER_FROM_TYPEHASH = keccak256(
        "PermitBatchTransferFrom(TokenPermissions[] permitted,address spender,uint256 nonce,uint256 deadline)TokenPermissions(address token,uint256 amount)"
    );

    string public constant _TOKEN_PERMISSIONS_TYPESTRING = "TokenPermissions(address token,uint256 amount)";

    string public constant _PERMIT_TRANSFER_FROM_WITNESS_TYPEHASH_STUB =
        "PermitWitnessTransferFrom(TokenPermissions permitted,address spender,uint256 nonce,uint256 deadline,";

    string public constant _PERMIT_BATCH_WITNESS_TRANSFER_FROM_TYPEHASH_STUB =
        "PermitBatchWitnessTransferFrom(TokenPermissions[] permitted,address spender,uint256 nonce,uint256 deadline,";

    function hash(IAllowanceTransfer.PermitSingle memory permitSingle) internal pure returns (bytes32) {
        bytes32 permitHash = _hashPermitDetails(permitSingle.details);
        return
            keccak256(abi.encode(_PERMIT_SINGLE_TYPEHASH, permitHash, permitSingle.spender, permitSingle.sigDeadline));
    }

    function hash(IAllowanceTransfer.PermitBatch memory permitBatch) internal pure returns (bytes32) {
        uint256 numPermits = permitBatch.details.length;
        bytes32[] memory permitHashes = new bytes32[](numPermits);
        for (uint256 i = 0; i < numPermits; ++i) {
            permitHashes[i] = _hashPermitDetails(permitBatch.details[i]);
        }
        return keccak256(
            abi.encode(
                _PERMIT_BATCH_TYPEHASH,
                keccak256(abi.encodePacked(permitHashes)),
                permitBatch.spender,
                permitBatch.sigDeadline
            )
        );
    }

    function hash(ISignatureTransfer.PermitTransferFrom memory permit) internal view returns (bytes32) {
        bytes32 tokenPermissionsHash = _hashTokenPermissions(permit.permitted);
        return keccak256(
            abi.encode(_PERMIT_TRANSFER_FROM_TYPEHASH, tokenPermissionsHash, msg.sender, permit.nonce, permit.deadline)
        );
    }

    function hash(ISignatureTransfer.PermitBatchTransferFrom memory permit) internal view returns (bytes32) {
        uint256 numPermitted = permit.permitted.length;
        bytes32[] memory tokenPermissionHashes = new bytes32[](numPermitted);

        for (uint256 i = 0; i < numPermitted; ++i) {
            tokenPermissionHashes[i] = _hashTokenPermissions(permit.permitted[i]);
        }

        return keccak256(
            abi.encode(
                _PERMIT_BATCH_TRANSFER_FROM_TYPEHASH,
                keccak256(abi.encodePacked(tokenPermissionHashes)),
                msg.sender,
                permit.nonce,
                permit.deadline
            )
        );
    }

    function hashWithWitness(
        ISignatureTransfer.PermitTransferFrom memory permit,
        bytes32 witness,
        string calldata witnessTypeString
    ) internal view returns (bytes32) {
        bytes32 typeHash = keccak256(abi.encodePacked(_PERMIT_TRANSFER_FROM_WITNESS_TYPEHASH_STUB, witnessTypeString));

        bytes32 tokenPermissionsHash = _hashTokenPermissions(permit.permitted);
        return keccak256(abi.encode(typeHash, tokenPermissionsHash, msg.sender, permit.nonce, permit.deadline, witness));
    }

    function hashWithWitness(
        ISignatureTransfer.PermitBatchTransferFrom memory permit,
        bytes32 witness,
        string calldata witnessTypeString
    ) internal view returns (bytes32) {
        bytes32 typeHash =
            keccak256(abi.encodePacked(_PERMIT_BATCH_WITNESS_TRANSFER_FROM_TYPEHASH_STUB, witnessTypeString));

        uint256 numPermitted = permit.permitted.length;
        bytes32[] memory tokenPermissionHashes = new bytes32[](numPermitted);

        for (uint256 i = 0; i < numPermitted; ++i) {
            tokenPermissionHashes[i] = _hashTokenPermissions(permit.permitted[i]);
        }

        return keccak256(
            abi.encode(
                typeHash,
                keccak256(abi.encodePacked(tokenPermissionHashes)),
                msg.sender,
                permit.nonce,
                permit.deadline,
                witness
            )
        );
    }

    function _hashPermitDetails(IAllowanceTransfer.PermitDetails memory details) private pure returns (bytes32) {
        return keccak256(abi.encode(_PERMIT_DETAILS_TYPEHASH, details));
    }

    function _hashTokenPermissions(ISignatureTransfer.TokenPermissions memory permitted)
        private
        pure
        returns (bytes32)
    {
        return keccak256(abi.encode(_TOKEN_PERMISSIONS_TYPEHASH, permitted));
    }
}

SignatureVerification

SignatureVerification
solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import {IERC1271} from "../interfaces/IERC1271.sol";

library SignatureVerification {
    /// @notice Thrown when the passed in signature is not a valid length
    error InvalidSignatureLength();

    /// @notice Thrown when the recovered signer is equal to the zero address
    error InvalidSignature();

    /// @notice Thrown when the recovered signer does not equal the claimedSigner
    error InvalidSigner();

    /// @notice Thrown when the recovered contract signature is incorrect
    error InvalidContractSignature();

    bytes32 constant UPPER_BIT_MASK = (0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);

    function verify(bytes calldata signature, bytes32 hash, address claimedSigner) internal view {
        bytes32 r;
        bytes32 s;
        uint8 v;

        if (claimedSigner.code.length == 0) {
            if (signature.length == 65) {
                (r, s) = abi.decode(signature, (bytes32, bytes32));
                v = uint8(signature[64]);
            } else if (signature.length == 64) {
                // EIP-2098
                bytes32 vs;
                (r, vs) = abi.decode(signature, (bytes32, bytes32));
                s = vs & UPPER_BIT_MASK;
                v = uint8(uint256(vs >> 255)) + 27;
            } else {
                revert InvalidSignatureLength();
            }
            address signer = ecrecover(hash, v, r, s);
            if (signer == address(0)) revert InvalidSignature();
            if (signer != claimedSigner) revert InvalidSigner();
        } else {
            bytes4 magicValue = IERC1271(claimedSigner).isValidSignature(hash, signature);
            if (magicValue != IERC1271.isValidSignature.selector) revert InvalidContractSignature();
        }
    }
}

Conclusion

This article explored the Permit2 contract using Bunzz's DeCipher feature. I hope it helped clarify the contract. I plan to continue covering particular NFTs and smart contracts.

I also publish articles about blockchain and AI on my blog and Qiita.

https://chaldene.net/