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.

This article covers ERC7498, OpenSea's proposal for associating NFTs with various digital assets, whether on-chain or off-chain.

This explanation translates, summarizes, and expands on the following proposal.

As of September 7, 2023, ERC7498 was at the Idea stage.

Overview

This specification extends the existing NFT (non-fungible token) standards ERC721 and ERC1155. It aims to associate additional on-chain or off-chain digital assets, such as content and privileges, with NFTs so that owners can redeem them.

In practical terms, NFT owners can receive digital assets associated with their NFTs in addition to holding the NFTs themselves. These digital assets may be stored on-chain or may exist outside the blockchain. For example, an NFT might represent a special game item stored on the game's server. Holding the NFT could entitle its owner to use that item.

The specification aims to provide additional value to NFT owners and make the NFT ecosystem more attractive. NFTs can represent more than digital art or collectibles: holding one may provide access to digital activities and benefits. The proposal seeks to expand NFT use cases and encourage growth in the NFT market.

Motivation

Artists and creators can use NFTs to offer benefits that provide access to digital or physical items. However, standard mechanisms for discovering and redeeming NFTs with these benefits are lacking. The proposed standard has the following objectives.

Discovery

Provide a mechanism for describing benefits and their eligibility requirements. Users and applications can thereby discover NFTs that offer particular benefits.

On-chain information

Track on-chain which NFTs were used to redeem benefits. This improves transaction transparency and verifiability.

Off-chain information

Provide a mechanism linking benefits to real-world product orders. This establishes the relationship between an actual product order and the benefit redeemed.

Trait redemptions

Improve redemption processes involving NFT traits and the consumption of NFTs or their traits. This simplifies trait redemption and improves the user experience.

Redemption Redemption refers to exercising or exchanging a benefit or entitlement. Benefits and rights generally become available when certain conditions are satisfied. Redemption is the act of exercising those rights once the conditions are met.

In blockchain and cryptocurrency applications, digital assets such as NFTs and other tokens can represent redeemable entitlements. For example, a user who owns an NFT may receive associated digital content or benefits if the relevant conditions are satisfied. Claiming such a benefit is called redemption.

Redemption is an important way for digital asset owners to exercise associated rights. Blockchain technology can help make the process transparent and verifiable. In NFT ecosystems, creators can offer collectors special benefits and strengthen their relationship with fans through redemption.

Specification

Tokens must provide the following interface and return true from ERC165 supportsInterface for the four-byte interface ID (the historical draft uses the placeholder 0x12345678).

javascript
interface IERC7501 {
  /* Events */
  event CampaignUpdated(uint256 indexed campaignId, CampaignParams params, string URI);
  event Redemption(uint256 indexed campaignId, bytes32 redemptionHash, uint256[] tokenIds, address redeemedBy);

  /* Structs */
  struct CampaignParams {
      uint32 startTime;
      uint32 endTime;
      uint32 maxCampaignRedemptions;
      address manager; // the address that can modify the campaign
      address signer; // null address means no EIP-712 signature required
      OfferItem[] offer; // items to be minted, can be empty for offchain redeemable
      ConsiderationItem[] consideration; // the items you are transferring to recipient
  }
  struct TraitRedemption {
    uint8 substandard;
    address token;
    uint256 identifier;
    bytes32 traitKey;
    bytes32 traitValue;
    bytes32 substandardValue;
  }

  /* Getters */
  function getCampaign(uint256 campaignId) external view returns (CampaignParams memory params, string memory uri, uint256 totalRedemptions);

  /* Setters */
  function createCampaign(CampaignParams calldata params, string calldata uri) external returns (uint256 campaignId);
  function updateCampaign(uint256 campaignId, CampaignParams calldata params, string calldata uri) external;
  function redeem(uint256[] calldata tokenIds, bytes calldata extraData) external;
}

---

/* Seaport structs, for reference, used in offer/consideration above */
enum ItemType {
    NATIVE,
    ERC20,
    ERC721,
    ERC1155
}
struct OfferItem {
    ItemType itemType;
    address token;
    uint256 identifierOrCriteria;
    uint256 startAmount;
    uint256 endAmount;
}
struct ConsiderationItem extends OfferItem {
    address payable recipient;
    // (note: psuedocode above, can't currently extend structs in solidity)
}
struct SpentItem {
    ItemType itemType;
    address token;
    uint256 identifier;
    uint256 amount;
}

Campaign creation

To create a new campaign, use the createCampaign function. It returns the newly created campaignId and emits CampaignUpdated. Campaign IDs start at 1 and increment.

Campaign updates

Use updateCampaign to update an existing campaign. The function emits CampaignUpdated to reflect the updated information. If an address other than the manager attempts an update, the transaction reverts with NotManager(). A manager wishing to make a campaign immutable can set manager to the zero address.

Offers

Tokens included in the offer parameters must implement the IRedemptionMintable interface to create new items. The interface implementation must be appropriate to the behavior of the particular token. The token must return true from ERC165 supportsInterface for the relevant interface ID (IERC721RedemptionMintable: 0x12345678 or IERC1155RedemptionMintable: 0x12345678 in this draft).

javascript
interface IERC721RedemptionMintable {
  function mintRedemption(address to, SpentItem[] calldata spent) external returns (uint256[] memory tokenIds);
}
interface IERC1155RedemptionMintable {
  function mintRedemption(address to, SpentItem[] calldata spent) external returns (uint256[] memory tokenIds, uint256[] amounts);
}

In the IERC1155RedemptionMintable interface, the tokenIds and amounts arrays must contain the same number of elements.

Consideration

The consideration in RedeemableParams can include any token. The token is transferred to the designated recipient. To send a token to a burn address, the recipient is typically set to 0x000000000000000000000000000000000000dEaD.

Dynamic traits

Tokens supporting trait redemption must implement the EIP-7496 Dynamic Traits interface.

Signer

A signer can be designated to authorize redemption. If the signer is not the zero address, authorization uses EIP712 or ERC1271 signatures.

The EIP712 structure (struct) is as follows.

SignedRedeem(address owner,address redeemedToken, uint256[] tokenIds,bytes32 redemptionHash, uint256 salt)"。 It contains the information authorized by the redemption signature.

Additional redemption data

When calling redeem, the additional data must follow the following layout.

Byte range Value Description / notes
0-32 campaignId
32-64 redemptionHash Hash of the off-chain order ID
64-* TraitRedemption[] Empty array if no trait redemption is performed
*-(+32) salt Only when the signer is not address(0)
*-(+*) signature Only when the signer is not address(0); an EIP-712 or ERC-1271 signature

At redemption, the contract must verify that the campaign remains active, using the same time boundaries as Seaport: startTime <= block.timestamp < endTime. If the campaign is inactive, the operation must revert with NotActive().

Redemption

The redeem function must transfer the tokens specified in consideration. It must also call mintRedemption on the tokens specified in offer. If some of the token IDs supplied to redeem fail validation, the function may process the valid redemptions and skip those that fail. Emit a Redemption event for valid redemptions.

Trait redemptions

Tokens follow the TraitRedemption substandards described below.

Substandard ID Description Substandard value
1 Set a value for traitValue Required previous value; if empty, the existing value must not equal traitValue.
2 Increase traitValue Maximum value
3 Decrease traitValue Minimum value

Maximum campaign redemptions

The token must enforce maxCampaignRedemptions. If a redemption would exceed maxCampaignRedemptions, it must revert with MaxCampaignRedemptionsReached(uint256 total, uint256 max).

Metadata URI

The metadata URI must conform to the following JSON schema.

