# Token standard

BAP-578 is a token standard that extends ERC-721 to create autonomous agent tokens with programmable behavior and optional learning capabilities.

## Standard Overview

### ERC-721 Extension

BAP-578 maintains full compatibility with ERC-721 while adding agent-specific functionality:

* Unique token IDs and ownership
* Safe transfer mechanisms
* Metadata URI referencing
* Approval and operator systems

### Agent-Specific Extensions

Additional functionality for autonomous behavior:

* Action execution via delegatecall
* State management and persistence
* Logic contract upgradeability
* Learning system integration

## Core Interfaces

### IBAP578 Interface

Defines the core functionality for BAP-578 compliant tokens:

{% code title="IBAP578.sol" %}

```solidity
interface IBAP578 {
    enum Status { Paused, Active, Terminated }
    
    struct State {
        uint256 balance;
        Status status;
        address owner;
        address logicAddress;
        uint256 lastActionTimestamp;
    }
    
    struct AgentMetadata {
        string persona;
        string experience;
        string voiceHash;
        string animationURI;
        string vaultURI;
        bytes32 vaultHash;
    }
    
    function createAgent(
        address to,
        address logicAddress,
        string memory metadataURI,
        AgentMetadata memory extendedMetadata
    ) external returns (uint256 tokenId);
    
    function executeAction(uint256 tokenId, bytes calldata data) external returns (bytes memory);
    function setLogicAddress(uint256 tokenId, address newLogic) external;
    function fundAgent(uint256 tokenId) external payable;
    function getState(uint256 tokenId) external view returns (State memory);
    function pause(uint256 tokenId) external;
    function unpause(uint256 tokenId) external;
    function terminate(uint256 tokenId) external;
    function getAgentMetadata(uint256 tokenId) external view returns (AgentMetadata memory);
}
```

{% endcode %}

## Data Structures

### Agent State

Represents the current state of an agent:

{% code title="State struct" %}

```solidity
struct State {
    uint256 balance;           // Agent's BNB balance
    Status status;             // Current status (Active/Paused/Terminated)
    address owner;             // Current owner address
    address logicAddress;      // Logic contract address
    uint256 lastActionTimestamp; // Last action execution time
}
```

{% endcode %}

### Agent Metadata

Extended metadata for agent personality and capabilities:

{% code title="AgentMetadata struct" %}

```solidity
struct AgentMetadata {
    string persona;           // JSON-encoded character traits
    string experience;        // Agent's role and purpose
    string voiceHash;         // Audio profile reference
    string animationURI;      // Animation/avatar URI
    string vaultURI;          // Extended data storage URI
    bytes32 vaultHash;        // Vault content verification hash
}
```

{% endcode %}

## Standard Functions

### Agent Creation

{% code title="createAgent" %}

```solidity
function createAgent(
    address to,
    address logicAddress,
    string memory metadataURI,
    AgentMetadata memory extendedMetadata
) external returns (uint256 tokenId);
```

{% endcode %}

### Action Execution

{% code title="executeAction" %}

```solidity
function executeAction(uint256 tokenId, bytes calldata data) external returns (bytes memory result);
```

{% endcode %}

### Logic Management

{% code title="setLogicAddress" %}

```solidity
function setLogicAddress(uint256 tokenId, address newLogic) external;
```

{% endcode %}

### State Management

{% code title="pause / unpause / terminate" %}

```solidity
function pause(uint256 tokenId) external;
function unpause(uint256 tokenId) external;
function terminate(uint256 tokenId) external;
```

{% endcode %}

### Funding

{% code title="fundAgent" %}

```solidity
function fundAgent(uint256 tokenId) external payable;
```

{% endcode %}

## Events

### Core Events

{% code title="Events" %}

```solidity
event ActionExecuted(address indexed agent, bytes result);
event LogicUpgraded(address indexed agent, address oldLogic, address newLogic);
event AgentFunded(address indexed agent, address indexed funder, uint256 amount);
event StatusChanged(address indexed agent, Status newStatus);
event MetadataUpdated(uint256 indexed tokenId, string metadataURI);
```

{% endcode %}

## Compliance Requirements

### ERC-721 Compliance

* Must implement all required ERC-721 functions
* Must emit Transfer events for ownership changes
* Must support safe transfer mechanisms
* Must implement metadata URI functionality

### BAP-578 Extensions

* Must implement IBAP578 interface
* Must support action execution via delegatecall
* Must maintain agent state variables
* Must support logic contract upgrades
* Must implement circuit breaker integration

## Security Considerations

### Access Control

* Only token owners can modify agent behavior
* Logic contracts must implement proper access controls
* Circuit breaker can pause agent operations
* Learning updates require cryptographic verification

### Reentrancy Protection

* All external calls protected against reentrancy
* Delegatecall operations have gas limits
* State updates occur before external calls

### Input Validation

* All function parameters validated
* Logic contract addresses cannot be zero
* Metadata must conform to expected format
* Learning data must be cryptographically verified

## Gas Optimization

### Storage Efficiency

* Packed structs minimize storage slots
* Off-chain storage for large data
* Merkle trees for learning verification
* Batch operations for multiple updates

### Execution Efficiency

* Delegatecall for logic execution
* Gas limits prevent out-of-gas attacks
* Lazy loading for expensive operations
* Compressed data formats

## Upgradeability

### Logic Contract Upgrades

* Agents can upgrade their logic contracts
* Old logic contracts remain accessible
* Upgrade events track changes
* Backward compatibility maintained

### Learning Module Upgrades

* Learning agents can upgrade learning modules
* Migration data preserves learning history
* Cryptographic verification ensures integrity
* Cross-chain migration support

## Interoperability

### Cross-Contract Interaction

* Agents can interact with any smart contract
* Standard interfaces for common operations
* Event-based communication
* Callback mechanisms for responses

### Cross-Chain Support

* Agent data can be migrated between chains
* Learning history preserved across chains
* Cross-chain verification mechanisms
* Bridge integration for asset transfers

## Standard Compliance

### Implementation Checklist

* [ ] Implements ERC-721 interface
* [ ] Implements IBAP578 interface
* [ ] Supports action execution
* [ ] Maintains agent state
* [ ] Implements access controls
* [ ] Supports circuit breaker
* [ ] Emits required events
* [ ] Validates all inputs
* [ ] Handles edge cases
* [ ] Includes comprehensive tests

### Testing Requirements

* Unit tests for all functions
* Integration tests for workflows
* Gas optimization tests
* Security vulnerability tests
* Upgrade mechanism tests
* Cross-chain migration tests

The BAP-578 token standard provides a comprehensive framework for creating autonomous agents while maintaining compatibility with existing NFT infrastructure and ensuring security, upgradeability, and interoperability.
