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 examines ERC5050, which proposes a mechanism for NFTs and other tokens to send and receive specific actions.

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

Overview

ERC5050 proposes a general-purpose action messaging protocol that enables different tokens to exchange actions initiated by users.

Beyond sending and receiving actions, the protocol enables more sophisticated interactions by integrating with optional contracts that store and manage state, known as state controller contracts or environments.

In games, for example, it provides a foundation for exchanging player actions and state changes between tokens, as well as using, trading, or combining items.

It also provides a common interface through which off-chain services can automatically discover contracts, retrieve their available capabilities, and present information in a human-readable format, enabling interactive token services.

Motivation

Widely used Ethereum token standards such as ERC721 and ERC1155 define objects, including NFTs and in-game items.

In recent years, however, games and decentralized identity applications have increasingly sought to go beyond static objects by giving them dynamic interactions and state changes, a form of digital physics.

This creates a need for NFTs and other tokens to send and receive actions such as attacking, equipping, merging, or moving.

A common standard would make interactive tokens and applications more open and reusable.

Benefits of the protocol

  • Applications can automatically discover and use action-enabled tokens.
  • Games and metaverses can implement a decentralized digital physics layer.
  • Dynamic NFTs involving state changes become easier and safer to implement.
  • The protocol can serve as an action bridge that propagates actions between chains.
    • For example, record action logs for L1 assets on L2.
    • Allow L1 assets to interact with L2 assets.
    • Ultimately reflect L2 actions on L1 through a rollup.

Specification

Interfaces

js
pragma solidity ^0.8.0;

/// @param _address The address of the interactive object
/// @param tokenId The token that is interacting (optional)
struct Object {
    address _address;
    uint256 _tokenId;
}

/// @param selector The bytes4(keccack256()) encoding of the action string
/// @param user The address of the sender
/// @param from The initiating object
/// @param to The receiving object
/// @param state The state controller contract
/// @param data Additional data with no specified format
struct Action {
    bytes4 selector;
    address user;
    Object from;
    Object to;
    address state;
    bytes data;
}

/// @title EIP-5050 Interactive NFTs with Modular Environments
interface IERC5050Sender {
    /// @notice Send an action to the target address
    /// @dev The action's `fromContract` is automatically set to `address(this)`,
    /// and the `from` parameter is set to `msg.sender`.
    /// @param action The action to send
    function sendAction(Action memory action) external payable;

    /// @notice Check if an action is valid based on its hash and nonce
    /// @dev When an action passes through all three possible contracts
    /// (`fromContract`, `to`, and `state`) the `state` contract validates the
    /// action with the initiating `fromContract` using a nonced action hash.
    /// This hash is calculated and saved to storage on the `fromContract` before
    /// action handling is initiated. The `state` contract calculates the hash
    /// and verifies it and nonce with the `fromContract`.
    /// @param _hash The hash to validate
    /// @param _nonce The nonce to validate
    function isValid(bytes32 _hash, uint256 _nonce) external returns (bool);

    /// @notice Retrieve list of actions that can be sent.
    /// @dev Intended for use by off-chain applications to query compatible contracts,
    /// and to advertise functionality in human-readable form.
    function sendableActions() external view returns (string[] memory);

    /// @notice Change or reaffirm the approved address for an action
    /// @dev The zero address indicates there is no approved address.
    ///  Throws unless `msg.sender` is the `_account`, or an authorized
    ///  operator of the `_account`.
    /// @param _account The account of the account-action pair to approve
    /// @param _action The action of the account-action pair to approve
    /// @param _approved The new approved account-action controller
    function approveForAction(
        address _account,
        bytes4 _action,
        address _approved
    ) external returns (bool);

    /// @notice Enable or disable approval for a third party ("operator") to conduct
    ///  all actions on behalf of `msg.sender`
    /// @dev Emits the ApprovalForAll event. The contract MUST allow
    ///  an unbounded number of operators per owner.
    /// @param _operator Address to add to the set of authorized operators
    /// @param _approved True if the operator is approved, false to revoke approval
    function setApprovalForAllActions(address _operator, bool _approved)
        external;

