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 ERC4974, a proposed standard for managing ratings in smart contracts.

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

As of September 13, 2023, ERC4974 was in Review.

Overview

This standard defines a way to manage ratings on Ethereum. A rating is a numerical assessment or ranking of an item or project. For example, ratings may assess products, artworks, or the success of a project.

The standard allows rating data to be stored on-chain and managed in a reliable manner. Other applications can access the same data and use it for different purposes.

This creates new potential uses for tokens. For example, an application could issue tokens with particular ratings and offer benefits based on them. Markets might also emerge in which assessments of projects are traded as tokens.

Motivation

Blockchain applications have primarily focused on buying and selling digital assets, such as cryptocurrencies and tokens. This asset-centric model has drawbacks, especially for community-based blockchain projects. In 2021, pay-for-privilege dynamics became a concern in EVM (Ethereum Virtual Machine) games, DAOs (decentralized autonomous organizations), and similar applications.

The proposal addresses this problem by making it possible to assign ratings to smart contracts and wallets. It thus provides a new composable primitive for blockchain applications. Potential applications include the following.

Voting power in DAOs

Ratings assigned using the standard can determine the voting power of members of a decentralized autonomous organization (DAO). For example, a DAO could give higher ratings to members who contribute more to the community and use those ratings to determine each member's influence over decisions.

Experience points in decentralized gaming ecosystems

Ratings can track players' progress in decentralized gaming ecosystems and reward them when they reach particular goals. For example, a game could assign ratings to players and allow them to unlock new content or abilities based on their ratings.

Customer loyalty points

Ratings can track customer loyalty to a particular business or service and provide rewards accordingly. For example, a business could assign ratings to customers and allow them to redeem those ratings for special offers or discounts.

Asset assessment in decentralized insurance

Ratings can assess asset risk profiles in decentralized insurance and help determine premiums and coverage. For example, a decentralized insurer could assess the risks of different assets and use ratings to offer lower premiums and greater coverage for lower-risk assets.

The standard draws on token standards such as EIP20 and EIP721.

For more on ERC20, see the following article.

https://chaldene.net/erc20

For more on ERC721, see the following article.

https://chaldene.net/erc721

Specification

Contracts compliant with this standard must implement the following interface.

javascript
// SPDX-License-Identifier: CC0

pragma solidity ^0.8.0;

/// @title EIP-4974 Ratings
/// @dev See https://eips.ethereum.org/EIPS/EIP-4974
///  Note: the EIP-165 identifier for this interface is #######.
///  Must initialize contracts with an `operator` address that is not `address(0)`.
interface IERC4974 /* is ERC165 */ {

    /// @dev Emits when operator changes.
    ///  MUST emit when `operator` changes by any mechanism.
    ///  MUST ONLY emit by `setOperator`.
    event NewOperator(address indexed _operator);

    /// @dev Emits when operator issues a rating. 
    ///  MUST emit when rating is assigned by any mechanism.
    ///  MUST ONLY emit by `rate`.
    event Rating(address _rated, int8 _rating);

    /// @dev Emits when operator removes a rating. 
    ///  MUST emit when rating is removed by any mechanism.
    ///  MUST ONLY emit by `remove`.
    event Removal(address _removed);

    /// @notice Appoint operator authority.
    /// @dev MUST throw unless `msg.sender` is `operator`.
    ///  MUST throw if `operator` address is either already current `operator`
    ///  or is the zero address.
    ///  MUST emit an `Appointment` event.
    /// @param _operator New operator of the smart contract.
    function setOperator(address _operator) external;

    /// @notice Rate an address.
    ///  MUST emit a Rating event with each successful call.
    /// @param _rated Address to be rated.
    /// @param _rating Total EXP tokens to reallocate.
    function rate(address _rated, int8 _rating) external;

    /// @notice Remove a rating from an address.
    ///  MUST emit a Remove event with each successful call.
    /// @param _removed Address to be removed.
    function removeRating(address _removed) external;