json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "description": {
      "type": "string",
      "description": "A short summary of the redemption. Markdown is not supported."
    },
    "details": {
      "type": "string",
      "description": "A detailed description of the redemption. Multiple lines or paragraphs are allowed, and Markdown is supported."
    },
    "imageUrls": {
      "type": "string",
      "description": "A list of image URLs for the redemption. The first image is used as a thumbnail. Multiple images are displayed in a carousel. Up to five images are allowed."
    },
    "bannerUrl": {
      "type": "string",
      "description": "Banner image for the redemption."
    },
    "faq": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "question": {
            "type": "string"
          },
          "answer": {
            "type": "string"
          },
          "required": ["question", "answer"]
        }
      }
    },
    "contentLocale": {
      "type": "string",
      "description": "Language tag for the content provided in this metadata."
    },
    "maxRedemptionsPerToken": {
      "type": "string",
      "description": "Maximum redemptions per token. Must be 1 if isBurn is true; otherwise, it may be a value based on trait redemption limits."
    },
    "isBurn": {
      "type": "string",
      "description": "Whether redemption burns the token."
    },
    "uuid": {
      "type": "string",
      "description": "Unique campaign identifier used by a backend to identify a draft campaign when it is published on-chain."
    },
    "productLimitForRedemption": {
      "type": "number",
      "description": "Number of products that may be selected in a single redemption."
    },
    "products": {
      "type": "object",
      "properties": "https://schema.org/Product",
      "required": ["name", "url", "description"]
    },
    "traitRedemptions": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "substandard": {
            "type": "number"
          },
          "token": {
            "type": "string",
            "description": "Token address"
          },
          "traitKey": {
            "type": "string"
          },
          "traitValue": {
            "type": "string"
          },
          "substandardValue": {
            "type": "string"
          }
        },
        "required": [
          "substandard",
          "token",
          "traitKey",
          "traitValue",
          "substandardValue"
        ]
      }
    }
  },
  "required": ["name", "description", "isBurn"]
}

Future SIPs (Standard Improvement Proposals) may extend this schema with additional functionality.

ERC-1155 (semi-fungible tokens)

The standard can also be applied to ERC1155, but redemption applies to the full quantity of tokens associated with a particular token ID. If an ERC1155 contract contains only tokens with a quantity of 1, the specification can be applied directly.

Additional considerations

This Ethereum Improvement Proposal aims to define a consistent standard for token-associated benefits that can be tracked on-chain. Specifically, it provides a mechanism for offering benefits to token owners and managing redemptions on-chain. Applications such as websites can use the standard to discover and display redemption campaigns and allow users to interact with them.

Backward compatibility

This proposal introduces additional functionality rather than requiring changes to existing protocols. Existing token contracts and projects may adopt the new interfaces where their implementations allow it. The proposal represents an effort to support a wider range of benefits in token ecosystems.

Tests

The tests are available in the following GitHub repository.

Reference implementation

javascript
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import {ContractOffererInterface} from "seaport-types/src/interfaces/ContractOffererInterface.sol";
import {SeaportInterface} from "seaport-types/src/interfaces/SeaportInterface.sol";
import {ItemType, OrderType} from "seaport-types/src/lib/ConsiderationEnums.sol";
import {
    AdvancedOrder,
    CriteriaResolver,
    OrderParameters,
    OfferItem,
    ConsiderationItem,
    ReceivedItem,
    Schema,
    SpentItem
} from "seaport-types/src/lib/ConsiderationStructs.sol";
import {ERC20} from "solady/src/tokens/ERC20.sol";
import {ERC721} from "solady/src/tokens/ERC721.sol";
import {ERC1155} from "solady/src/tokens/ERC1155.sol";
import {IERC721Receiver} from "seaport-types/src/interfaces/IERC721Receiver.sol";
import {IERC1155Receiver} from "./interfaces/IERC1155Receiver.sol";
import {IERC721RedemptionMintable} from "./interfaces/IERC721RedemptionMintable.sol";
import {IERC1155RedemptionMintable} from "./interfaces/IERC1155RedemptionMintable.sol";
import {SignedRedeemContractOfferer} from "./lib/SignedRedeemContractOfferer.sol";
import {RedeemableErrorsAndEvents} from "./lib/RedeemableErrorsAndEvents.sol";
import {CampaignParams} from "./lib/RedeemableStructs.sol";

/**
 * @title  RedeemablesContractOfferer
 * @author ryanio, stephankmin
 * @notice A Seaport contract offerer that allows users to burn to redeem off chain redeemables.
 */
