masa-finance / masa-oracle

Masa Oracle: Decentralized Data Protocol 🌐
https://developers.masa.ai/docs/category/oracle-node
MIT License
16 stars 13 forks source link

EPIC: Masa Protocol Staking Logic - MVP for Testnet #317

Closed teslashibe closed 2 months ago

teslashibe commented 3 months ago

Epic: Refactor and Enhance ProtocolStaking Contract

Description

This epic focuses on refactoring the OracleNodeStaking.sol contract to ProtocolStaking to improve its modularity, incorporate epoch-based reward distribution, and add protocol node fee functionality. The updates will align the contract with the utility functions defined for validators, workers, and oracle nodes based on the heuristics outlined in the [DRAFT]_Technical_Whitepaper_Rev_1.3.pdf.

Goals

  1. Refactor the OracleNodeStaking contract to achieve better code organization, reusability, and maintainability, rename it to ProtocolStaking to reflect our updated code and vision.
  2. Incorporate the correct logic for our decentralized protocol, as outlined in the technical whitepaper.
  3. Implement epoch-based reward distribution for validators and workers based on their utility.
  4. Add fee functionality for protocol nodes based on their usage.

Problem Statement

The current implementation of the OracleNodeStaking contract has the following issues:

  1. Lack of modularity: The contract combines multiple functionalities, making it complex and harder to maintain.
  2. Absence of epoch-based reward distribution: The contract does not distribute rewards to validators and workers based on their utility over a specific epoch.
  3. Missing fee logic for oracle nodes: The contract does not track the usage of protocol nodes and calculate the fees they need to pay.
  4. Inconsistency with the technical whitepaper: The contract does not accurately reflect the utility of each actor (validator, worker, and oracle node) as defined in the whitepaper.

To address these issues, we need to refactor the ProtocolStaking contract into separate contracts, each responsible for a specific functionality. The contract should be updated to consider the following heuristics for each actor:

  1. Validator:

    • Size of stake
    • Number of transactions validated
    • Uptime
  2. Worker:

    • Size of stake
    • Amount of data scraped in bytes
    • Uptime
    • Average latency
  3. Oracle Node:

    • Size of stake
    • Amount of data queried from the network

Suggested Implementation

  1. Create separate contracts:

    • Staking: Handles staking functionality for validators, workers, and protocol nodes.
    • UtilityTracker: Tracks the utility of each actor based on the defined heuristics.
    • EpochRewards: Handles reward distribution logic for each epoch.
    • ProtocolFees: Handles fee logic for oracle nodes, oracle nodes must pre-pay fees that are deducted as they use the protocol.
  2. Update the ProtocolStaking contract:

    • Inherit from the newly created contracts.
    • Remove duplicate functionality handled by the separate contracts.
    • Update the contract interactions and flow to reflect the changes in the contract structure.
    • Add validator role for making changes to variables
  3. Implement utility tracking:

    • Add state variables to track the utility of each actor.
    • Implement functions to update the stats for validators, workers, and oracle nodes.
    • Add validator role for making changes to variables
  4. Update staking and withdrawal:

    • Modify the stake function to consider the utility of each actor based on their role and the defined heuristics.
    • Adjust the withdraw function to update the utility of each actor when they withdraw their stake.
    • Add validator role for making changes to variables
  5. Implement epoch-based reward distribution:

    • Add state variables to track the current epoch and the reward split between validators and workers.
    • Implement functions to start a new epoch and distribute rewards based on utility.
    • Add an access control mechanism to allow only the validator role to modify the reward split.
    • Add validator role for making changes to variables and setting epoch time in blocks or time
  6. Implement protocol node fees:

    • Add state variables to track the usage and fees of each protocol node.
    • Implement functions to update the usage of protocol nodes and calculate their fees.
    • Add a function for protocol nodes to pay their fees.
    • Add validator role for making changes to variables
  7. Update documentation and perform testing:

    • Update the contract documentation to reflect the changes and provide clear explanations of the utility calculations.
    • Conduct thorough testing to verify the correctness of the utility calculations and the overall functionality.

Contract Structure Diagram

+-----------------------+
|  ProtocolStaking      |
+-----------------------+
          |
          |
          v
+-----------------------+
|       Staking         |
+-----------------------+
          |
          |
          v
+-----------------------+
|    UtilityTracker     |
+-----------------------+
          |
          |
          v
+-----------------------+
|     EpochRewards      |
+-----------------------+
          |
          |
          v
+-----------------------+
|    ProtocolFees       |
+-----------------------+

Acceptance Criteria

Deployment

Reference

Tasks

teslashibe commented 3 months ago

Example code for utility: inspirational only and may not be suited to solidity code we will probably end up having this logic on the protocol itself

To reflect the complexity and non-linear relationships described in the whitepaper for utlity functions, we need can adjust the Solidity code examples for Validators, Worker Nodes, and Oracle Nodes. This involves incorporating specific non-linear functions and conditional logic that governs staking requirements and utility calculations, aligned with the performance metrics.

Validators

The utility calculation for Validators will include an exponential function to represent the non-linear relationship between their performance metrics and the staking requirements.

Revised Solidity Code for Validators:

pragma solidity ^0.8.0;