    /// @notice Get the approved address for an account-action pair
    /// @dev Throws if `_tokenId` is not a valid NFT.
    /// @param _account The account of the account-action to find the approved address for
    /// @param _action The action of the account-action to find the approved address for
    /// @return The approved address for this account-action, or the zero address if
    ///  there is none
    function getApprovedForAction(address _account, bytes4 _action)
        external
        view
        returns (address);

    /// @notice Query if an address is an authorized operator for another address
    /// @param _account The address on whose behalf actions are performed
    /// @param _operator The address that acts on behalf of the account
    /// @return True if `_operator` is an approved operator for `_account`, false otherwise
    function isApprovedForAllActions(address _account, address _operator)
        external
        view
        returns (bool);

    /// @dev This emits when an action is sent (`sendAction()`)
    event SendAction(
        bytes4 indexed name,
        address _from,
        address indexed _fromContract,
        uint256 _tokenId,
        address indexed _to,
        uint256 _toTokenId,
        address _state,
        bytes _data
    );

    /// @dev This emits when the approved address for an account-action pair
    ///  is changed or reaffirmed. The zero address indicates there is no
    ///  approved address.
    event ApprovalForAction(
        address indexed _account,
        bytes4 indexed _action,
        address indexed _approved
    );

    /// @dev This emits when an operator is enabled or disabled for an account.
    ///  The operator can conduct all actions on behalf of the account.
    event ApprovalForAllActions(
        address indexed _account,
        address indexed _operator,
        bool _approved
    );
}

interface IERC5050Receiver {
    /// @notice Handle an action
    /// @dev Both the `to` contract and `state` contract are called via
    /// `onActionReceived()`.
    /// @param action The action to handle
    function onActionReceived(Action calldata action, uint256 _nonce)
        external
        payable;

    /// @notice Retrieve list of actions that can be received.
    /// @dev Intended for use by off-chain applications to query compatible contracts,
    /// and to advertise functionality in human-readable form.
    function receivableActions() external view returns (string[] memory);

    /// @dev This emits when a valid action is received.
    event ActionReceived(
        bytes4 indexed name,
        address _from,
        address indexed _fromContract,
        uint256 _tokenId,
        address indexed _to,
        uint256 _toTokenId,
        address _state,
        bytes _data
    );
}

Contracts implementing ERC5050 must implement ERC165's supportsInterface() so other contracts and clients can discover their capabilities.

For more on ERC165, see the following article.

[ERC165] Checking whether a contract supports a specific interface

  • An implementation of IERC5050Sender returns true when queried with 0xc8c6c9f3.
  • An implementation of IERC5050Receiver returns true when queried with 0x1a3f02f4.

This allows external services to discover interactive contracts automatically.

Structs

Object

A struct representing an object that initiates or receives an action.

js
struct Object {
    address _address;
    uint256 _tokenId;
}

This struct uniquely identifies an interactive object, such as an NFT, using a contract address and tokenId. It can also be used where token IDs are unnecessary, such as with ERC20.

Action

A struct containing the details of an action being sent or received.

js
struct Action {
    bytes4 selector;
    address user;
    Object from;
    Object to;
    address state;
    bytes data;
}

The struct contains the following information.

  • selector
    • A bytes4 value derived by hashing the action name with keccak256, for example bytes4(keccak256("attack")).
  • user
    • The address initiating the action.
  • from / to
    • The source and destination objects of the action.
  • state
    • The address of the contract responsible for state control.
  • data
    • Arbitrary additional data associated with the action.

IERC5050Sender

IERC5050Sender defines the functions that action-sending contracts must implement.

Functions

sendAction
js
function sendAction(Action memory action) external payable;

Sends a specified action to a target. The sending contract is automatically set to address(this).

isValid
js
function isValid(bytes32 _hash, uint256 _nonce) external returns (bool);