contract RedeemableContractOfferer is
    ContractOffererInterface,
    RedeemableErrorsAndEvents,
    SignedRedeemContractOfferer
{
    /// @dev The Seaport address allowed to interact with this contract offerer.
    address internal immutable _SEAPORT;

    /// @dev The conduit address to allow as an operator for this contract for newly minted tokens.
    address internal immutable _CONDUIT;

    bytes32 internal immutable _CONDUIT_KEY;

    /// @dev Counter for next campaign id.
    uint256 private _nextCampaignId = 1;

    /// @dev The campaign parameters by campaign id.
    mapping(uint256 campaignId => CampaignParams params) private _campaignParams;

    /// @dev The campaign URIs by campaign id.
    mapping(uint256 campaignId => string campaignURI) private _campaignURIs;

    /// @dev The total current redemptions by campaign id.
    mapping(uint256 campaignId => uint256 count) private _totalRedemptions;

    constructor(address conduit, bytes32 conduitKey, address seaport) {
        _CONDUIT = conduit;
        _CONDUIT_KEY = conduitKey;
        _SEAPORT = seaport;
    }

    function createCampaign(CampaignParams calldata params, string calldata uri)
        external
        returns (uint256 campaignId)
    {
        // Revert if there are no consideration items, since the redemption should require at least something.
        if (params.consideration.length == 0) revert NoConsiderationItems();

        // Revert if startTime is past endTime.
        if (params.startTime > params.endTime) revert InvalidTime();

        // Revert if any of the consideration item recipients is the zero address. The 0xdead address should be used instead.
        for (uint256 i = 0; i < params.consideration.length;) {
            if (params.consideration[i].recipient == address(0)) {
                revert ConsiderationItemRecipientCannotBeZeroAddress();
            }
            unchecked {
                ++i;
            }
        }

        // Check for and set token approvals for the campaign.
        _setTokenApprovals(params);

        // Set the campaign params for the next campaignId.
        _campaignParams[_nextCampaignId] = params;

        // Set the campaign URI for the next campaignId.
        _campaignURIs[_nextCampaignId] = uri;

        // Set the correct current campaignId to return before incrementing
        // the next campaignId.
        campaignId = _nextCampaignId;

        // Increment the next campaignId.
        _nextCampaignId++;

        emit CampaignUpdated(campaignId, params, _campaignURIs[campaignId]);
    }

    function updateCampaign(uint256 campaignId, CampaignParams calldata params, string calldata uri) external {
        if (campaignId == 0 || campaignId >= _nextCampaignId) {
            revert InvalidCampaignId();
        }

        // Revert if there are no consideration items, since the redemption should require at least something.
        if (params.consideration.length == 0) revert NoConsiderationItems();

        // Revert if startTime is past endTime.
        if (params.startTime > params.endTime) revert InvalidTime();

        // Revert if msg.sender is not the manager.
        address existingManager = _campaignParams[campaignId].manager;
        if (params.manager != msg.sender && (existingManager != address(0) && existingManager != params.manager)) {
            revert NotManager();
        }

        // Revert if any of the consideration item recipients is the zero address. The 0xdead address should be used instead.
        for (uint256 i = 0; i < params.consideration.length;) {
            if (params.consideration[i].recipient == address(0)) {
                revert ConsiderationItemRecipientCannotBeZeroAddress();
            }
            unchecked {
                ++i;
            }
        }

        // Check for and set token approvals for the campaign.
        _setTokenApprovals(params);

        // Set the campaign params for the given campaignId.
        _campaignParams[campaignId] = params;

        // Update campaign uri if it was provided.
        if (bytes(uri).length != 0) {
            _campaignURIs[campaignId] = uri;
        }

        emit CampaignUpdated(campaignId, params, _campaignURIs[campaignId]);
    }

    function _setTokenApprovals(CampaignParams memory params) internal {
        // Allow Seaport and the conduit as operators on behalf of this contract for offer items to be minted and transferred.
        for (uint256 i = 0; i < params.offer.length;) {
            // Native items do not need to be approved.
            if (params.offer[i].itemType == ItemType.NATIVE) {
                revert InvalidNativeOfferItem();
            }
            // ERC721 and ERC1155 have the same function signatures for isApprovedForAll and setApprovalForAll.
            else if (params.offer[i].itemType >= ItemType.ERC721) {
                if (!ERC721(params.offer[i].token).isApprovedForAll(_CONDUIT, address(this))) {
                    ERC721(params.offer[i].token).setApprovalForAll(_CONDUIT, true);
                }
                // Set the maximum approval amount for ERC20 tokens.
            } else {
                ERC20(params.offer[i].token).approve(_CONDUIT, type(uint256).max);
            }
            unchecked {
                ++i;
            }
        }

        // Allow Seaport and the conduit as operators on behalf of this contract for consideration items to be transferred in the onReceived hooks.
        for (uint256 i = 0; i < params.consideration.length;) {
            // ERC721 and ERC1155 have the same function signatures for isApprovedForAll and setApprovalForAll.
            if (params.consideration[i].itemType >= ItemType.ERC721) {
                if (!ERC721(params.consideration[i].token).isApprovedForAll(_CONDUIT, address(this))) {
                    ERC721(params.consideration[i].token).setApprovalForAll(_CONDUIT, true);
                }
                // Set the maximum approval amount for ERC20 tokens.
            } else {
                ERC20(params.consideration[i].token).approve(_CONDUIT, type(uint256).max);
            }
            unchecked {
                ++i;
            }
        }
    }

    function updateCampaignURI(uint256 campaignId, string calldata uri) external {
        CampaignParams storage params = _campaignParams[campaignId];

        if (params.manager != msg.sender) revert NotManager();

        _campaignURIs[campaignId] = uri;

        emit CampaignUpdated(campaignId, params, uri);
    }

    /**
     * @dev Generates an order with the specified minimum and maximum spent
     *      items, and optional context (supplied as extraData).
     *
     * @param fulfiller        The address of the fulfiller.
     * @param minimumReceived  The minimum items that the caller must receive.
     * @param maximumSpent     The maximum items the caller is willing to spend.
     * @param context          Additional context of the order.
     *
     * @return offer         A tuple containing the offer items.
     * @return consideration An array containing the consideration items.
     */
    function generateOrder(
        address fulfiller,
        SpentItem[] calldata minimumReceived,
        SpentItem[] calldata maximumSpent,
        bytes calldata context // encoded based on the schemaID
    ) external override returns (SpentItem[] memory offer, ReceivedItem[] memory consideration) {
        // Derive the offer and consideration with effects.
        (offer, consideration) = _createOrder(fulfiller, minimumReceived, maximumSpent, context, true);
    }

    /**
     * @dev Ratifies an order with the specified offer, consideration, and
     *      optional context (supplied as extraData).
     *
     * @custom:param offer         The offer items.
     * @custom:param consideration The consideration items.
     * @custom:param context       Additional context of the order.
     * @custom:param orderHashes   The hashes to ratify.
     * @custom:param contractNonce The nonce of the contract.
     *
     * @return ratifyOrderMagicValue The magic value returned by the contract
     *                               offerer.
     */
    function ratifyOrder(
        SpentItem[] calldata, /* offer */
        ReceivedItem[] calldata, /* consideration */
        bytes calldata, /* context */ // encoded based on the schemaID
        bytes32[] calldata, /* orderHashes */
        uint256 /* contractNonce */
    ) external pure override returns (bytes4) {
        assembly {
            // Return the RatifyOrder magic value.
            mstore(0, 0xf4dd92ce)
            return(0x1c, 32)
        }
    }

    /**
     * @dev View function to preview an order generated in response to a minimum
     *      set of received items, maximum set of spent items, and context
     *      (supplied as extraData).
     *
     * @custom:param caller      The address of the caller (e.g. Seaport).
     * @param fulfiller          The address of the fulfiller (e.g. the account
     *                           calling Seaport).
     * @param minimumReceived    The minimum items that the caller is willing to
     *                           receive.
     * @param maximumSpent       The maximum items caller is willing to spend.
     * @param context            Additional context of the order.
     *
     * @return offer         A tuple containing the offer items.
     * @return consideration A tuple containing the consideration items.
     */
    function previewOrder(
        address, /* caller */
        address fulfiller,
        SpentItem[] calldata minimumReceived,
        SpentItem[] calldata maximumSpent,
        bytes calldata context // encoded based on the schemaID
    ) external view override returns (SpentItem[] memory offer, ReceivedItem[] memory consideration) {
        // To avoid the solidity compiler complaining about calling a non-view
        // function here (_createOrder), we will cast it as a view and use it.
        // This is okay because we are not modifying any state when passing
        // withEffects=false.
        function(
            address,
            SpentItem[] memory,
            SpentItem[] memory,
            bytes calldata,
            bool
        ) internal view returns (SpentItem[] memory, ReceivedItem[] memory) fn;
        function(
            address,
            SpentItem[] memory,
            SpentItem[] memory,
            bytes calldata,
            bool
        )
            internal
            returns (
                SpentItem[] memory,
                ReceivedItem[] memory
            ) fn2 = _createOrder;
        assembly {
            fn := fn2
        }

        // Derive the offer and consideration without effects.
        (offer, consideration) = fn(fulfiller, minimumReceived, maximumSpent, context, false);
    }

    /**
     * @dev Gets the metadata for this contract offerer.
     *
     * @return name    The name of the contract offerer.
     * @return schemas The schemas supported by the contract offerer.
     */
    function getSeaportMetadata()
        external
        pure
        override
        returns (
            string memory name,
            Schema[] memory schemas // map to Seaport Improvement Proposal IDs
        )
    {
        schemas = new Schema[](0);
        return ("RedeemablesContractOfferer", schemas);
    }

    function supportsInterface(bytes4 interfaceId) external view virtual returns (bool) {
        return interfaceId == type(ContractOffererInterface).interfaceId
            || interfaceId == type(IERC721Receiver).interfaceId || interfaceId == type(IERC1155Receiver).interfaceId;
    }

    function _createOrder(
        address fulfiller,
        SpentItem[] memory minimumReceived,
        SpentItem[] memory maximumSpent,
        bytes calldata context,
        bool withEffects
    ) internal returns (SpentItem[] memory offer, ReceivedItem[] memory consideration) {
        // Get the campaign.
        uint256 campaignId = uint256(bytes32(context[0:32]));
        CampaignParams storage params = _campaignParams[campaignId];

        // Declare an error buffer; first check is that caller is Seaport or the token contract.
        uint256 errorBuffer = _cast(msg.sender != _SEAPORT && msg.sender != params.consideration[0].token);

        // Check the redemption is active.
        errorBuffer |= _cast(_isInactive(params.startTime, params.endTime)) << 1;

        // Check max total redemptions would not be exceeded.
        errorBuffer |= _cast(_totalRedemptions[campaignId] + maximumSpent.length > params.maxCampaignRedemptions) << 2;

        // Get the redemption hash.
        bytes32 redemptionHash = bytes32(context[32:64]);

        // Check the signature is valid if required.
        if (params.signer != address(0)) {
            uint256 salt = uint256(bytes32(context[64:96]));
            bytes memory signature = context[96:];
            // _verifySignature will revert if the signature is invalid or digest is already used.
            _verifySignature(params.signer, fulfiller, maximumSpent, redemptionHash, salt, signature, withEffects);
        }

        if (errorBuffer > 0) {
            if (errorBuffer << 255 != 0) {
                revert InvalidCaller(msg.sender);
            } else if (errorBuffer << 254 != 0) {
                revert NotActive(block.timestamp, params.startTime, params.endTime);
            } else if (errorBuffer << 253 != 0) {
                revert MaxCampaignRedemptionsReached(
                    _totalRedemptions[campaignId] + maximumSpent.length, params.maxCampaignRedemptions
                );
                // TODO: do we need this error?
                // } else if (errorBuffer << 252 != 0) {
                //     revert InvalidConsiderationLength(
                //         maximumSpent.length,
                //         params.consideration.length
                //     );
            } else if (errorBuffer << 252 != 0) {
                revert InvalidConsiderationItem(maximumSpent[0].token, params.consideration[0].token);
            } else {
                // todo more validation errors
            }
        }

        // Set the offer from the params.
        offer = new SpentItem[](params.offer.length);
        for (uint256 i = 0; i < params.offer.length;) {
            OfferItem memory offerItem = params.offer[i];

            uint256 tokenId = IERC721RedemptionMintable(offerItem.token).mintRedemption(address(this), maximumSpent);

            // Set the itemType without criteria.
            ItemType itemType = offerItem.itemType == ItemType.ERC721_WITH_CRITERIA
                ? ItemType.ERC721
                : offerItem.itemType == ItemType.ERC1155_WITH_CRITERIA ? ItemType.ERC1155 : offerItem.itemType;

            offer[i] = SpentItem({
                itemType: itemType,
                token: offerItem.token,
                identifier: tokenId,
                amount: offerItem.startAmount // TODO: do we need to calculate amount based on timestamp?
            });
            unchecked {
                ++i;
            }
        }

        // Set the consideration from the params.
        consideration = new ReceivedItem[](params.consideration.length);
        for (uint256 i = 0; i < params.consideration.length;) {
            ConsiderationItem memory considerationItem = params.consideration[i];

            // TODO: make helper getItemTypeWithoutCriteria
            ItemType itemType;
            uint256 identifier;

            // If consideration item is wildcard criteria item, set itemType to ERC721
            // and identifier to the maximumSpent item identifier.
            if (
                (considerationItem.itemType == ItemType.ERC721_WITH_CRITERIA)
                    && (considerationItem.identifierOrCriteria == 0)
            ) {
                itemType = ItemType.ERC721;
                identifier = maximumSpent[i].identifier;
            } else if (
                (considerationItem.itemType == ItemType.ERC1155_WITH_CRITERIA)
                    && (considerationItem.identifierOrCriteria == 0)
            ) {
                itemType = ItemType.ERC1155;
                identifier = maximumSpent[i].identifier;
            } else {
                itemType = considerationItem.itemType;
                identifier = considerationItem.identifierOrCriteria;
            }

            consideration[i] = ReceivedItem({
                itemType: itemType,
                token: considerationItem.token,
                identifier: identifier,
                amount: considerationItem.startAmount,
                recipient: considerationItem.recipient
            });
            unchecked {
                ++i;
            }
        }

        // If withEffects is true then make state changes.
        if (withEffects) {
            // Increment total redemptions.
            _totalRedemptions[campaignId] += maximumSpent.length;

            SpentItem[] memory spent = new SpentItem[](consideration.length);
            for (uint256 i = 0; i < consideration.length;) {
                spent[i] = SpentItem({
                    itemType: consideration[i].itemType,
                    token: consideration[i].token,
                    identifier: consideration[i].identifier,
                    amount: consideration[i].amount
                });
                unchecked {
                    ++i;
                }
            }

            // Emit Redemption event.
            emit Redemption(campaignId, redemptionHash);
        }
    }

    function onERC721Received(
        address,
        /* operator */
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4) {
        if (from == address(0)) {
            return IERC721Receiver.onERC721Received.selector;
        }

        // Get the campaign.
        uint256 campaignId = uint256(bytes32(data[0:32]));
        CampaignParams storage params = _campaignParams[campaignId];

        OfferItem[] memory offer = new OfferItem[](1);
        offer[0] = OfferItem({
            itemType: ItemType.ERC721_WITH_CRITERIA,
            token: params.offer[0].token,
            identifierOrCriteria: 0,
            startAmount: 1,
            endAmount: 1
        });

        ConsiderationItem[] memory consideration = new ConsiderationItem[](1);
        consideration[0] = ConsiderationItem({
            itemType: ItemType.ERC721,
            token: msg.sender,
            identifierOrCriteria: tokenId,
            startAmount: 1,
            endAmount: 1,
            recipient: payable(address(0x000000000000000000000000000000000000dEaD))
        });

        OrderParameters memory parameters = OrderParameters({
            offerer: address(this),
            zone: address(0),
            offer: offer,
            consideration: consideration,
            orderType: OrderType.CONTRACT,
            startTime: block.timestamp,
            endTime: block.timestamp + 10, // TODO: fix
            zoneHash: bytes32(0), // TODO: fix
            salt: uint256(0), // TODO: fix
            conduitKey: _CONDUIT_KEY,
            totalOriginalConsiderationItems: consideration.length
        });

        AdvancedOrder memory order =
            AdvancedOrder({parameters: parameters, numerator: 1, denominator: 1, signature: "", extraData: data});

        SeaportInterface(_SEAPORT).fulfillAdvancedOrder(order, new CriteriaResolver[](0), _CONDUIT_KEY, from);

        return IERC721Receiver.onERC721Received.selector;
    }

    function onERC1155Received(
        address,
        /* operator */
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4) {
        if (from == address(0)) {
            return IERC1155Receiver.onERC1155Received.selector;
        }

        // Get the campaign.
        uint256 campaignId = uint256(bytes32(data[0:32]));
        CampaignParams storage params = _campaignParams[campaignId];

        SpentItem[] memory minimumReceived = new SpentItem[](1);
        minimumReceived[0] = SpentItem({
            itemType: ItemType.ERC721,
            token: params.offer[0].token,
            identifier: params.offer[0].identifierOrCriteria,
            amount: params.offer[0].startAmount
        });

        SpentItem[] memory maximumSpent = new SpentItem[](1);
        maximumSpent[0] = SpentItem({itemType: ItemType.ERC1155, token: msg.sender, identifier: id, amount: value});

        // _createOrder will revert if any validations fail.
        _createOrder(from, minimumReceived, maximumSpent, data, true);

        // Transfer the token to the consideration item recipient.
        address recipient = _getConsiderationRecipient(params.consideration, msg.sender);
        ERC1155(msg.sender).safeTransferFrom(address(this), recipient, id, value, "");

        // Transfer the newly minted token to the fulfiller.
        ERC721(params.offer[0].token).safeTransferFrom(address(this), from, id, "");

        return IERC1155Receiver.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address, /* operator */
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4) {
        if (from == address(0)) {
            return IERC1155Receiver.onERC1155BatchReceived.selector;
        }

        if (ids.length != values.length) revert RedeemMismatchedLengths();

        // Get the campaign.
        uint256 campaignId = uint256(bytes32(data[0:32]));
        CampaignParams storage params = _campaignParams[campaignId];

        SpentItem[] memory minimumReceived = new SpentItem[](1);
        minimumReceived[0] = SpentItem({
            itemType: ItemType.ERC721,
            token: params.offer[0].token,
            identifier: params.offer[0].identifierOrCriteria,
            amount: params.offer[0].startAmount
        });

        SpentItem[] memory maximumSpent = new SpentItem[](ids.length);
        for (uint256 i = 0; i < ids.length;) {
            maximumSpent[i] =
                SpentItem({itemType: ItemType.ERC1155, token: msg.sender, identifier: ids[i], amount: values[i]});
            unchecked {
                ++i;
            }
        }

        // _createOrder will revert if any validations fail.
        _createOrder(from, minimumReceived, maximumSpent, data, true);

        // Transfer the tokens to the consideration item recipient.
        address recipient = _getConsiderationRecipient(params.consideration, msg.sender);
        ERC1155(msg.sender).safeBatchTransferFrom(address(this), recipient, ids, values, "");

        // Transfer the newly minted token to the fulfiller.
        ERC721(params.offer[0].token).safeTransferFrom(address(this), from, ids[0]);

        return IERC1155Receiver.onERC1155BatchReceived.selector;
    }

    function getCampaign(uint256 campaignId)
        external
        view
        returns (CampaignParams memory params, string memory uri, uint256 totalRedemptions)
    {
        if (campaignId >= _nextCampaignId) revert InvalidCampaignId();
        params = _campaignParams[campaignId];
        uri = _campaignURIs[campaignId];
        totalRedemptions = _totalRedemptions[campaignId];
    }

    function _getConsiderationRecipient(ConsiderationItem[] storage consideration, address token)
        internal
        view
        returns (address)
    {
        for (uint256 i = 0; i < consideration.length;) {
            if (consideration[i].token == token) {
                return consideration[i].recipient;
            }
            unchecked {
                ++i;
            }
        }
        revert ConsiderationRecipientNotFound(token);
    }

    function _isInactive(uint256 startTime, uint256 endTime) internal view returns (bool inactive) {
        // Using the same check for time boundary from Seaport.
        // startTime <= block.timestamp < endTime
        assembly {
            inactive := or(iszero(gt(endTime, timestamp())), gt(startTime, timestamp()))
        }
    }

    function _isValidTokenAddress(CampaignParams memory params, address token) internal pure returns (bool valid) {
        for (uint256 i = 0; i < params.consideration.length;) {
            if (params.consideration[i].token == token) {
                valid = true;
                break;
            }
            unchecked {
                ++i;
            }
        }
    }

    /**
     * @notice Internal utility function to remove a uint from a supplied
     *         enumeration.
     *
     * @param toRemove    The uint to remove.
     * @param enumeration The enumerated uints to parse.
     */
    function _removeFromEnumeration(uint256 toRemove, uint256[] storage enumeration) internal {
        // Cache the length.
        uint256 enumerationLength = enumeration.length;
        for (uint256 i = 0; i < enumerationLength;) {
            // Check if the enumerated element is the one we are deleting.
            if (enumeration[i] == toRemove) {
                // Swap with the last element.
                enumeration[i] = enumeration[enumerationLength - 1];
                // Delete the (now duplicated) last element.
                enumeration.pop();
                // Exit the loop.
                break;
            }
            unchecked {
                ++i;
            }
        }
    }

    /**
     * @notice Internal utility function to cast uint types to address
     *         to dedupe the need for multiple implementations of
     *         `_removeFromEnumeration`.
     *
     * @param fnIn The fn with uint input.
     *
     * @return fnOut The fn with address input.
     */
    function _asAddressArray(function(uint256, uint256[] storage) internal fnIn)
        internal
        pure
        returns (function(address, address[] storage) internal fnOut)
    {
        assembly {
            fnOut := fnIn
        }
    }

    /**
     * @dev Internal pure function to cast a `bool` value to a `uint256` value.
     *
     * @param b The `bool` value to cast.
     *
     * @return u The `uint256` value.
     */
    function _cast(bool b) internal pure returns (uint256 u) {
        assembly {
            u := b
        }
    }
}

