# Core Contracts

### BAP578.sol

The main contract implementing the Non-Fungible Agent token standard.

#### Overview

BAP578 extends ERC-721 to create autonomous agent tokens with extended metadata and action execution capabilities.

#### Key Features

* Agent creation with extended metadata
* Action execution via delegatecall
* Logic upgradeability
* Agent state management
* Circuit breaker integration

#### Functions

**createAgent(address to, address logicAddress, string memory metadataURI, AgentMetadata memory extendedMetadata)**

Creates a new agent token with extended metadata.

Parameters:

* to: The address that will own the agent
* logicAddress: The address of the logic contract
* metadataURI: The URI for the agent's metadata
* extendedMetadata: The extended metadata for the agent

Returns: uint256 tokenId — The ID of the new agent token

**executeAction(uint256 tokenId, bytes calldata data)**

Executes an action using the agent's logic contract.

Parameters:

* tokenId: The ID of the agent token
* data: Encoded function call data

Returns: bytes memory result — The result of the action execution

**setLogicAddress(uint256 tokenId, address newLogic)**

Updates the logic address for the agent.

Parameters:

* tokenId: The ID of the agent token
* newLogic: The address of the new logic contract

Requirements:

* Caller must be the owner of the token
* New logic address cannot be zero

**fundAgent(uint256 tokenId)**

Funds the agent with BNB for gas fees.

Parameters:

* tokenId: The ID of the agent token

Payable: Yes — sends BNB to the agent

**getState(uint256 tokenId)**

Returns the current state of the agent.

Parameters:

* tokenId: The ID of the agent token

Returns: State memory — The agent's state

**pause(uint256 tokenId) / unpause(uint256 tokenId)**

Pauses or resumes the agent.

Parameters:

* tokenId: The ID of the agent token

Requirements:

* Caller must be the owner of the token

**terminate(uint256 tokenId)**

Terminates the agent permanently and returns any remaining balance.

Parameters:

* tokenId: The ID of the agent token

Requirements:

* Caller must be the owner of the token
* Agent must not already be terminated

#### 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);
```

#### Data Structures

```solidity
enum Status {
    Paused,
    Active,
    Terminated
}

struct State {
    uint256 balance;           // Agent's BNB balance
    Status status;             // Current status
    address owner;             // Current owner
    address logicAddress;      // Logic contract address
    uint256 lastActionTimestamp; // Last action time
}

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

***

### AgentFactory.sol

Factory contract for deploying new agent tokens with customizable templates.

#### Overview

AgentFactory provides a standardized way to create new agent contracts with consistent initialization and template management.

#### Key Features

* Template management (approval, revocation)
* Agent creation with consistent initialization
* Version tracking for templates
* Learning module support
* Fee collection

#### Functions

**createAgent(string memory name, string memory symbol, address logicAddress, string memory metadataURI, AgentMetadata memory extendedMetadata)**

Creates a new agent with extended metadata.

Parameters:

* name: The name of the agent token collection
* symbol: The symbol of the agent token collection
* logicAddress: The address of the logic contract
* metadataURI: The URI for the agent's metadata
* extendedMetadata: The extended metadata for the agent

Returns: address agent — The address of the new agent contract

Payable: Yes — requires 0.01 BNB creation fee

**approveTemplate(address template, string memory category, string memory version)**

Approves a new template for agent creation.

Parameters:

* template: The address of the template contract
* category: The category of the template
* version: The version of the template

Requirements:

* Caller must be the owner

**getLatestTemplate(string memory category)**

Gets the latest template for a category.

Parameters:

* category: The category of the template

Returns: address — The address of the latest template

#### Events

```solidity
event AgentCreated(
    address indexed agent,
    address indexed owner,
    uint256 tokenId,
    address logic
);
event TemplateApproved(address indexed template, string category, string version);
event AgentCreationFeeCollected(address indexed creator, uint256 amount);
```

***

### CircuitBreaker.sol

Emergency shutdown mechanism for the BORT ecosystem.

#### Overview