Verifies the validity of an action using its hash and nonce. This maintains action integrity as actions pass through multiple contracts.

sendableActions
js
function sendableActions() external view returns (string[] memory);

Returns a list of actions that can be sent. Off-chain services use it to display available capabilities.

approveForAction / setApprovalForAllActions
js
function approveForAction(address _account, bytes4 _action, address _approved) external returns (bool);
function setApprovalForAllActions(address _operator, bool _approved) external;

Grants or revokes a third party's authorization for a particular account and action combination or for all actions.

getApprovedForAction / isApprovedForAllActions
js
function getApprovedForAction(address _account, bytes4 _action) external view returns (address);
function isApprovedForAllActions(address _account, address _operator) external view returns (bool);

Checks the address approved for an action or whether an operator is approved for all actions.

Events

  • SendAction
    • Emitted when an action is sent.
  • ApprovalForAction
    • Emitted when approval for an individual action changes.
  • ApprovalForAllActions
    • Emitted when approval for all actions changes.

IERC5050Receiver

IERC5050Receiver defines the functions that contracts must implement to handle incoming actions.

Functions

onActionReceived
js
function onActionReceived(Action calldata action, uint256 _nonce) external payable;

Processes a received action. This function may also be called through a state contract.

receivableActions
js
function receivableActions() external view returns (string[] memory);

Returns a list of actions that can be received. This is used for off-chain display.

Events

  • ActionReceived
    • Emitted when a valid action is received.

Action naming conventions

ERC5050 recommends two types of separators in action names: dots (.) and arrows (>).

Dot-separated names (namespaces)

  • Format
    • namespace.action
  • Example: spells.cast represents a cast action in the spells namespace.

This format distinguishes actions with the same name according to their purpose. For example, spells.cast (casting a spell) and building.cast (casting a material) can be used in different contexts.

Arrow-separated names (action order)

  • Format
    • action1>action2
  • Example: settle>build indicates that the settle action takes place before the build action.

Describing action sequences in this way makes it possible to express complex behavior involving multiple actions.

Role and operation of state contracts

State contracts are optional

ERC5050 allows actions to be processed using a state management contract, but does not require one. In simple cases, users can send actions directly to tokens, or tokens can exchange actions directly with one another.

Each token contract controls its own state in this case.

Why use a state contract?

A state contract allows multiple senders and receivers to share the same state environment.

  • Tokens A and B interact within a shared game environment, such as a battlefield.
  • The state contract chosen by the user centrally manages state.

The state contract is then responsible for determining whether the action is ultimately valid.

Workflow using a state contract

  1. Register the token

    • The token owner calls register on the state contract.
    • Set the initial state, such as HP and other attributes.
  2. Initiate an action

    • The owner initiates an action, such as an attack.
    • sendAction() specifies the source, destination, and state contract.
  3. Process the action

    • The receiving token processes the action and, if needed, responds according to the state.
    • The state contract verifies validity using the action hash and nonce, then updates state.
  4. Update token metadata

    • Tokens A and B update their appearance or information based on the state contract's state.

State contract modularity and applications

ERC5050 allows state contracts to be modular. Multiple environments with the same logic can be created and substituted as needed.

This enables applications such as the following.

  • Aggregators analyze action events to identify commonly used state contracts.
  • Tokens restrict usage to specific state contracts.
  • A default state contract can be configured while allowing users to change it freely, which is useful for NFTs whose appearance depends on state.
  • Cross-chain architectures, such as validating actions on L1 and storing them on L2, can optimize costs.

Example: the FightGame state contract

The following is one example of a use case envisioned by ERC5050.

  • The FightGame state contract provides a combat environment.
  • Users call FightGame.register(contract, tokenId) to obtain initial attributes such as HP and attack power.
  • Token A from the Fighters contract calls sendAction(AttackAction) to attack token B from the Pacifists contract.
  • Token B processes the action, after which FightGame validates and approves it and updates the attributes.
  • The metadata of A and B changes according to the FightGame state and the results of their internal processing.