_SEAPORT

javascript
address internal immutable _SEAPORT;

Overview Seaport address. The address of Seaport authorized to interact with this contract.

Details Allows communication with the separate Seaport contract. Seaport can interact with this contract to perform operations such as processing redemptions.


_CONDUIT

javascript
address internal immutable _CONDUIT;

Overview Conduit address. The address approved as an operator for newly minted tokens.

Details Specifies the address authorized to operate on newly minted tokens. The Conduit can operate on tokens involved in processing redemptions.


_CONDUIT_KEY

javascript
bytes32 internal immutable _CONDUIT_KEY;

Overview The Conduit key used by this contract.

Details A key identifying the relevant Conduit. The key is used when routing token operations through the Conduit.


_nextCampaignId

javascript
uint256 private _nextCampaignId = 1;

Overview Counter for the next available campaign ID.

Details Tracks the campaign ID to assign automatically to the next campaign. The counter increments by one each time a new campaign is created.


_campaignParams

javascript
mapping(uint256 campaignId => CampaignParams params) private _campaignParams;

Overview A mapping storing campaign parameters by campaign ID.

Details The campaign ID is the key, and the associated campaign parameters are the value.


_campaignURIs

javascript
mapping(uint256 campaignId => string campaignURI) private _campaignURIs;