    /// @notice Return a rated address' rating.
    /// @dev MUST register each time `Rating` emits.
    ///  SHOULD throw for queries about the zero address.
    /// @param _rated An address for whom to query rating.
    /// @return int8 The rating assigned.
    function ratingOf(address _rated) external view returns (int8);
}

interface IERC165 {
    /// @notice Query if a contract implements an interface.
    /// @dev Interface identification is specified in EIP-165. This function
    ///  uses less than 30,000 gas.
    /// @param interfaceID The interface identifier, as specified in EIP-165.
    /// @return bool `true` if the contract implements `interfaceID` and
    ///  `interfaceID` is not 0xffffffff, `false` otherwise.
    function supportsInterface(bytes4 interfaceID) external view returns (bool);
}

Additional considerations

Assigning ratings

Ratings are assigned at the contract operator's discretion. The operator may be a sports team coach, a multisignature DAO wallet, or another authorized party. The standard does not prescribe a particular governance mechanism; it only requires one to exist. Rather than optimizing for a single decision-making model, this leaves room for a wider range of potential uses.

Choosing int8

A signed integer (int8) was chosen. This allows reviewers to assign neutral or negative ratings to wallets and contracts. This is particularly important in decentralized applications where malicious behavior may occur. Using an 8-bit integer keeps ratings within a comparable range. Over time, this can make ratings easier to aggregate and reduce the use of incompatible rating scales.

An integer (int) is a data type used to represent numerical data. A signed integer (int) can represent both positive and negative values, such as 0, 1, -1, 2, and -2. An 8-bit integer (int8) uses eight bits (binary digits of 0 or 1) to represent a number.

Example 1 When ratings for wallets or contracts are represented using int8, they can range from -128 to 127. This is the range representable by an 8-bit signed integer.

Example 2 Suppose a reviewer assesses a particular decentralized application. Ratings might be represented by the following values.

  • 0
    • A neutral rating.
  • 1~127
    • Positive ratings (1 is the least positive and 127 is the most positive).
  • -1~-128
    • Negative ratings (-1 is the least negative and -128 is the most negative).

Example 3 Suppose several users rate the same wallet. Each user can assign a neutral, positive, or negative rating within the ranges 0 to 127 or -1 to -128.

Example 4 When an application collects and aggregates ratings from multiple users, the int8 type makes it easy to sum ratings assigned by different users. For example, if 100 users rate a wallet and each rating lies between 0 and 127, the wallet's aggregate rating can be calculated by summing these values using a sufficiently wide integer type.

An 8-bit integer provides an effective way to store ratings in a comparable format for aggregation. Since users need not use different scales, it helps maintain consistency across ratings.

Updating ratings

Ratings should be updatable by the contract operator. For example, if Bob contributes significantly to a community but is later found to have stolen from Alice, the community can decide whether to reduce Bob's standing and influence. This cannot guarantee ethical behavior within a community, but it provides a mechanism for addressing it. Similarly, the system should allow reviewers to withdraw ratings if they lack confidence in their ability to assess the subject effectively.

Example 1: Updating a rating Bob is a member of a decentralized community known for his substantial contributions and high rating. One day, the community receives a report that Bob stole from Alice. The community needs to address the issue.

  • Bob's high rating reflects his standing and influence within the community.
  • The community decides to update the rating.
  • Bob's rating decreases, reducing his standing and influence.
  • Community members or operators implement the decision through the contract, adjusting Bob's rating in response to his conduct and enabling the community to address misconduct and uphold ethical standards.

Example 2: Withdrawing a rating Some users may not be confident in their ability to act as reviewers. Such users need a way to withdraw ratings they assigned accidentally or incorrectly.

  • User A attempts to rate a particular contract but is unsure whether the rating is accurate.
  • User A realizes they assigned an excessively high rating by mistake and decides to withdraw it.
  • The system offers User A the option to withdraw the rating so they can correct their mistake.

Users can thereby adjust incorrect ratings and improve their accuracy. This functionality improves the reliability of the rating process and allows misunderstandings and inaccurate ratings to be corrected.

Interface detection

Standard interface detection (EIP165) was chosen so compliant smart contracts can expose the interfaces they support.

Metadata