Extensions

ERC5050 standardizes NFT interactivity, but also defines optional extensions that can be implemented according to the use case. These can improve user experience, maintain compatibility with existing contracts, strengthen security, and support cross-chain interactions.

Providing interactive user interfaces (Interactive)

Some contracts have custom UIs that let users perform actions intuitively.

IERC5050Interactive.sol
pragma solidity ^0.8.0;

/// @title EIP-5050 Interactive NFTs with Modular Environments
interface IERC5050Interactive {
    function interfaceURI(bytes4 _action) external view returns (string);
}

interfaceURI

Takes a bytes4 action selector and returns the UI URI corresponding to that action, for example an HTML or JSON resource. Off-chain applications can retrieve this URI and display the appropriate interface to the user.

For example, the spells.cast action can present a UI in which the user selects a spell.

Backward compatibility and cross-chain support through action proxies (Action Proxies)

Action proxies can maintain compatibility with existing non-upgradeable contracts or help implement cross-chain bridges.

Implementation example and role

Action proxies can be implemented as an extension of ERC1820, the interface discovery standard. The original article describes configuring an administrator with setManager() in connection with ERC173 ownership management and executing specific actions on behalf of another contract. Note that setManager() is an ERC1820 registry function; ERC173 defines ownership management separately. This enables action interactions with older, non-upgradeable NFT contracts or NFTs on other chains.

These proxies are useful for building flexible infrastructure.

For more on ERC1820, see the following article.

[ERC1820] How ERC1820 addresses ERC820 issues introduced by a Solidity update

For more on ERC173, see the following article.

[ERC173] Understanding contract ownership management

Controller mechanism for controlling actions (Controllable)

This extension allows trusted contracts to force action execution for security and cross-chain control purposes.

IControllable.sol
pragma solidity ^0.8.0;

/// @title EIP-5050 Action Controller
interface IControllable {
    
    /// @notice Enable or disable approval for a third party ("controller") to force
    ///  handling of a given action without performing EIP-5050 validity checks.
    /// @dev Emits the ControllerApproval event. The contract MUST allow
    ///  an unbounded number of controllers per action.
    /// @param _controller Address to add to the set of authorized controllers
    /// @param _action Selector of the action for which the controller is approved / disapproved
    /// @param _approved True if the controller is approved, false to revoke approval
    function setControllerApproval(address _controller, bytes4 _action, bool _approved)
        external;

    /// @notice Enable or disable approval for a third party ("controller") to force
    ///  action handling without performing EIP-5050 validity checks. 
    /// @dev Emits the ControllerApproval event. The contract MUST allow
    ///  an unbounded number of controllers per action.
    /// @param _controller Address to add to the set of authorized controllers
    /// @param _approved True if the controller is approved, false to revoke approval
    function setControllerApprovalForAll(address _controller, bool _approved)
        external;

    /// @notice Query if an address is an authorized controller for a given action.
    /// @param _controller The trusted third party address that can force action handling
    /// @param _action The action selector to query against
    /// @return True if `_controller` is an approved operator for `_account`, false otherwise
    function isApprovedController(address _controller, bytes4 _action)
        external
        view
        returns (bool);
    
    /// @dev This emits when a controller is enabled or disabled for the given
    ///  action. The controller can force `action` handling on the emitting contract, 
    ///  bypassing the standard EIP-5050 validity checks.
    event ControllerApproval(
        address indexed _controller,
        bytes4 indexed _action,
        bool _approved
    );
    
    /// @dev This emits when a controller is enabled or disabled for all actions.
    ///  Disabling all action approval for a controller does not override explicit action
    ///  action approvals. Controller's approved for all actions can force action handling 
    ///  on the emitting contract for any action.
    event ControllerApprovalForAll(
        address indexed _controller,
        bool _approved
    );
}

A previously trusted controller, such as an L2 bridge contract, can force an action to execute without ordinary action validation. This is intended to avoid validation or rollback risks and ensure execution of authorized actions.