Overview A mapping storing campaign URIs by campaign ID.

Details The campaign ID is the key, and the URI string is the value.


_totalRedemptions

javascript
mapping(uint256 campaignId => uint256 count) private _totalRedemptions;

Overview A mapping storing total redemptions by campaign ID.

Details The campaign ID is the key, and the redemption count is the value.


constructor

javascript
constructor(address conduit, bytes32 conduitKey, address seaport) {
    _CONDUIT = conduit;
    _CONDUIT_KEY = conduitKey;
    _SEAPORT = seaport;
}

Overview The contract constructor. Initializes the contract and sets the required addresses.

Parameters

  • conduit
    • Address of another contract with which this contract integrates.
  • conduitKey
    • Key used by the contract.
  • seaport
    • Address of the contract used through the relevant interface.

createCampaign

javascript
function createCampaign(CampaignParams calldata params, string calldata uri)
        external
        returns (uint256 campaignId)
    {
        // Revert if there are no consideration items, since the redemption should require at least something.
        if (params.consideration.length == 0) revert NoConsiderationItems();

        // Revert if startTime is past endTime.
        if (params.startTime > params.endTime) revert InvalidTime();

        // Revert if any of the consideration item recipients is the zero address. The 0xdead address should be used instead.
        for (uint256 i = 0; i < params.consideration.length;) {
            if (params.consideration[i].recipient == address(0)) {
                revert ConsiderationItemRecipientCannotBeZeroAddress();
            }
            unchecked {
                ++i;
            }
        }

        // Check for and set token approvals for the campaign.
        _setTokenApprovals(params);

        // Set the campaign params for the next campaignId.
        _campaignParams[_nextCampaignId] = params;

        // Set the campaign URI for the next campaignId.
        _campaignURIs[_nextCampaignId] = uri;

        // Set the correct current campaignId to return before incrementing
        // the next campaignId.
        campaignId = _nextCampaignId;

        // Increment the next campaignId.
        _nextCampaignId++;

        emit CampaignUpdated(campaignId, params, _campaignURIs[campaignId]);
    }

Overview Creates a new campaign.

Details Creates a campaign using the specified parameters and URI.

Parameters

  • params
    • Data structure specifying campaign parameters.
  • uri
    • URI associated with the campaign.

Return value Returns campaignId, the unique ID of the created campaign.


updateCampaign

javascript
function updateCampaign(uint256 campaignId, CampaignParams calldata params, string calldata uri) external {
        if (campaignId == 0 || campaignId >= _nextCampaignId) {
            revert InvalidCampaignId();
        }

        // Revert if there are no consideration items, since the redemption should require at least something.
        if (params.consideration.length == 0) revert NoConsiderationItems();

        // Revert if startTime is past endTime.
        if (params.startTime > params.endTime) revert InvalidTime();

        // Revert if msg.sender is not the manager.
        address existingManager = _campaignParams[campaignId].manager;
        if (params.manager != msg.sender && (existingManager != address(0) && existingManager != params.manager)) {
            revert NotManager();
        }

        // Revert if any of the consideration item recipients is the zero address. The 0xdead address should be used instead.
        for (uint256 i = 0; i < params.consideration.length;) {
            if (params.consideration[i].recipient == address(0)) {
                revert ConsiderationItemRecipientCannotBeZeroAddress();
            }
            unchecked {
                ++i;
            }
        }

        // Check for and set token approvals for the campaign.
        _setTokenApprovals(params);

        // Set the campaign params for the given campaignId.
        _campaignParams[campaignId] = params;

        // Update campaign uri if it was provided.
        if (bytes(uri).length != 0) {
            _campaignURIs[campaignId] = uri;
        }

        emit CampaignUpdated(campaignId, params, _campaignURIs[campaignId]);
}

Overview Updates an existing campaign.

Details Changes the specified campaign's parameters and URI.

Parameters

  • campaignId
    • Unique ID of the campaign to update.
  • params
    • Data structure specifying the new campaign parameters.
  • uri
    • New URI to associate with the campaign.

_setTokenApprovals

javascript
function _setTokenApprovals(CampaignParams memory params) internal {
        // Allow Seaport and the conduit as operators on behalf of this contract for offer items to be minted and transferred.
        for (uint256 i = 0; i < params.offer.length;) {
            // Native items do not need to be approved.
            if (params.offer[i].itemType == ItemType.NATIVE) {
                revert InvalidNativeOfferItem();
            }
            // ERC721 and ERC1155 have the same function signatures for isApprovedForAll and setApprovalForAll.
            else if (params.offer[i].itemType >= ItemType.ERC721) {
                if (!ERC721(params.offer[i].token).isApprovedForAll(_CONDUIT, address(this))) {
                    ERC721(params.offer[i].token).setApprovalForAll(_CONDUIT, true);
                }
                // Set the maximum approval amount for ERC20 tokens.
            } else {
                ERC20(params.offer[i].token).approve(_CONDUIT, type(uint256).max);
            }
            unchecked {
                ++i;
            }
        }

        // Allow Seaport and the conduit as operators on behalf of this contract for consideration items to be transferred in the onReceived hooks.
        for (uint256 i = 0; i < params.consideration.length;) {
            // ERC721 and ERC1155 have the same function signatures for isApprovedForAll and setApprovalForAll.
            if (params.consideration[i].itemType >= ItemType.ERC721) {
                if (!ERC721(params.consideration[i].token).isApprovedForAll(_CONDUIT, address(this))) {
                    ERC721(params.consideration[i].token).setApprovalForAll(_CONDUIT, true);
                }
                // Set the maximum approval amount for ERC20 tokens.
            } else {
                ERC20(params.consideration[i].token).approve(_CONDUIT, type(uint256).max);
            }
            unchecked {
                ++i;
            }
        }
}