contract ValidatorUtility {
    struct Validator {
        uint256 stake;
        uint256 numTransactionsValidated;
        uint256 dataVerified;
        uint256 llmOutputsEvaluated;
    }

    mapping(address => Validator) public validators;

    // Performance coefficients, should be settable via governance
    uint256 alpha = 1;
    uint256 beta = 1;
    uint256 gamma = 1;
    uint256 lambda = 10; // Sensitivity parameter for performance

    // Function to update validator metrics
    function updateValidatorActivities(address validatorAddress, uint256 transactions, uint256 verifiedData, uint256 outputsEvaluated) public {
        Validator storage v = validators[validatorAddress];
        v.numTransactionsValidated += transactions;
        v.dataVerified += verifiedData;
        v.llmOutputsEvaluated += outputsEvaluated;
    }

    // Non-linear utility calculation using exponential function
    function calculateUtility(address validatorAddress) public view returns (uint256) {
        Validator storage v = validators[validatorAddress];
        uint256 performanceScore = alpha * v.numTransactionsValidated + beta * v.dataVerified + gamma * v.llmOutputsEvaluated;
        return v.stake * (10 ** (performanceScore / lambda));
    }
}

Worker Nodes

Incorporate a dynamic adjustment based on computational power and data quality, using an exponential function to simulate the increased utility for higher performance.

Revised Solidity Code for Worker Nodes:

pragma solidity ^0.8.0;

contract WorkerNodeUtility {
    struct WorkerNode {
        uint256 stake;
        uint256 computationalPower;
        uint256 dataQuality;
    }

    mapping(address => WorkerNode) public workerNodes;

    uint256 alpha = 1; // Weight for computational power
    uint256 beta = 1; // Weight for data quality
    uint256 lambdaW = 5; // Sensitivity parameter

    // Update metrics for worker nodes
    function updateWorkerNodePerformance(address workerAddress, uint256 compPower, uint256 dataQual) public {
        WorkerNode storage w = workerNodes[workerAddress];
        w.computationalPower += compPower;
        w.dataQuality += dataQual;
    }

    // Non-linear utility calculation
    function calculateUtility(address workerAddress) public view returns (uint256) {
        WorkerNode storage w = workerNodes[workerAddress];
        uint256 performanceScore = alpha * w.computationalPower + beta * w.dataQuality;
        return w.stake * exp(performanceScore / lambdaW);
    }

    // Helper function to calculate exponential
    function exp(uint x) private pure returns (uint) {
        return uint(keccak256(abi.encodePacked(x))); // Simplified; use actual exp calculation in production
    }
}

Oracle Nodes

Oracle Nodes' utility will be adjusted for their resource usage with an exponential function to accurately represent the impact of high resource consumption.

Revised Solidity Code for Oracle Nodes:

pragma solidity ^0.8.0;

contract OracleNodeUtility {
    struct OracleNode {
        uint256 stake;
        uint256 resourcesUsed;
    }

    mapping(address => OracleNode) public oracleNodes;

    uint256 lambdaO = 20; // Sensitivity parameter for Oracle Nodes

    // Update resource usage
    function updateResourceUsage(address oracleAddress, uint256 resourceAmount) public {
        OracleNode storage o = oracleNodes[oracleAddress];
        o.resourcesUsed += resourceAmount;
    }

    // Non-linear utility calculation with resource usage
    function calculateUtility(address oracleAddress) public view returns (uint256) {
        OracleNode storage o = oracleNodes[oracleAddress];
        return o.stake * exp(o.resourcesUsed / lambdaO);
    }

    // Helper function for exponential calculation
    function exp(uint x) private pure returns (uint) {
        return uint(keccak256(abi.encodePacked(x))); // Simplified; use actual exp calculation in production
    }
}

General Notes:

miquelcabot commented 3 months ago

@mudler @teslashibe @H34D @Luka-Loncar Some questions:

Luka-Loncar commented 3 months ago

Here are the answers:

Question: Should there be a minimum amount required for staking? Should this minimum apply to the total staked amount or to each individual staking action? Answer: According to the technical whitepaper, the staking requirements for each role (validator, worker, and oracle nodes) are determined by performance-sensitive staking mechanisms. The staking requirement for each role is defined as a proportion of the total token supply, adjusted by a monotonic function that maps the node's performance to a staking coefficient. The whitepaper does not specify a fixed minimum staking amount. This quote is from @teslashibe: "Think about adding starting/minimum/dynamic staking for each actor. This is currently missing from requirements. Forgot to add this to ticket. Staking requirement for each actor should be modifiable by the validator role." You can find it in this link

Question: The technical paper states that "validators must stake MASA tokens as collateral." Does this requirement also apply to worker and oracle nodes, meaning all roles can only stake MASA tokens? Answer: The technical whitepaper clearly states that validators, worker nodes, and oracle nodes must stake MASA tokens as collateral.

Question: The technical paper mentions the TAO token but does not specify its use. Can TAO tokens be used for staking, rewards, or both? Answer: I'd like us to get more clarity here from @teslashibe since the technical whitepaper mentions the TAO token as part of the dual-token economic model, alongside the MASA token. However, the specific use case of TAO tokens within the staking smart contract is not clearly defined in the whitepaper.

Question: Can a single account hold multiple roles (e.g., validator, worker, oracle)? This would simplify the creation of a single staking smart contract for all roles. Answer: Whitepaper does not explicitly state whether a single account can hold multiple roles (e.g., validator, worker, and oracle). However, we should consider the potential implications of allowing multiple roles per account, such as centralization risks and the impact on the overall network dynamics. On top of that, I'm not sure if this is related, but during hackathon Vasilis got his nodes banned when he was trying to run validator and worker nodes from same computer.

I don't have answer to your last question @miquelcabot.

teslashibe commented 2 months ago

@mudler @Luka-Loncar I updated the description to include the tickets that are on the board for this EPIC

mudler commented 2 months ago

Closing this epic as the only outstanding card to finish the story is already available (but blocked): https://github.com/masa-finance/masa-oracle/issues/326