Key points
  • Ordinary action validation (require/revert) is bypassed.
  • Controllers are important for cross-chain bridges and secure workflows.
  • The ControllerApproval and ControllerApprovalForAll events allow approvals to be monitored.

ERC4906 support for metadata updates (Metadata Update)

Interactive NFTs using ERC5050 may change their appearance or attributes in response to actions.

Emitting an ERC4906-compliant MetadataUpdate event enables external marketplaces and viewers to detect such changes promptly.

Examples
  • HP decreases during combat and the token's appearance changes to show damage.
  • Using an item causes an evolution and updates the metadata.

Using ERC4906 makes the user experience more responsive to state changes.

For more on ERC4906, see the following article.

[ERC4906] An interface for logging changes to NFT metadata

Additional notes

Core value of the standard

ERC5050 aims to achieve four goals.

  • Common interaction definitions Standardize the definition, discovery, and execution of actions between objects such as NFTs.
  • Optional state management Use state contracts to share state where needed, enabling flexible interoperability and validation.
  • Developer-friendly design Make the standard easy to adopt, including within existing contract architectures.
  • User-friendly design Provide an accessible experience without requiring complex user operations.

Action names and selectors

Actions have two representations.

  • For users, a human-readable string, such as spells.cast.
  • Inside contracts, a bytes4 selector, such as bytes4(keccak256("spells.cast")).

This design lets UIs and off-chain services handle understandable names while contracts process selectors efficiently.

It also supports namespaces using dots and action ordering using arrows, allowing flexible designs.

Action validation and security design

The following design is used to ensure action validity.

  • Action validation with a hash and nonce Action data is hashed and stored by fromContract. The state contract verifies it.

The proposal adopts this approach for the following reasons.

  • It is highly gas-efficient.
  • It has received support from developers and users.

An alternative considered but not adopted

  • Validation using signed messages
    • A worse user experience, because signing and submitting require two steps.
    • High gas costs.
    • Difficulty addressing the actual threat model, in which users may unknowingly be directed to malicious contracts.

ERC5050 treats the token contract, rather than the user, as the initiator of an action. Anyone can send an action to another token, and the receiving contract decides whether to accept it.

Design rationale for state contracts

Separating state management into a dedicated contract has the following benefits.

  • Explicitly defining how an action handles state makes the design more transparent.
  • State definitions and validation can be delegated to a shared environment.
  • Sending and receiving contracts do not need to share state directly.

This makes it easier to implement custom state contracts based on each game's own logic and rules.

Gas costs and complexity

The proposal highlights the following considerations regarding gas consumption in chains of actions.

  • Action processing in an individual contract may have arbitrary complexity.
  • However, loops such as for loops should be avoided where possible.
  • Developers are encouraged to minimize gas consumption.

A push-pull action chain has been considered as a future alternative, but has not been adopted at the time of writing.

Compatibility

Because ERC5050 introduces a new action-processing model, existing non-upgradeable token contracts cannot support it directly. However, the following approaches can enable new interactive experiences involving older NFTs and existing assets.

  • Place an action proxy outside the existing token contract to adapt it to the ERC5050 format.
  • The approach can also be used for cross-chain bridges, making it a flexible compatibility layer.

Reference implementation

FightGame.sol
// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.0;

import {ERC5050State, Action} from "./ERC5050State.sol";
import {ERC5050, Action} from "./ERC5050.sol";

struct TokenInfo {
   uint256 health;
   uint256 healthRemaining;
   uint256 power;
   uint256 blockedAt;
   uint256 blockPower;
   uint256 lockedUntilBlock;
   uint256 wins;
   bool hasRegistered;
}

interface IFightGame {
     function getStats(address _contract, uint256 _tokenId) external view returns (TokenInfo);
}