Overview Sets approvals for tokens associated with a campaign.

Details Processes token approvals for offer and consideration items.

Parameters

  • params
    • Data structure specifying campaign parameters.

updateCampaignURI

javascript
function updateCampaignURI(uint256 campaignId, string calldata uri) external {
        CampaignParams storage params = _campaignParams[campaignId];

        if (params.manager != msg.sender) revert NotManager();

        _campaignURIs[campaignId] = uri;

        emit CampaignUpdated(campaignId, params, uri);
}

Overview Updates the URI associated with the specified campaign.

Parameters

  • campaignId
    • Unique ID of the campaign to update.
  • uri
    • New URI to associate with the campaign.

generateOrder

javascript
function generateOrder(
        address fulfiller,
        SpentItem[] calldata minimumReceived,
        SpentItem[] calldata maximumSpent,
        bytes calldata context // encoded based on the schemaID
    ) external override returns (SpentItem[] memory offer, ReceivedItem[] memory consideration) {
        // Derive the offer and consideration with effects.
        (offer, consideration) = _createOrder(fulfiller, minimumReceived, maximumSpent, context, true);
}

Overview Generates an order.

Details Specifies minimum and maximum spent items and supplies optional context information.

Parameters

  • fulfiller
    • Address fulfilling the order.
  • minimumReceived
    • Data structure specifying the minimum items to receive.
  • maximumSpent
    • Data structure specifying the maximum items that may be spent.
  • context
    • Additional context information encoded according to the schema ID.

Return value

  • offer
    • Array of offer items in the order.
  • consideration
    • Array of consideration items in the order.

ratifyOrder

javascript
function ratifyOrder(
        SpentItem[] calldata, /* offer */
        ReceivedItem[] calldata, /* consideration */
        bytes calldata, /* context */ // encoded based on the schemaID
        bytes32[] calldata, /* orderHashes */
        uint256 /* contractNonce */
    ) external pure override returns (bytes4) {
        assembly {
            // Return the RatifyOrder magic value.
            mstore(0, 0xf4dd92ce)
            return(0x1c, 32)
        }
}

Overview Ratifies an order using the specified offer, consideration, and optional context.

Parameters

  • offer
    • Array containing the offered items.
  • consideration
    • Array containing the consideration items.
  • context
    • Encoded additional information about the order.
  • orderHashes
    • Array of hashes for the orders being ratified.
  • contractNonce
    • Contract nonce.

Return value

  • ratifyOrderMagicValue
    • Magic value returned by the contract offerer.

previewOrder

javascript
function previewOrder(
        address, /* caller */
        address fulfiller,
        SpentItem[] calldata minimumReceived,
        SpentItem[] calldata maximumSpent,
        bytes calldata context // encoded based on the schemaID
    ) external view override returns (SpentItem[] memory offer, ReceivedItem[] memory consideration) {
        // To avoid the solidity compiler complaining about calling a non-view
        // function here (_createOrder), we will cast it as a view and use it.
        // This is okay because we are not modifying any state when passing
        // withEffects=false.
        function(
            address,
            SpentItem[] memory,
            SpentItem[] memory,
            bytes calldata,
            bool
        ) internal view returns (SpentItem[] memory, ReceivedItem[] memory) fn;
        function(
            address,
            SpentItem[] memory,
            SpentItem[] memory,
            bytes calldata,
            bool
        )
            internal
            returns (
                SpentItem[] memory,
                ReceivedItem[] memory
            ) fn2 = _createOrder;
        assembly {
            fn := fn2
        }

        // Derive the offer and consideration without effects.
        (offer, consideration) = fn(fulfiller, minimumReceived, maximumSpent, context, false);
    }

Overview Previews an order generated from the minimum received items, maximum spent items, and context.

Parameters

  • caller
    • Calling address (for example, the Seaport address).
  • fulfiller
    • Fulfiller address (for example, the account calling Seaport).
  • minimumReceived
    • Minimum received items.
  • maximumSpent
    • Maximum spent items.
  • context
    • Encoded additional information about the order.

Return value

  • offer
    • Array containing the offered items.
  • consideration
    • Array containing the consideration items.

getSeaportMetadata

javascript
function getSeaportMetadata()
        external
        pure
        override
        returns (
            string memory name,
            Schema[] memory schemas // map to Seaport Improvement Proposal IDs
        )
    {
        schemas = new Schema[](0);
        return ("RedeemablesContractOfferer", schemas);
}

Overview Retrieves metadata for the contract offerer.

Parameters

  • name
    • Name of the contract offerer.
  • schemas
    • Array of schemas supported by the contract offerer.

Return value

  • name
    • Name of the contract offerer.
  • schemas
    • Array of schemas supported by the contract offerer.

supportsInterface

javascript
function supportsInterface(bytes4 interfaceId) external view virtual returns (bool) {
        return interfaceId == type(ContractOffererInterface).interfaceId
            || interfaceId == type(IERC721Receiver).interfaceId || interfaceId == type(IERC1155Receiver).interfaceId;
}

Overview Checks whether a specified interface is supported.

Details

  • Supported interface IDs include the contract offerer interface, IERC721Receiver, and IERC1155Receiver.

Parameters

  • interfaceId
    • Interface ID to check.

Return value

  • Returns true if the interface is supported, and false otherwise.

_createOrder