CircuitBreaker provides a way to pause the system in case of emergencies, protecting users and their assets.

#### Key Features

* Global pause for system-wide emergencies
* Contract-specific pauses for targeted intervention
* Multi-level authorization (governance and emergency multi-sig)

#### Functions

**setGlobalPause(bool paused)**

Sets the global pause state.

Parameters:

* paused: Whether to pause the system globally

Requirements:

* Caller must be governance or emergency multi-sig

**setContractPause(address contractAddress, bool paused)**

Sets the pause state for a specific contract.

Parameters:

* contractAddress: The address of the contract to pause
* paused: Whether to pause the contract

**isContractPaused(address contractAddress)**

Checks if a contract is paused.

Parameters:

* contractAddress: The address of the contract to check

Returns: bool — Whether the contract is paused

#### Events

```solidity
event GlobalPauseUpdated(bool paused);
event ContractPauseUpdated(address indexed contractAddress, bool paused);
```

***

### BAP578Governance.sol

Governance contract for protocol-level decisions.

#### Overview

BAP578Governance manages the governance of the BORT ecosystem, including protocol upgrades, parameter changes, and emergency actions.

#### Key Features

* Proposal creation and voting
* Protocol parameter management
* Emergency circuit breaker control
* Treasury fund allocation

#### Functions

**createProposal(string memory description, bytes memory callData, address targetContract)**

Creates a new governance proposal.

Parameters:

* description: Description of the proposal
* callData: Encoded function call data
* targetContract: The contract to execute the proposal on

Returns: uint256 proposalId — The ID of the new proposal

**castVote(uint256 proposalId, bool support)**

Casts a vote on a proposal.

Parameters:

* proposalId: The ID of the proposal
* support: Whether to support the proposal

**executeProposal(uint256 proposalId)**

Executes an approved proposal.

Parameters:

* proposalId: The ID of the proposal to execute

Requirements:

* Proposal must be approved
* Execution delay must have passed

#### Events

```solidity
event ProposalCreated(uint256 indexed proposalId, address indexed proposer, string description);
event VoteCast(uint256 indexed proposalId, address indexed voter, bool support, uint256 weight);
event ProposalExecuted(uint256 indexed proposalId);
```

***

### BAP578Treasury.sol

Treasury management for the BORT ecosystem.

#### Overview

BAP578Treasury manages the funds allocated for ecosystem development, grants, and other initiatives.

#### Key Features

* Fund allocation and distribution
* Multi-signature approval for withdrawals
* Transparent fund tracking
* Grant program management

#### Functions

**donate(string memory message)**

Donates funds to the treasury.

Parameters:

* message: Optional message with the donation

Payable: Yes — sends BNB to the treasury

**allocateFunds(address recipient, uint256 amount, string memory purpose)**

Allocates funds for a specific purpose.

Parameters:

* recipient: The address to receive the funds
* amount: The amount to allocate
* purpose: The purpose of the allocation

Returns: uint256 allocationId — The ID of the allocation

**executeAllocation(uint256 allocationId)**

Executes an approved allocation.

Parameters:

* allocationId: The ID of the allocation to execute

Requirements:

* Allocation must be approved by required signers

#### Events

```solidity
event DonationReceived(address indexed donor, uint256 amount, string message);
event FundsAllocated(uint256 indexed allocationId, address recipient, uint256 amount, string purpose);
event AllocationExecuted(uint256 indexed allocationId);
```

***

## Learning System Contracts

### MerkleTreeLearning.sol

Core learning module implementing Merkle tree-based learning.

#### Overview

MerkleTreeLearning provides cryptographically verifiable learning capabilities for agents using Merkle trees.

#### Key Features

* Merkle tree root storage for learning data integrity
* Learning metrics tracking
* Rate limiting to prevent spam
* Milestone system for achievements
* Cryptographic verification for all learning claims

#### Functions

**updateLearning(uint256 tokenId, LearningUpdate calldata update)**

Updates the learning state of an agent.

Parameters:

* tokenId: The ID of the agent token
* update: The learning update data

