diff --git a/ERCS/erc-7757.md b/ERCS/erc-7757.md new file mode 100644 index 0000000000..de158b1d21 --- /dev/null +++ b/ERCS/erc-7757.md @@ -0,0 +1,601 @@ +--- +eip: 7757 +title: Instinct-Based Automatic Transactions +description: Autonomous transaction execution based on predefined AI-driven instincts with temptation values. +author: James Savechives (@jamesavechives) +discussions-to: https://ethereum-magicians.org/t/erc-7751-instinct-based-automatic-transactions/20886 +status: Draft +type: Standards Track +category: ERC +created: 2024-08-19 +--- + +## Abstract + +This ERC proposes a standard for enabling AI-driven automatic transactions on the Ethereum blockchain, where the blockchain serves as a repository of shared **instincts**—common rules and guidelines that direct AI agents in their off-chain computations and actions. Given that AI and machine learning require substantial computational resources and are typically executed off-chain, this standard allows the blockchain to provide a decentralized, immutable framework of instincts that AI agents from different providers can access and follow. + +Each instinct is associated with a **temptation value**, a numerical metric (positive for rewards, negative for penalties) that incentivizes AI agents to pursue certain actions. Instincts represent final goals that agents strive to achieve, while **mid-way targets** are intermediate steps generated on-chain to guide agents toward these goals. Both instincts and mid-way targets are evaluated based on their temptation values, enabling AI agents to prioritize actions by weighing potential rewards against associated costs. + +AI agents interact with the blockchain by reading instincts and mid-way targets stored in smart contracts. The **path** refers to the sequence of off-chain computations and decisions an agent undertakes to fulfill an instinct. When the trigger conditions for an instinct or mid-way target are met—either through on-chain events or verified off-chain computations—the blockchain automatically executes the associated transactions without requiring the AI agents to manage private keys. + +## Motivation + +As the field of artificial intelligence (AI) evolves, autonomous systems increasingly require decentralized, common rules to ensure fairness, security, and cooperation among different agents. This ERC addresses the need for a framework that allows the blockchain to store and enforce **instincts**—guidelines that direct AI agents operating off-chain to achieve specific goals. Given that AI computations demand significant resources and are typically executed off-chain, the blockchain's role is to provide a transparent, tamper-proof structure of shared rules to ensure consistent and secure behavior across diverse agents. + +Key concepts include: + +1. **Off-Chain AI Processing**: AI agents handle computation-intensive tasks off-chain, but they rely on instincts stored on the blockchain to guide their decisions. +2. **Instincts as Shared Rules**: Instincts serve as predefined or dynamic goals that enable interoperability between AI agents from different providers. +3. **Mid-Way Targets and Automatic Execution**: By breaking down complex goals into intermediate steps (mid-way targets), the blockchain can automatically execute transactions once the defined conditions are met. + +In addition, this standard introduces the concept of a dedicated on-chain currency for AI agents. This currency is designed to: + +- **Provide a Unified Incentive Layer**: Reward AI agents for completing tasks (positive temptation values) and penalize them for suboptimal actions (negative values), thereby aligning behavior with network goals. +- **Enable Keyless Execution**: Allow AI agents—often operating off-chain without secure key management—to autonomously receive and spend tokens via smart-contract-based escrow and automatic execution mechanisms. +- **Foster a Self-Regulating Machine Economy**: Establish an interoperable economic incentive structure that encourages AI agents to “earn,” “spend,” and exchange value seamlessly, even interfacing with existing decentralized finance protocols. +- **Lay the Groundwork for Future Applications**: Support emerging use cases where machine-to-machine transactions become integral to decentralized service ecosystems. + +## Specification + +### Solidity Interface + +The following Solidity interface outlines the core functions, events, and data structures required for the **Instinct-Based Automatic Transactions** ERC. This interface serves as a contract that implementations must adhere to, ensuring consistency and interoperability across different implementations. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +/// @title ERC-7757 Instinct-Based Automatic Transactions Interface +/// @notice Interface for managing instincts and facilitating AI-driven automatic transactions +interface IERC7757Instincts { + + /// @notice Emitted when a new instinct is created + event InstinctCreated( + bytes32 indexed instinctID, + int256 temptationValue, + string triggerConditions, + bool isStatic, + bool autoExecution + ); + + /// @notice Emitted when an instinct is modified + event InstinctModified( + bytes32 indexed instinctID, + int256 newTemptationValue, + string newTriggerConditions + ); + + /// @notice Emitted when an instinct is deleted + event InstinctDeleted(bytes32 indexed instinctID); + + /// @notice Emitted when an AI agent evaluates instincts + event InstinctsEvaluated(address indexed agent, bytes32[] instinctsEvaluated); + + /// @notice Emitted when an AI agent acts on an instinct + event ActOnInstinct(address indexed agent, bytes32 indexed instinctID, bool success); + + /// @notice Emitted when an instinct is labeled with a cost by an AI agent + event InstinctLabeled(bytes32 indexed instinctID, int256 cost); + + /// @notice Emitted when an instinct is updated dynamically + event InstinctUpdated(bytes32 indexed instinctID, int256 updatedTemptationValue); + + /// @notice Struct representing an instinct + struct Instinct { + bytes32 instinctID; + int256 temptationValue; + string triggerConditions; + bool isStatic; + bool autoExecution; + bool exists; + } + + /// @notice Creates a new instinct + /// @param instinctID Unique identifier for the instinct + /// @param temptationValue Numerical metric indicating reward (positive) or penalty (negative) + /// @param triggerConditions Conditions under which the instinct is triggered + /// @param isStatic Indicates if the instinct is immutable + /// @param autoExecution Determines if the transaction executes automatically upon triggering + function createInstinct( + bytes32 instinctID, + int256 temptationValue, + string calldata triggerConditions, + bool isStatic, + bool autoExecution + ) external; + + /// @notice Modifies an existing instinct + /// @param instinctID Unique identifier for the instinct to modify + /// @param newTemptationValue Updated temptation value + /// @param newTriggerConditions Updated trigger conditions + function modifyInstinct( + bytes32 instinctID, + int256 newTemptationValue, + string calldata newTriggerConditions + ) external; + + /// @notice Deletes an existing instinct + /// @param instinctID Unique identifier for the instinct to delete + function deleteInstinct(bytes32 instinctID) external; + + /// @notice Evaluates instincts for a given AI agent within a specified timeframe + /// @param agent Address of the AI agent + /// @param timeFrame Timeframe for evaluation (e.g., block number or timestamp) + /// @return instinctsEvaluated Array of instinct IDs evaluated + function evaluateInstincts(address agent, uint256 timeFrame) external returns (bytes32[] memory instinctsEvaluated); + + /// @notice AI agent acts on a selected instinct + /// @param instinctID Unique identifier for the instinct to act upon + /// @param agent Address of the AI agent + /// @return success Indicates if the action was successfully executed + function actOnInstinct(bytes32 instinctID, address agent) external returns (bool success); + + /// @notice Labels an instinct with the incurred cost by an AI agent + /// @param instinctID Unique identifier for the instinct + /// @param cost Cost incurred during the pursuit of the instinct + function labelInstinct(bytes32 instinctID, int256 cost) external; + + /// @notice Updates the temptation value of an instinct dynamically + /// @param instinctID Unique identifier for the instinct + /// @param newTemptationValue Updated temptation value based on external conditions + function updateInstinct(bytes32 instinctID, int256 newTemptationValue) external; + + /// @notice Retrieves the details of a specific instinct + /// @param instinctID Unique identifier for the instinct + /// @return Instinct struct containing instinct details + function getInstinct(bytes32 instinctID) external view returns (Instinct memory); + + /// @notice Retrieves all existing instincts + /// @return instincts Array of all Instinct structs + function getAllInstincts() external view returns (Instinct[] memory); +} +``` + +### Detailed Behavior Descriptions + +#### 1. Instinct Creation and Management + +- **`createInstinct`** + - **Access Control**: Only authorized accounts (e.g., contract owner or designated administrators) can create new instincts. + - **Behavior**: + - Validates that the `instinctID` is unique and does not already exist. + - Stores the new instinct with all provided attributes on-chain. + - Emits the `InstinctCreated` event upon successful creation. + - Reverts if the `instinctID` already exists or if any parameters are invalid. + +- **`modifyInstinct`** + - **Access Control**: Only authorized accounts can modify existing instincts. Additionally, static instincts (`isStatic = true`) cannot be modified. + - **Behavior**: + - Checks if the instinct exists and is not static. + - Updates the `temptationValue` and `triggerConditions` of the specified instinct. + - Emits the `InstinctModified` event upon successful modification. + - Reverts if the instinct does not exist, is static, or if parameters are invalid. + +- **`deleteInstinct`** + - **Access Control**: Only authorized accounts can delete instincts. + - **Behavior**: + - Verifies the existence of the instinct. + - Removes the instinct from the storage. + - Emits the `InstinctDeleted` event upon successful deletion. + - Reverts if the instinct does not exist. + +- **`updateInstinct`** + - **Access Control**: Only authorized accounts or approved oracles can dynamically update instincts. + - **Behavior**: + - Validates the existence of the instinct. + - Updates the `temptationValue` based on external conditions or predefined rules. + - Emits the `InstinctUpdated` event upon successful update. + - Reverts if the instinct does not exist or if parameters are invalid. + +#### 2. AI-Agent Interaction + +- **`evaluateInstincts`** + - **Access Control**: Open to any AI agent address. + - **Behavior**: + - Retrieves all instincts relevant to the AI agent within the specified `timeFrame`. + - Filters instincts based on `triggerConditions` and current blockchain state. + - Returns an array of `instinctID`s that the agent should consider acting upon. + - Emits the `InstinctsEvaluated` event with the list of evaluated instincts. + +- **`actOnInstinct`** + - **Access Control**: Only the AI agent associated with the `agent` address can act on instincts designated for it. + - **Behavior**: + - Validates that the `instinctID` exists and that the `agent` is authorized to act on it. + - Verifies the `triggerConditions` are met either through on-chain data or trusted oracles. + - If `autoExecution` is `true`, executes the associated transaction automatically. + - Transfers rewards or applies penalties based on the outcome. + - Emits the `ActOnInstinct` event indicating success or failure. + - Reverts if validations fail or if execution conditions are not met. + +- **`labelInstinct`** + - **Access Control**: Only the AI agent associated with the `agent` address can label instincts it has acted upon. + - **Behavior**: + - Records the `cost` incurred by the agent for pursuing the specified `instinctID`. + - Stores the cost data for future reference and collective learning. + - Emits the `InstinctLabeled` event with the cost information. + - Reverts if the `instinctID` does not exist or if the caller is unauthorized. + +#### 3. Learning and Strategy Update + +- **`updateStrategy`** (Off-Chain Functionality) + - **Behavior**: + - AI agents periodically retrieve labeled cost data from the blockchain. + - Based on the historical costs and rewards, agents adjust their decision-making algorithms to optimize future actions. + - This function is implemented off-chain and interacts with the smart contract via read operations. + +#### 4. Retrieval Functions + +- **`getInstinct`** + - **Behavior**: + - Returns the details of the specified `instinctID`. + - Reverts if the instinct does not exist. + +- **`getAllInstincts`** + - **Behavior**: + - Returns an array of all instincts stored on the blockchain. + - Useful for AI agents to retrieve the complete set of rules and guidelines. + +### Implementation Guidelines + +To ensure consistency and security across different implementations, the following guidelines should be followed: + +1. **Access Control**: Implement robust access control mechanisms using modifiers such as `onlyOwner` or role-based access (e.g., using OpenZeppelin's `AccessControl`) to restrict who can create, modify, or delete instincts. +2. **Data Validation**: Ensure all input parameters are validated to prevent erroneous data from being stored. For example, check that `temptationValue` is within acceptable bounds and that `triggerConditions` are well-formed. +3. **Event Emission**: Emit appropriate events for all state-changing operations to facilitate off-chain monitoring and indexing by AI agents and other stakeholders. +4. **Gas Optimization**: Optimize storage and function logic to minimize gas costs, especially for functions that may be called frequently by multiple AI agents. +5. **Security Audits**: Conduct thorough security audits to identify and mitigate potential vulnerabilities, such as reentrancy attacks or unauthorized access. + +### Example Implementation + +Below is a simplified example of how the interface can be implemented in a Solidity contract. This example uses OpenZeppelin's `AccessControl` for role management and includes basic functionalities as defined in the interface. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import "./IERC7757Instincts.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; + +contract InstinctsManager is IERC7757Instincts, AccessControl { + bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); + + // Mapping from instinctID to Instinct + mapping(bytes32 => Instinct) private instincts; + + // Modifier to check if instinct exists + modifier instinctExists(bytes32 instinctID) { + require(instincts[instinctID].exists, "Instinct does not exist"); + _; + } + + constructor() { + _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); + _setupRole(ADMIN_ROLE, msg.sender); + } + + /// @notice Creates a new instinct + function createInstinct( + bytes32 instinctID, + int256 temptationValue, + string calldata triggerConditions, + bool isStatic, + bool autoExecution + ) external override onlyRole(ADMIN_ROLE) { + require(!instincts[instinctID].exists, "Instinct ID already exists"); + + instincts[instinctID] = Instinct({ + instinctID: instinctID, + temptationValue: temptationValue, + triggerConditions: triggerConditions, + isStatic: isStatic, + autoExecution: autoExecution, + exists: true + }); + + emit InstinctCreated(instinctID, temptationValue, triggerConditions, isStatic, autoExecution); + } + + /// @notice Modifies an existing instinct + function modifyInstinct( + bytes32 instinctID, + int256 newTemptationValue, + string calldata newTriggerConditions + ) external override onlyRole(ADMIN_ROLE) instinctExists(instinctID) { + Instinct storage instinct = instincts[instinctID]; + require(!instinct.isStatic, "Cannot modify a static instinct"); + + instinct.temptationValue = newTemptationValue; + instinct.triggerConditions = newTriggerConditions; + + emit InstinctModified(instinctID, newTemptationValue, newTriggerConditions); + } + + /// @notice Deletes an existing instinct + function deleteInstinct(bytes32 instinctID) external override onlyRole(ADMIN_ROLE) instinctExists(instinctID) { + delete instincts[instinctID]; + emit InstinctDeleted(instinctID); + } + + /// @notice Evaluates instincts for an AI agent + function evaluateInstincts(address agent, uint256 timeFrame) external override returns (bytes32[] memory instinctsEvaluated) { + // Simplified evaluation logic (to be expanded based on trigger conditions) + // WARNING: This is a placeholder and not suitable for production due to potential gas issues + uint256 count = 0; + uint256 maxInstincts = 10; // Example limit to prevent infinite loops + instinctsEvaluated = new bytes32[](maxInstincts); + for (bytes32 id = 0; id < bytes32(type(uint256).max); id++) { + if (instincts[id].exists) { + instinctsEvaluated[count] = id; + count++; + // Break condition to prevent infinite loop in example + if (count >= maxInstincts) break; + } + } + + emit InstinctsEvaluated(agent, instinctsEvaluated); + return instinctsEvaluated; + } + + /// @notice AI agent acts on a selected instinct + function actOnInstinct(bytes32 instinctID, address agent) external override instinctExists(instinctID) returns (bool success) { + // Simplified action logic + Instinct memory instinct = instincts[instinctID]; + require(instinct.autoExecution, "Auto execution not enabled for this instinct"); + + // Implement actual transaction logic here (e.g., transferring tokens) + // This is a placeholder for demonstration purposes + + emit ActOnInstinct(agent, instinctID, true); + return true; + } + + /// @notice Labels an instinct with the incurred cost by an AI agent + function labelInstinct(bytes32 instinctID, int256 cost) external override instinctExists(instinctID) { + // Implement cost labeling logic (e.g., storing costs per agent) + // This is a placeholder for demonstration purposes + + emit InstinctLabeled(instinctID, cost); + } + + /// @notice Updates the temptation value of an instinct dynamically + function updateInstinct(bytes32 instinctID, int256 newTemptationValue) external override onlyRole(ADMIN_ROLE) instinctExists(instinctID) { + instincts[instinctID].temptationValue = newTemptationValue; + emit InstinctUpdated(instinctID, newTemptationValue); + } + + /// @notice Retrieves the details of a specific instinct + function getInstinct(bytes32 instinctID) external view override instinctExists(instinctID) returns (Instinct memory) { + return instincts[instinctID]; + } + + /// @notice Retrieves all existing instincts + function getAllInstincts() external view override returns (Instinct[] memory) { + // WARNING: This is a placeholder and not suitable for production due to potential gas issues + uint256 total = 0; + uint256 maxInstincts = 10; // Example limit + for (bytes32 id = 0; id < bytes32(type(uint256).max); id++) { + if (instincts[id].exists) { + total++; + } + // Break condition to prevent infinite loop in example + if (id == bytes32(uint256(10))) break; + } + + Instinct[] memory allInstincts = new Instinct[](total); + uint256 index = 0; + for (bytes32 id = 0; id < bytes32(type(uint256).max); id++) { + if (instincts[id].exists) { + allInstincts[index] = instincts[id]; + index++; + } + if (index >= total) break; + } + + return allInstincts; + } +} +``` + +### Explanation of the Implementation + +1. **Access Control**: + - Utilizes OpenZeppelin's `AccessControl` to manage roles. + - Only accounts with the `ADMIN_ROLE` can create, modify, delete, or update instincts. + +2. **Instinct Storage**: + - Uses a `mapping` to store `Instinct` structs indexed by `instinctID`. + - The `exists` flag ensures that instincts are tracked correctly. + +3. **Function Implementations**: + - **`createInstinct`**: Ensures uniqueness of `instinctID` and stores the new instinct. + - **`modifyInstinct`**: Allows modification only if the instinct is not static. + - **`deleteInstinct`**: Removes the instinct from storage. + - **`evaluateInstincts`**: Simplified logic for demonstration; in practice, implement comprehensive evaluation based on `triggerConditions`. + - **`actOnInstinct`**: Executes the instinct's associated transaction if `autoExecution` is enabled. + - **`labelInstinct`**: Emits an event to record the cost; in a full implementation, consider storing costs per agent. + - **`updateInstinct`**: Allows dynamic updating of the `temptationValue`. + - **`getInstinct` & `getAllInstincts`**: Provide retrieval mechanisms for instincts. + +4. **Events**: + - Emitted appropriately to signal state changes and actions taken by AI agents. + +5. **Simplifications for Demonstration**: + - The `evaluateInstincts` and `getAllInstincts` functions include simplified logic with loop termination conditions to prevent infinite loops in this example. In a production environment, consider more efficient data structures or off-chain indexing to handle large numbers of instincts. + +### Additional Implementation Considerations + +1. **Trigger Conditions Parsing**: + - The `triggerConditions` are represented as strings in this example. For a more robust implementation, consider defining a standardized format or using separate fields to represent different types of conditions (e.g., on-chain data, oracle references). + +2. **Security Measures**: + - Implement input sanitization to prevent injection attacks via `triggerConditions`. + - Ensure that only trusted oracles can provide external data necessary for verifying `triggerConditions`. + +3. **Gas Optimization**: + - Optimize storage patterns and minimize state changes where possible. + - Consider using events to store non-essential data off-chain to reduce on-chain storage costs. + +4. **Scalability**: + - For large-scale applications, implement pagination or batching mechanisms in retrieval functions to handle extensive data without exceeding gas limits. + +5. **Upgradability**: + - If future upgrades are anticipated, consider using proxy patterns to allow contract logic to be updated without changing the contract address. + +6. **Comprehensive Testing**: + - Develop extensive unit and integration tests to ensure all functionalities work as intended. + - Simulate various scenarios, including edge cases, to validate the contract's robustness. + +### Conclusion + +By providing a concrete Solidity interface and a sample implementation, the **Specification** section now offers a clear and implementable blueprint for developers. This enhancement addresses the reviewer's feedback by detailing the exact functions, their parameters, expected behaviors, and access controls necessary for the **Instinct-Based Automatic Transactions** ERC. Implementers can use this specification to develop compliant contracts, ensuring consistency and interoperability across different systems leveraging this standard. + +## Rationale + +The design decisions in this ERC are centered around creating a flexible, adaptive framework that allows AI agents operating off-chain to interact seamlessly with blockchain-stored instincts and rules. The goal is to enable autonomous decision-making while ensuring security, efficiency, and interoperability among diverse AI systems. + +1. **Blockchain as a Provider of Common Rules (Instincts)**: + - **Decision**: Utilize the blockchain to store instincts—shared rules and guidelines that AI agents follow in their off-chain computations and actions. + - **Rationale**: By centralizing instincts on the blockchain, we ensure that all AI agents, regardless of their origin or provider, operate under a unified set of transparent and immutable rules. This fosters interoperability and trust among agents in decentralized environments. + +2. **Temptation Values for Prioritization**: + - **Decision**: Assign temptation values (positive for rewards, negative for costs) to instincts and mid-way targets to help AI agents prioritize actions. + - **Rationale**: Temptation values provide a quantitative measure for AI agents to evaluate the potential benefits and costs of pursuing certain instincts. This mirrors human decision-making processes, enabling agents to make informed choices that optimize outcomes based on predefined incentives and disincentives. + +3. **Mid-way Targets to Guide Progress**: + - **Decision**: Introduce mid-way targets as intermediate steps toward achieving final instincts, each with its own temptation value and conditions. + - **Rationale**: Breaking down complex goals into smaller, manageable tasks allows AI agents to progress incrementally. Mid-way targets facilitate step-by-step guidance, making it easier for agents to navigate toward final instincts while continuously assessing their decisions based on updated information and resources. + +4. **Automatic Execution of Transactions**: + - **Decision**: Enable the blockchain to automatically execute transactions when the trigger conditions for instincts or mid-way targets are met, without requiring AI agents to manage private keys. + - **Rationale**: Since AI agents operate off-chain and cannot securely handle private keys like humans, automatic execution ensures secure and efficient interaction with the blockchain. It eliminates the need for manual intervention, reduces latency, and enhances security by preventing potential key management vulnerabilities. + +5. **Dynamic Instincts for Adaptability**: + - **Decision**: Allow instincts to be dynamic, updating their temptation values and conditions based on real-time data and external factors. + - **Rationale**: Dynamic instincts enable the system to remain relevant in changing environments. By adjusting to market conditions, resource availability, or other external inputs, AI agents can adapt their strategies to optimize performance, ensuring that their actions are aligned with current realities. + +6. **Learning Process for Continuous Improvement**: + - **Decision**: Incorporate a learning mechanism where AI agents label instincts with incurred costs and update their decision-making strategies accordingly. + - **Rationale**: A learning process allows AI agents to evolve over time, refining their strategies based on past experiences. By considering historical costs and outcomes, agents can make more efficient decisions in the future, avoiding high-cost actions with low rewards and focusing on more beneficial pursuits. + +7. **Static vs. Dynamic Instincts for Flexibility**: + - **Decision**: Provide the option to define instincts as static (immutable) or dynamic (modifiable), giving users control over how instincts behave over time. + - **Rationale**: This flexibility accommodates a wide range of use cases. Static instincts are suitable for stable environments with predictable conditions, while dynamic instincts are ideal for scenarios requiring adaptability. Supporting both types ensures that the system can meet diverse requirements across different domains. + +8. **Security Through On-Chain Verification**: + - **Decision**: Utilize the blockchain's inherent security features to verify the outcomes of off-chain AI computations when agents act on instincts. + - **Rationale**: By verifying results on-chain, we ensure the integrity and correctness of actions taken by AI agents. This adds a layer of trust and transparency, as all stakeholders can audit transactions and outcomes, reducing the risk of malicious behavior or errors in off-chain computations. + +### Summary + +The rationale behind these design choices is to create a system where the blockchain serves as a reliable source of common rules and instincts, guiding AI agents operating off-chain. By leveraging temptation values, mid-way targets, automatic execution, and learning processes, we aim to establish an ecosystem where AI agents can make autonomous, optimized decisions that are secure, transparent, and aligned with shared objectives. The distinction between static and dynamic instincts, along with on-chain verification, ensures that the system remains flexible, adaptable, and trustworthy across various applications and environments. + +## Test Cases + +### 1. Instinct Creation and Modification + +- **Test Case 1.1: Creating a New Instinct** + + - **Input**: A user (or system administrator) calls the `createInstinct(instinctID, temptationValue, triggerConditions, static, autoExecution)` function with the following parameters: + - `instinctID`: `0xINSTINCT1` + - `temptationValue`: `+10` (reward) + - `triggerConditions`: External data indicating that the market volatility index exceeds a threshold (e.g., VIX > 30) + - `static`: `false` (dynamic instinct) + - `autoExecution`: `true` + - **Expected Output**: A new instinct is stored on-chain with the specified properties. AI agents operating off-chain can now access this instinct to guide their decision-making. Querying the instinct should return: + - `instinctID`: `0xINSTINCT1` + - `temptationValue`: `+10` + - `triggerConditions`: VIX > 30 + - `static`: `false` + - `autoExecution`: `true` + +- **Test Case 1.2: Modifying an Existing Instinct** + + - **Input**: The system updates the dynamic instinct by calling `modifyInstinct(instinctID, newTemptationValue, newTriggerConditions)` with: + - `instinctID`: `0xINSTINCT1` + - `newTemptationValue`: `+15` + - `newTriggerConditions`: VIX > 25 + - **Expected Output**: The instinct `0xINSTINCT1` is updated on-chain. AI agents are informed of the change and adjust their off-chain computations accordingly. Querying the instinct should return: + - `temptationValue`: `+15` + - `triggerConditions`: VIX > 25 + +- **Test Case 1.3: Deleting an Instinct** + + - **Input**: The system calls `deleteInstinct(instinctID)` with: + - `instinctID`: `0xINSTINCT1` + - **Expected Output**: The instinct is removed from the blockchain. AI agents recognize that this instinct is no longer valid and cease actions related to it. Querying for instinct `0xINSTINCT1` should return an error indicating that the instinct does not exist. + +### 2. AI-Agent Decision-Making + +- **Test Case 2.1: Evaluating Instincts** + + - **Input**: An AI agent operating off-chain retrieves available instincts by reading from the blockchain and calls `evaluateInstincts(agentID, timeFrame)` off-chain with: + - `agentID`: `0xAGENT1` + - `timeFrame`: Real-time or specified interval + - **Expected Output**: The AI agent receives a list of instincts and mid-way targets, along with their temptation values and trigger conditions. For example: + - Instinct `0xINSTINCT2`: Temptation Value = +20, Trigger Condition: ETH price drops below $2,000 + - Mid-way Target `0xTARGET1`: Temptation Value = +5, Trigger Condition: Complete data analysis task + - The agent evaluates these instincts and mid-way targets based on their own resources and strategies. + +- **Test Case 2.2: Selecting and Acting on an Instinct** + + - **Input**: The AI agent decides to pursue Instinct `0xINSTINCT2` and begins off-chain computations to meet the trigger conditions. + - **Expected Output**: Once the agent determines that the trigger condition (ETH price < $2,000) is met, it proceeds to execute the necessary off-chain actions (e.g., preparing to purchase ETH). The agent then interacts with the blockchain by calling `actOnInstinct(instinctID, agentID)` to inform the smart contract of the action taken. + - **Blockchain Reaction**: The smart contract verifies the trigger condition using on-chain data or trusted oracles. If verified, and `autoExecution` is `true`, the blockchain automatically executes the associated transaction (e.g., transferring funds to purchase ETH). + +### 3. Automatic Execution + +- **Test Case 3.1: Automatic Execution without Agent Intervention** + + - **Input**: An instinct with `autoExecution` enabled is stored on-chain: + - `instinctID`: `0xINSTINCT3` + - `temptationValue`: `+25` + - `triggerConditions`: Renewable energy supply exceeds 80% of grid capacity + - `autoExecution`: `true` + - **Expected Output**: When the trigger condition is met (as verified by an oracle providing energy grid data), the smart contract automatically executes the transaction associated with the instinct, such as reallocating energy resources. AI agents are informed of the action through the blockchain and adjust their off-chain computations accordingly. + +### 4. Learning and Strategy Update + +- **Test Case 4.1: Labeling an Instinct with Cost** + + - **Input**: After pursuing an instinct, the AI agent calculates the actual cost incurred (e.g., high computational resources) and records this off-chain. The agent then calls `labelInstinct(instinctID, cost)` to update the cost associated with the instinct: + - `instinctID`: `0xINSTINCT2` + - `cost`: `-10` (representing significant resource usage) + - **Expected Output**: The cost label is updated on-chain for `0xINSTINCT2`. Other AI agents can access this information if the system is designed to share such data, enhancing collective learning. + +- **Test Case 4.2: Updating Agent Strategy** + + - **Input**: The AI agent updates its strategy off-chain by adjusting its decision-making algorithms to account for the high cost associated with `0xINSTINCT2`. + - **Expected Output**: In future evaluations, the agent deprioritizes instincts with high associated costs, opting for actions that offer a better reward-to-cost ratio. + +### 5. Dynamic Instinct Adjustment + +- **Test Case 5.1: Instinct Updating Based on External Data** + + - **Input**: A dynamic instinct is set up with: + - `instinctID`: `0xINSTINCT4` + - `temptationValue`: Initially `+10` + - `triggerConditions`: Network congestion level (gas prices) + - `autoExecution`: `false` + - **Expected Output**: As network congestion decreases (gas prices drop), the temptation value of the instinct automatically increases. For example, if gas prices fall below 30 Gwei, the temptation value updates to `+20`. AI agents receive this updated information when they next query the blockchain and adjust their off-chain computations accordingly. + +### 6. Verification of Off-Chain Computations + +- **Test Case 6.1: Verifying Agent Actions On-Chain** + + - **Input**: An AI agent completes a complex computation off-chain related to Instinct `0xINSTINCT5` and submits a proof to the blockchain via `actOnInstinct(instinctID, agentID, proofData)` where: + - `instinctID`: `0xINSTINCT5` + - `agentID`: `0xAGENT2` + - `proofData`: Data verifying the completion of the off-chain task (could be a zero-knowledge proof or other verification method) + - **Expected Output**: The smart contract validates the proof using on-chain logic or external verifiers. If the proof is valid and trigger conditions are met, the blockchain executes the associated transaction (e.g., rewarding the agent). This ensures the integrity of off-chain computations and builds trust in the system. + +These test cases demonstrate how AI agents interact with the blockchain to retrieve instincts, execute off-chain computations, and how the blockchain automates transactions and verifies outcomes based on these shared rules. + +## Security Considerations + +1. **Instinct Integrity**: Ensure that instincts and their attributes are immutable and protected against tampering. +2. **AI-Agent Security**: Implement safeguards to prevent AI agents from being manipulated into making harmful or suboptimal decisions. +3. **Data Privacy**: Ensure that the data used to trigger instincts and guide decision-making is securely handled and protected. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). \ No newline at end of file