The standard requires metadata containing a name (name) and description (description) to provide information about the smart contract. These are common elements of major blockchain primitives, and including them maintains consistency with other blockchain standards. The description field also provides a detailed explanation when multiple rating systems exist. Implementers who do not supply this information may return empty strings, which are still valid responses. Note that other smart contracts may use the same name and description.

Drawbacks

One potential drawback is that ratings are subjective and may not always accurately reflect the true value or quality of a contract or wallet. The standard offers flexibility by allowing ratings to be updated and removed. Users need to know how other contracts and communities assess them; ratings may be a source of pride or unfairly negative judgments. Unfair ratings may encourage malicious behavior, so implementers of rating systems have a responsibility to address these concerns carefully.

Backwards compatibility

The standard adopts the definition of name from EIP20 and EIP721.

Reference implementation

javascript
// SPDX-License-Identifier: CC0-1.0

pragma solidity ^0.8.0;
import "./IERC4974.sol";

/**
 * See {IERC4974}
 * Implements the ERC4974 Metadata extension.
 */
contract LoyaltyPoints is IERC4974 {

    // The address of the operator that can assign ratings
    address private _operator;

    // Mapping of customer addresses to their ratings
    mapping (bytes32 => int8) private _ratings;

    // Initializes the contract by setting the operator to msg.sender
    constructor () {
        _operator = msg.sender;
    }

    // Set the operator address
    // Only the current operator or the contract owner can call this function
    function setOperator(address newOperator) public override {
        require(_operator == msg.sender || msg.sender == address(this), "Only the current operator or the contract owner can set the operator.");
        _operator = newOperator;
        emit NewOperator(_operator);
    }

    // Rate a customer
    // Only the operator can call this function
    function rate(address customer, int8 rating) public override {
        require(_operator == msg.sender, "Only the operator can assign ratings.");
        bytes32 hash = keccak256(abi.encodePacked(customer));
        _ratings[hash] = rating;
        emit Rating(customer, rating);
    }

    // Remove a rating from a customer
    // Only the operator can call this function
    function removeRating(address customer) external override {
        require(_operator == msg.sender, "Only the operator can remove ratings.");
        bytes32 hash = keccak256(abi.encodePacked(customer));
        delete _ratings[hash];
        emit Removal(customer);
    }

    // Get the rating for a customer
    function getOperator() public view returns (address) {
        return _operator;
    }

    // Check if a customer has been rated
    function hasBeenRated(address customer) public view returns (bool) {
        // Hash the customer address
        bytes32 hash = keccak256(abi.encodePacked(customer));

        // Check if the hash exists in the mapping
        return _ratings[hash] != 0;
    }

    function ratingOf(address _rated) public view override returns (int8) {
        bytes32 hash = keccak256(abi.encodePacked(_rated));
        // Check if the customer has been rated
        require(hasBeenRated(_rated), "This customer has not been rated yet.");
        // Return the customer's rating
        return _ratings[hash];
    }

    // Award ETH to a customer based on their rating
    function awardEth(address payable customer) public payable {
        // Calculate the amount of ETH to award based on the customer's rating
        int8 rating = ratingOf(customer);
        require(rating > 0, "Sorry, this customer has a rating less than 0 and cannot be awarded.");
        uint256 award = uint256(int256(rating));
        // Transfer the ETH to the customer
        require(address(this).balance >= award, "Contract has insufficient balance to award ETH.");
        customer.transfer(award);
    }

    receive () external payable {}

}

_operator

javascript
address private _operator;

Overview The address of the operator authorized to assign ratings.

Details This account has permission to assign ratings within the smart contract. The operator can assign ratings to other users.

_ratings

javascript
mapping (bytes32 => int8) private _ratings;

Overview A mapping that stores ratings associated with addresses.

Details It records a rating for each user. A user's address-derived hash (bytes32) is associated with the corresponding rating (int8, a signed integer). The operator assigns user ratings and can update or remove them as needed.


setOperator

javascript
function setOperator(address newOperator) public override {
    require(_operator == msg.sender || msg.sender == address(this), "Only the current operator or the contract owner can set the operator.");
    _operator = newOperator;
    emit NewOperator(_operator);
}