contract FightGame is IFightGame, ERC5050State {
    
    bytes4 constant LIGHT_ATTACK_SELECTOR = bytes4(keccak256("fg.light-attack"));
    bytes4 constant HEAVY_ATTACK_SELECTOR = bytes4(keccak256("fg.heavy-attack"));
    bytes4 constant BLOCK_SELECTOR = bytes4(keccak256("fg.block"));
    
    uint256 constant BLOCK_DECAY = 100;
    uint256 constant LIGHT_ATTACK_DECAY = 200;
    uint256 constant HEAVY_ATTACK_DECAY = 500;
    
    mapping(address => mapping(uint256 => TokenInfo)) state;
    
    constructor()  {
        _registerReceivable("fg.light-attack");
        _registerReceivable("fg.heavy-attack");
        _registerReceivable("fg.block");
    }
    
    function register(address _contract, uint256 _tokenId) external {
        require(msg.sender == ownerOf(_contract, _tokenId), "sender not token owner");
        require(!state[_contract][_tokenId].hasRegistered, "token already registered");
        state[_contract][_tokenId] = TokenInfo(100, 100, 5, 0, 0, 0, true);
    }
    
    function getStats(address _contract, uint256 _tokenId) external view returns (TokenInfo){
        return state[_contract][_tokenId];
    }
    
    function onActionReceived(Action calldata action, uint256 _nonce)
        external
        payable
        override
        onlyReceivableAction(action, _nonce)
    {
        TokenInfo storage from = state[action.from._address][action.from._tokenId];
        require(from.healthRemaining > 0, "health 0");
        require(block.number > from.lockedUntilBlock, "token locked");
        if (action.selector == BLOCK_SELECTOR) {
            from.blockPower = from.power * 3;
            from.blockedAt = block.number;
            from.lockedUntilBlock = block.number + BLOCK_DECAY;
            return;
        }
        
        TokenInfo storage to = state[action.to._address][action.to._tokenId];
        require(to.healthRemaining > 0, "target health 0");
        
        uint256 damage;
        if (action.selector == LIGHT_ATTACK_SELECTOR ) {
            damage = from.power;
            from.lockedUntilBlock = block.number + LIGHT_ATTACK_DECAY;
        }
        
        if (action.selector == HEAVY_ATTACK_SELECTOR) {
            damage = from.power * 3;
            from.lockedUntilBlock = block.number + HEAVY_ATTACK_DECAY;
        }
        if(to.blockedAt + BLOCK_DECAY > block.number) {
            if(to.blockPower >= damage){
                to.blockPower -= damage;
                return;
            }
            damage -= to.blockPower;
        }
        if(to.healthRemaining > damage){
            to.healthRemaining -= damage;
            return;
        }
        
        // Winner gains loser's power and some health 
        from.power += to.power;
        from.healthRemaining += to.power;
        from.wins++;
        to.healthRemaining = 0;
    }
}

contract Fighter is ERC5050, ERC721 {
    
    IFightGame stateContract;
    
    constructor(address _stateContract)  {
        _registerAction("fg.light-attack");
        _registerAction("fg.heavy-attack");
        _registerSendable("fg.block");
        stateContract = IFightGame(_stateContract);
    }
    
    // Update NFT render / metadata based on game stats
    function tokenURICharacterEmoji(uint256 tokenId)
        public
        view
        override
        returns (string memory)
    {
        TokenInfo memory stats = stateContract.getStats(address(this), tokenId);
        if(stats.healthRemaining == 0){
            return unicode"😵";
        }
        if(stats.power > 100){
            return unicode"🦾";
        }
        if(stats.power > 50){
            return unicode"💪";
        }
        if(stats.power > 20){
            return unicode"🤩";
        }
        if(stats.power > 5){
            return unicode"😃";
        }
        return unicode"😀";
    }
}
Spells.sol
// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.0;

import {ERC5050, Action} from "./ERC5050.sol";