javascript
function _createOrder(
    address fulfiller,
    SpentItem[] memory minimumReceived,
    SpentItem[] memory maximumSpent,
    bytes calldata context,
    bool withEffects
) internal returns (SpentItem[] memory offer, ReceivedItem[] memory consideration) {
    // Retrieve the campaign.
    uint256 campaignId = uint256(bytes32(context[0:32]));
    CampaignParams storage params = _campaignParams[campaignId];

    // Declare the error buffer. First check that the caller is Seaport or the token contract.
    uint256 errorBuffer = _cast(msg.sender != _SEAPORT && msg.sender != params.consideration[0].token);

    // Verify that redemption is active.
    errorBuffer |= _cast(_isInactive(params.startTime, params.endTime)) << 1;

    // Verify that the maximum total redemption count is not exceeded.
    errorBuffer |= _cast(_totalRedemptions[campaignId] + maximumSpent.length > params.maxCampaignRedemptions) << 2;

    // Retrieve the redemption hash.
    bytes32 redemptionHash = bytes32(context[32:64]);

    // Verify the signature if required.
    if (params.signer != address(0)) {
        uint256 salt = uint256(bytes32(context[64:96]));
        bytes memory signature = context[96:];
        // _verifySignature reverts if the signature is invalid or the digest has already been used.
        _verifySignature(params.signer, fulfiller, maximumSpent, redemptionHash, salt, signature, withEffects);
    }

    if (errorBuffer > 0) {
        if (errorBuffer << 255 != 0) {
            revert InvalidCaller(msg.sender);
        } else if (errorBuffer << 254 != 0) {
            revert NotActive(block.timestamp, params.startTime, params.endTime);
        } else if (errorBuffer << 253 != 0) {
            revert MaxCampaignRedemptionsReached(
                _totalRedemptions[campaignId] + maximumSpent.length, params.maxCampaignRedemptions
            );
            // TODO: Is this error necessary?
            // } else if (errorBuffer << 252 != 0) {
            //     revert InvalidConsiderationLength(
            //         maximumSpent.length,
            //         params.consideration.length
            //     );
        } else if (errorBuffer << 252 != 0) {
            revert InvalidConsiderationItem(maximumSpent[0].token, params.consideration[0].token);
        } else {
            // Additional validation errors are planned.
        }
    }

    // Set the offer from the parameters.
    offer = new SpentItem[](params.offer.length);
    for (uint256 i = 0; i < params.offer.length;) {
        OfferItem memory offerItem = params.offer[i];

        uint256 tokenId = IERC721RedemptionMintable(offerItem.token).mintRedemption(address(this), maximumSpent);

        // Set the item type for items without criteria.
        ItemType itemType = offerItem.itemType == ItemType.ERC721_WITH_CRITERIA
            ? ItemType.ERC721
            : offerItem.itemType == ItemType.ERC1155_WITH_CRITERIA ? ItemType.ERC1155 : offerItem.itemType;

        offer[i] = SpentItem({
            itemType: itemType,
            token: offerItem.token,
            identifier: tokenId,
            amount: offerItem.startAmount // TODO: Should the amount be calculated based on the timestamp?
        });
        unchecked {
            ++i;
        }
    }

    // Set the consideration from the parameters.
    consideration = new ReceivedItem[](params.consideration.length);
    for (uint256 i = 0; i < params.consideration.length;) {
        ConsiderationItem memory considerationItem = params.consideration[i];

        // TODO: Create the getItemTypeWithoutCriteria helper.
        ItemType itemType;
        uint256 identifier;

        // If the consideration item has wildcard criteria, set its item type to ERC721
        // and set the identifier to the identifier of the maximumSpent item.
        if (
            (considerationItem.itemType == ItemType.ERC721_WITH_CRITERIA)
                && (considerationItem.identifierOrCriteria == 0)
        ) {
            itemType = ItemType.ERC721;
            identifier = maximumSpent[i].identifier;
        } else if (
            (considerationItem.itemType == ItemType.ERC1155_WITH_CRITERIA)
                && (considerationItem.identifierOrCriteria == 0)
        ) {
            itemType = ItemType.ERC1155;
            identifier = maximumSpent[i].identifier;
        } else {
            itemType = considerationItem.itemType;
            identifier = considerationItem.identifierOrCriteria;
        }

        consideration[i] = ReceivedItem({
            itemType: itemType,
            token: considerationItem.token,
            identifier: identifier,
            amount: considerationItem.startAmount,
            recipient: considerationItem.recipient
        });
        unchecked {
            ++i;
        }
    }

    // Apply state changes if withEffects is true.
    if (withEffects) {
        // Increment the total redemption count.
        _totalRedemptions[campaignId] += maximumSpent.length;

        SpentItem[] memory spent = new SpentItem[](consideration.length);
        for (uint256 i = 0; i < consideration.length;) {
            spent[i] = SpentItem({
                itemType: consideration[i].itemType,
                token: consideration[i].token,
                identifier: consideration[i].identifier,
                amount: consideration[i].amount
            });
            unchecked {
                ++i;
            }
        }

        // Emit the redemption event.
        emit Redemption(campaignId, redemptionHash);
    }
}

Overview Creates, validates, and processes a redemption order.

Details

  • Retrieve the campaign and its parameters.
  • Validate using the error buffer and revert if an error occurs.
  • Set the offer and consideration items.
  • Apply state changes if withEffects is true.
  • Emit the redemption event.

Parameters

  • fulfiller
    • Address performing the redemption.
  • minimumReceived
    • Array of minimum redemption items.
  • maximumSpent
    • Array of maximum redemption items.
  • context
    • Context data.
  • withEffects
    • Boolean indicating whether to apply state changes.

Return value

  • offer
    • Array of offer items.
  • consideration
    • Array of consideration items.

Consideration items Items or services provided as consideration in a contract or transaction. In an exchange, each party generally provides something of value, such as goods, services, or money, in return for something provided by the other party.

Redemption The act of receiving a benefit or exercising a right. Specifically, it refers to a user who owns a token or NFT claiming the benefits or rewards associated with that asset.

Campaigns or other mechanisms can offer benefits associated with tokens or NFTs, requiring users to meet specific conditions before redeeming them. For example, the owner of a particular NFT might follow a designated procedure to redeem related digital content or items.


onERC721Received

javascript
function onERC721Received(
    address,
    /* operator */
    address from,
    uint256 tokenId,
    bytes calldata data
) external returns (bytes4) {
    if (from == address(0)) {
        return IERC721Receiver.onERC721Received.selector;
    }

    // Retrieve the campaign.
    uint256 campaignId = uint256(bytes32(data[0:32]));
    CampaignParams storage params = _campaignParams[campaignId];

    OfferItem[] memory offer = new OfferItem[](1);
    offer[0] = OfferItem({
        itemType: ItemType.ERC721_WITH_CRITERIA,
        token: params.offer[0].token,
        identifierOrCriteria: 0,
        startAmount: 1,
        endAmount: 1
    });

    ConsiderationItem[] memory consideration = new ConsiderationItem[](1);
    consideration[0] = ConsiderationItem({
        itemType: ItemType.ERC721,
        token: msg.sender,
        identifierOrCriteria: tokenId,
        startAmount: 1,
        endAmount: 1,
        recipient: payable(address(0x000000000000000000000000000000000000dEaD))
    });

    OrderParameters memory parameters = OrderParameters({
        offerer: address(this),
        zone: address(0),
        offer: offer,
        consideration: consideration,
        orderType: OrderType.CONTRACT,
        startTime: block.timestamp,
        endTime: block.timestamp + 10, // TODO: Needs correction
        zoneHash: bytes32(0), // TODO: Needs correction
        salt: uint256(0), // TODO: Needs correction
        conduitKey: _CONDUIT_KEY,
        totalOriginalConsiderationItems: consideration.length
    });

    AdvancedOrder memory order =
        AdvancedOrder({parameters: parameters, numerator: 1, denominator: 1, signature: "", extraData: data});

    SeaportInterface(_SEAPORT).fulfillAdvancedOrder(order, new CriteriaResolver[](0), _CONDUIT_KEY, from);

    return IERC721Receiver.onERC721Received.selector;
}

Overview Called when an ERC721 token is received to create and process a redemption order.

Details

  • Handle the received ERC721 token if the from address is not zero.
  • Retrieve the campaign and its parameters.
  • Set the offer and consideration items and construct order parameters.
  • Execute an AdvancedOrder through Seaport.

Parameters

  • from
    • Sender address.
  • tokenId
    • ERC721 token ID.
  • data
    • Context data.

Return value

  • bytes4d
    • ERC721 receiver callback selector.

onERC1155Received

javascript
function onERC1155Received(
    address,
    /* operator */
    address from,
    uint256 id,
    uint256 value,
    bytes calldata data
) external returns (bytes4) {
    if (from == address(0)) {
        return IERC1155Receiver.onERC1155Received.selector;
    }

    // Retrieve the campaign.
    uint256 campaignId = uint256(bytes32(data[0:32]));
    CampaignParams storage params = _campaignParams[campaignId];

    SpentItem[] memory minimumReceived = new SpentItem[](1);
    minimumReceived[0] = SpentItem({
        itemType: ItemType.ERC721,
        token: params.offer[0].token,
        identifier: params.offer[0].identifierOrCriteria,
        amount: params.offer[0].startAmount
    });

    SpentItem[] memory maximumSpent = new SpentItem[](1);
    maximumSpent[0] = SpentItem({itemType: ItemType.ERC1155, token: msg.sender, identifier: id, amount: value});

    // Revert if _createOrder fails.
    _createOrder(from, minimumReceived, maximumSpent, data, true);

    // Transfer the token to the consideration item recipient.
    address recipient = _getConsiderationRecipient(params.consideration, msg.sender);
    ERC1155(msg.sender).safeTransferFrom(address(this), recipient, id, value, "");

    // Transfer the newly created tokens to the fulfiller.
    ERC721(params.offer[0].token).safeTransferFrom(address(this), from, id, "");

    return IERC1155Receiver.onERC1155Received.selector

;
}

Overview Called when an ERC1155 token is received to create and process a redemption order.