Overview Sets the operator address.

Details The operator is the account authorized to assign ratings. This function sets a new operator address. Only the current operator or the contract itself can call this function in the reference implementation. Setting a new operator emits the NewOperator event.

Parameters

  • newOperator
    • The address of the new operator.

rate

javascript
function rate(address customer, int8 rating) public override {
    require(_operator == msg.sender, "Only the operator can assign ratings.");
    bytes32 hash = keccak256(abi.encodePacked(customer));
    _ratings[hash] = rating;
    emit Rating(customer, rating);
}

Overview Assigns a rating to a customer.

Details The rating is associated with a particular address and stored under its corresponding hash. Only the operator authorized to assign ratings can call this function. Assigning a rating emits the Rating event.

Parameters

  • customer
    • The address being rated.
  • rating
    • The rating assigned to the address (an integer from -128 to 127).

removeRating

javascript
function removeRating(address customer) external override {
    require(_operator == msg.sender, "Only the operator can remove ratings.");
    bytes32 hash = keccak256(abi.encodePacked(customer));
    delete _ratings[hash];
    emit Removal(customer);
}

Overview Removes the rating for a specified address.

Details Removing a rating deletes the value associated with the corresponding hash, resetting the rating. Removing a rating emits the Removal event. Only the operator authorized to assign ratings can call this function.

Parameters

  • customer
    • The address whose rating is to be removed.

getOperator

javascript
function getOperator() public view returns (address) {
    return _operator;
}

Overview Returns the current operator's address.

Details Allows other users to identify the current operator.

Return value

  • address
    • The current operator's address.

hasBeenRated

javascript
function hasBeenRated(address customer) public view returns (bool) {
    // Hash the customer address
    bytes32 hash = keccak256(abi.encodePacked(customer));

    // Check if the hash exists in the mapping
    return _ratings[hash] != 0;
}

Overview Checks whether the specified address has been rated.

Details It hashes the customer's address and checks the corresponding entry in the mapping. A nonzero value indicates that the address has been rated in this implementation.

Parameters

  • customer
    • The address whose rating status is to be checked.

Return value

  • bool
    • true if a rating exists according to the implementation, or false otherwise.

ratingOf

javascript
function ratingOf(address _rated) public view override returns (int8) {
    bytes32 hash = keccak256(abi.encodePacked(_rated));
    // Check if the customer has been rated
    require(hasBeenRated(_rated), "This customer has not been rated yet.");
    // Return the customer's rating
    return _ratings[hash];
}

Overview Returns the rating for a specified address.

Details It hashes the address and checks that a rating exists. If a rating exists, it returns the customer's rating. If no rating exists, it reverts with an error message.

Parameters

  • _rated
    • The address whose rating is to be retrieved.

Return value

  • int8
    • The rating for the specified address (an integer from -128 to 127).

awardEth

javascript
function awardEth(address payable customer) public payable {
    // Calculate the amount of ETH to award based on the customer's rating
    int8 rating = ratingOf(customer);
    require(rating > 0, "Sorry, this customer has a rating less than 0 and cannot be awarded.");
    uint256 award = uint256(int256(rating));
    // Transfer the ETH to the customer
    require(address(this).balance >= award, "Contract has insufficient balance to award ETH.");
    customer.transfer(award);
}

Overview Awards ETH to a specified address.

Details The award is calculated based on the address's rating. The function awards ETH only if the rating is greater than 0, transferring the amount to the specified address. It also checks that the contract's ETH balance is sufficient to cover the award.

Parameters

  • customer
    • The address receiving the ETH award.

Security considerations

Citation

Daniel Tedesco (@dtedesco1), "ERC-4974: Ratings [DRAFT]," Ethereum Improvement Proposals, no. 4974, April 2022. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-4974.

Conclusion

This article covered ERC4974, a proposed standard for managing ratings within smart contracts. I hope you found it useful.

If you have any questions, feel free to contact me via Twitter DM.

Twitter @cardene777

I also publish on other platforms, which you can find below.

https://chaldene.net/