**recordInteraction(uint256 tokenId, string calldata interactionType, bool success)**

Records an interaction for learning purposes.

Parameters:

* tokenId: The ID of the agent token
* interactionType: The type of interaction
* success: Whether the interaction was successful

**getLearningMetrics(uint256 tokenId)**

Gets the learning metrics for an agent.

Parameters:

* tokenId: The ID of the agent token

Returns: LearningMetrics memory — The learning metrics

#### Data Structures

```solidity
struct LearningMetrics {
    uint256 totalInteractions;    // Total user interactions
    uint256 learningEvents;       // Significant learning updates
    uint256 lastUpdateTimestamp;  // Last learning update time
    uint256 learningVelocity;     // Learning rate (scaled by 1e18)
    uint256 confidenceScore;      // Overall confidence (scaled by 1e18)
}

struct LearningUpdate {
    bytes32 previousRoot;         // Previous Merkle root
    bytes32 newRoot;              // New Merkle root
    bytes32[] proof;              // Merkle proof for update
    bytes metadata;               // Encoded learning data
}
```

***

## Interface Contracts

### IBAP578.sol

Core interface defining BAP-578 functionality.

```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);
}
```

***

### ILearningModule.sol

Interface for learning module implementations.

```solidity
interface ILearningModule {
    struct LearningMetrics {
        uint256 totalInteractions;
        uint256 learningEvents;
        uint256 lastUpdateTimestamp;
        uint256 learningVelocity;
        uint256 confidenceScore;
    }
    
    struct LearningUpdate {
        bytes32 previousRoot;
        bytes32 newRoot;
        bytes32[] proof;
        bytes metadata;
    }
    
    function updateLearning(uint256 tokenId, LearningUpdate calldata update) external;
    function verifyLearning(uint256 tokenId, bytes32 claim, bytes32[] calldata proof) external view returns (bool);
    function getLearningMetrics(uint256 tokenId) external view returns (LearningMetrics memory);
    function recordInteraction(uint256 tokenId, bytes calldata interactionData) external;
    function isLearningEnabled(uint256 tokenId) external view returns (bool);
}
```

***

## Gas Estimates

### Typical Gas Costs

| Operation             | Gas Cost  | Notes                        |
| --------------------- | --------- | ---------------------------- |
| Create Simple Agent   | \~200,000 | Basic agent creation         |
| Create Learning Agent | \~250,000 | Agent with learning enabled  |
| Execute Action        | \~100,000 | Basic action execution       |
| Update Learning       | \~80,000  | Learning tree update         |
| Record Interaction    | \~30,000  | Simple interaction recording |
| Fund Agent            | \~50,000  | Send BNB to agent            |
| Pause/Unpause         | \~40,000  | Change agent status          |

### Gas Optimization Tips

{% stepper %}
{% step %}

### Batch Operations

Combine multiple operations when possible to reduce per-operation overhead and amortize gas costs.
{% endstep %}

{% step %}

### Compress Data

Use compressed formats for large data payloads to reduce storage and transfer costs.
{% endstep %}

{% step %}

### Lazy Loading

Only load data when needed rather than eagerly reading and storing all state.
{% endstep %}

{% step %}

### Efficient Storage

Use appropriate data types (e.g., smaller integers, packed structs) to save storage slots.
{% endstep %}

{% step %}

### Gas Estimation

Always estimate gas before transactions to choose appropriate gas limits and avoid overpaying.
{% endstep %}
{% endstepper %}

***

## Error Codes

### Common Error Messages

* "BAP578: caller is not agent owner" — Only agent owner can perform this action
* "BAP578: agent not active" — Agent must be active to perform this action
* "BAP578: global pause active" — System is globally paused
* "BAP578: logic address is zero" — Logic address cannot be zero
* "AgentFactory: incorrect fee amount" — Must pay exact creation fee
* "AgentFactory: template not approved" — Template must be approved
* "Rate limit exceeded" — Too many learning updates today
* "Invalid learning proof" — Merkle proof verification failed