Details

  • Handle the received ERC1155 token if the from address is not zero.
  • Retrieve the campaign and its parameters.
  • Set the minimum and maximum redemption items, then validate and process them through _createOrder.
  • Transfer the token to the consideration recipient and newly created tokens to the fulfiller.

Parameters

  • from
    • Sender address.
  • id
    • ERC1155 token ID.
  • value
    • Token amount.
  • data
    • Context data.

Return value

  • bytes4
    • ERC1155 receiver callback selector.

onERC1155BatchReceived

javascript
function onERC1155BatchReceived(
    address, /* operator */
    address from,
    uint256[] calldata ids,
    uint256[] calldata values,
    bytes calldata data
) external returns (bytes4) {
    if (from == address(0)) {
        return IERC1155Receiver.onERC1155BatchReceived.selector;
    }

    if (ids.length != values.length) revert RedeemMismatchedLengths();

    // Retrieve the campaign.
    uint256 campaignId = uint256(bytes32(data[0:32]));
    CampaignParams storage params = _campaignParams[campaignId];

    SpentItem[] memory minimumReceived = new SpentItem[](1);
    minimumReceived[0] = SpentItem({
        itemType: ItemType.ERC721,
        token: params.offer[0].token,
        identifier: params.offer[0].identifierOrCriteria,
        amount: params.offer[0].startAmount
    });

    SpentItem[] memory maximumSpent = new SpentItem[](ids.length);
    for (uint256 i = 0; i < ids.length;) {
        maximumSpent[i] =
            SpentItem({itemType: ItemType.ERC1155, token: msg.sender, identifier: ids[i], amount: values[i]});
        unchecked {
            ++i;
        }
    }

    // Revert if _createOrder fails.
    _createOrder(from, minimumReceived, maximumSpent, data, true);

    // Transfer the token to the consideration item recipient.
    address recipient = _getConsiderationRecipient(params.consideration, msg.sender);
    ERC1155(msg.sender).safeBatchTransferFrom(address(this), recipient, ids, values, "");

    // Transfer the newly created tokens to the fulfiller.
    ERC721(params.offer[0].token).safeTransferFrom(address(this), from, ids[0]);

    return IERC1155Receiver.onERC1155BatchReceived.selector;
}

Overview Called when a batch of ERC1155 tokens is received to create and process a redemption order.

Details

  • Handle the received ERC1155 batch if the from address is not zero.
  • Revert with RedeemMismatchedLengths if ids and values have different lengths.
  • Retrieve the campaign and its parameters.
  • Set the minimum and maximum redemption items, then validate and process them through _createOrder.
  • Transfer the tokens to the consideration recipient and the newly created tokens to the fulfiller.

Parameters

  • from
    • Sender address.
  • ids
    • Array of ERC1155 token IDs.
  • values
    • Array of amounts for each token.
  • data
    • Context data.

Return value

  • bytes4
    • ERC1155 batch receiver callback selector.

getCampaign

javascript
function getCampaign(uint256 campaignId)
    external
    view
    returns (CampaignParams memory params, string memory uri, uint256 totalRedemptions)
{
    if (campaignId >= _nextCampaignId) revert InvalidCampaignId();
    params = _campaignParams[campaignId];
    uri = _campaignURIs[campaignId];
    totalRedemptions = _totalRedemptions[campaignId];
}

Overview Retrieves information about the specified campaign.

Details

  • Retrieve campaign parameters, URI, and total redemption count using campaignId.

Parameters

  • campaignId
    • Campaign ID.

Return value

  • params
    • Campaign parameters.
  • uri
    • Campaign URI.
  • totalRedemptions
    • Total redemption count.

_getConsiderationRecipient

javascript
function _getConsiderationRecipient(ConsiderationItem[] storage consideration, address token)
    internal
    view
    returns (address)
{
    for (uint256 i = 0; i < consideration.length;) {
        if (consideration[i].token == token) {
            return consideration[i].recipient;
        }
        unchecked {
            ++i;
        }
    }
    revert ConsiderationRecipientNotFound(token);
}

Overview Retrieves the recipient address associated with a specified token.

Details

  • Inspect the items in consideration to find the recipient associated with the specified token.
  • Return the address if found.
  • Otherwise revert with ConsiderationRecipientNotFound.

Parameters

  • consideration
    • Array of consideration items.
  • token
    • Token address.

Return value

  • address
    • Recipient address associated with the token.

_isInactive

javascript
function _isInactive(uint256 startTime, uint256 endTime) internal view returns (bool inactive) {
    // Use the same time boundary check as Seaport.
    // startTime <= block.timestamp < endTime
    assembly {
        inactive := or(iszero(gt(endTime, timestamp())), gt(startTime, timestamp()))
    }
}

Overview Checks whether a campaign is inactive.

Details

  • Compare the current timestamp against the campaign's startTime and endTime.
  • The campaign is inactive if the current time falls outside its active interval.

Parameters

  • startTime
    • Campaign start time.
  • endTime
    • Campaign end time.

Return value

  • inactive
    • true if the campaign is inactive, otherwise false.

_isValidTokenAddress

javascript
function _isValidTokenAddress(CampaignParams memory params, address token) internal pure returns (bool valid) {
    for (uint256 i = 0; i < params.consideration.length;) {
        if (params.consideration[i].token == token) {
            valid = true;
            break;
        }
        unchecked {
            ++i;
        }
    }
}

Overview Determines whether a specified token address is valid.

Details

  • Check whether token appears among the consideration items in the campaign parameters params.
  • Set valid to true if the token is valid.

Parameters

  • params
    • Campaign parameters.
  • token
    • Token address to check.

Return value

  • valid
    • true if the token is valid, otherwise false.

_removeFromEnumeration

javascript
function _removeFromEnumeration(uint256 toRemove, uint256[] storage enumeration) internal {
    // Cache the length.
    uint256 enumerationLength = enumeration.length;
    for (uint256 i = 0; i < enumerationLength;) {
        // If the element to remove is found
        if (enumeration[i] == toRemove) {
            // Swap it with the last element.
            enumeration[i] = enumeration[enumerationLength - 1];
            // Remove the last element, which is now duplicated.
            enumeration.pop();
            // Exit the loop.
            break;
        }
        unchecked {
            ++i;
        }
    }
}

Overview Removes the specified value from an array.

Details

  • Inspect the elements in enumeration. When an element matches toRemove, swap it with the last element and remove it from the array.

Parameters

  • toRemove
    • Value to remove.
  • enumeration
    • Array of values.

_asAddressArray

javascript
function _asAddressArray(function(uint256, uint256[] storage) internal fnIn)
    internal
    pure
    returns (function(address, address[] storage) internal fnOut)
{
    assembly {
        fnOut := fnIn
    }
}

Overview Converts a function accepting a uint256 argument into a function accepting an address argument.

Details

  • Takes an internal function fnIn accepting a uint256 and returns a corresponding internal function fnOut accepting an address.

Parameters

  • fnIn
    • Function accepting a uint256 argument.

Return value

  • fnOut
    • Internal function accepting an address argument.

_cast

javascript
function _cast(bool b) internal pure returns (uint256 u) {
    assembly {
        u := b
    }
}

Overview Casts a bool value to a uint256.

Details

  • Cast the Boolean b to a uint256 value u.

Parameters

  • b
    • Boolean value to cast.

Return value

  • u
    • Resulting uint256 value.

Security considerations

  1. Tokens must correctly implement EIP7496 Dynamic Traits to support trait redemption. This enables trait redemptions. Trait redemption allows a token's properties, such as a particular level or character attribute, to be used to claim benefits. If the token does not implement this mechanism correctly, trait redemption may not work as intended. The token must therefore recognize the relevant traits and support their use in redemption.

  2. The mintRedemption function in IRedemptionMintable, used to mint tokens included in offer, requires appropriate access control. The implementation must restrict which addresses can call this function. When creating tokens to provide benefits, allow only authorized addresses to invoke the minting function. Incorrect permissions introduce security risks. Configure them carefully to prevent unauthorized token issuance.

Conclusion

This article covered ERC7498, OpenSea's proposal for associating NFTs with various on-chain and off-chain digital assets.

I hope it helped clarify the mechanism.

If you have questions, feel free to reach out via Twitter DM.

Twitter @cardene777