contract Spells is ERC5050, ERC721 {

    bytes4 constant CAST_SELECTOR = bytes4(keccak256("cast"));
    bytes4 constant ATTUNE_SELECTOR = bytes4(keccak256("attune"));

    mapping(uint256 => uint256) spellDust;
    mapping(uint256 => string) attunement;

    constructor() ERC721("Spells", unicode"🔮") {
        _registerSendable("cast");
        _registerReceivable("attune");
    }

    function sendAction(Action memory action)
        external
        payable
        override
        onlySendableAction(action)
    {
        require(
            msg.sender == ownerOf(action.from._tokenId),
            "Spells: invalid sender"
        );
        _sendAction(action);
    }

    function onActionReceived(Action calldata action, uint256 _nonce)
        external
        payable
        override
        onlyReceivableAction(action, _nonce)
    {
        if (action.selector == ATTUNE_SELECTOR) {
            string memory unicodeChar;
            bytes memory _data = action.data;
            assembly {
                // Read unicode character from first 6 bytes (\u5050)
                unicodeChar := shr(208, _data)
            }
            attunement[action.to._tokenId] = unicodeChar;
        }
        // Pass action to state receiver if specified
        _onActionReceived(action, _nonce);
    }

    string[12] private dust = [
        unicode"․",
        unicode"∴",
        unicode"`"
    ];

    string[5] private spells = [
        "Conjuring",
        "Divining",
        "Transforming",
        "Hexing",
        "Banishing"
    ];

    function tokenURI(uint256 tokenId)
        public
        view
        override
        returns (string memory)
    {
        string
            memory out = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 400 350"><style>.base { fill: lightyellow; font-family: serif; font-size: 14px; } .chant { font-style: italic;} .dust {font-family: monospace; font-size: 8px; letter-spacing:5px;}.sm{font-size: 10px;} .sigil{font-family: monospace, font-size:13}</style><rect width="100%" height="100%" fill="#171717" /><text x="14" y="24" class="base">';

        out = string.concat(
            out,
            string.concat(spells[_spellType(tokenId)], " Spell"),
            '</text><text x="376" y="336" class="base sigil">',
            attunement[tokenId]
        );
        out = string.concat(out, "</text></svg>");
        string memory json = Base64.encode(
            bytes(
                string(
                    abi.encodePacked(
                        '{"name": "Spell #',
                        Strings.toString(tokenId),
                        '", "description": "Cast spells, attune spells.", "image": "data:image/svg+xml;base64,',
                        Base64.encode(bytes(out)),
                        '"}'
                    )
                )
            )
        );
        return string(abi.encodePacked("data:application/json;base64,", json));
    }

    function _spellType(uint256 tokenId) internal pure returns (uint256) {
        uint256 rand = _random(Strings.toString(tokenId));
        return rand % 6;
    }

    function _random(string memory input) internal pure returns (uint256) {
        return uint256(keccak256(abi.encodePacked(input)));
    }
}

Security

Challenges in action validation

The protocol relays actions between multiple contracts. For example, the flow may look like this.

text
Sending contract → Receiving contract → State management contract

With this relay structure, the receiving contract has no native means of verifying whether an action really originated from the contract specified in from.

User signature authentication is one option, but ERC5050 does not adopt it.

Why not use signature authentication?

Signed messages were considered disadvantageous in terms of both user experience and gas costs for the following reasons.

  • Users must perform two steps each time: signing and submitting a transaction.
  • Signature verification incurs high gas costs.

Instead of signatures, ERC5050 therefore adopts a design centered on the contract and token that initiate the action.

Token-centric validation model

In this protocol, the contract rather than the user is treated as the actor.

  • Anyone can send arbitrary actions to another token, much like anyone can send a tweet to Bill Gates.
  • The receiver decides how to handle the action.
  • For high-value actions, access can be controlled using state contracts or allowlists.

This design aims to balance security and flexibility.

Citation

Alexi (@alexi), "ERC-5050: Interactive NFTs with Modular Environments [DRAFT]," Ethereum Improvement Proposals, no. 5050, April 2021. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-5050.

Conclusion

This article examined ERC5050, which proposes a mechanism for NFTs and other tokens to send and receive specific actions.