> ## Documentation Index
> Fetch the complete documentation index at: https://docs.synclear.io/llms.txt
> Use this file to discover all available pages before exploring further.

# On-Chain Audit Trail for AI Agent Transactions in Synclear

> How Synclear's MandateExecution event log works, how to query it on-chain or via API, and how to use it for compliance reporting and reconciliation.

Every transaction executed by a mandate-authorized AI agent emits a `MandateExecution` event from the `MandateRegistry` contract at the moment of execution. These events are part of the canonical chain state — immutable, permissionlessly queryable, and independent of Synclear's own infrastructure. They constitute the authoritative record of what every agent did, when, under which mandate, and with what effect on protocol positions.

The audit trail is not a reporting feature layered on top of agent execution. It is a direct output of the execution mechanism itself: if an agent transaction occurred, a `MandateExecution` event exists. If no event exists for a claimed transaction, the transaction did not occur under a valid mandate.

## Event Structure

The `MandateExecution` event carries a standardized set of fields designed to support financial reconciliation without requiring additional off-chain context:

```solidity theme={null}
event MandateExecution(
    address indexed agentAddress,
    bytes32 indexed mandateId,
    uint8   actionType,        // maps to BORROW | REPAY | DEPOSIT | WITHDRAW | SWAP
    address asset,
    uint256 amount,
    uint256 timestamp,
    bytes32 positionId,        // resulting or affected position identifier
    int256  positionDelta,     // change in position size (positive = increase)
    uint8   executionStatus    // 0 = SUCCESS, 1 = PARTIAL, 2 = FAILED_POST_HOOK
);
```

Each field maps to a standard financial reporting dimension:

* `agentAddress` — the executing party (agent)
* `mandateId` — the authorization under which the action was taken
* `actionType` — the economic nature of the transaction
* `asset` + `amount` — the instrument and notional value
* `timestamp` — the block-level timestamp of execution
* `positionId` + `positionDelta` — the resulting change in on-chain positions
* `executionStatus` — whether the action completed fully, partially, or with a post-execution warning

## Querying the Audit Trail

### On-Chain Event Queries

Principals, auditors, and agents themselves can query the full event history directly from a node using standard event filter patterns:

```js theme={null}
const events = await mandateRegistry.queryFilter(
  mandateRegistry.filters.MandateExecution(agentAddress),
  fromBlock,
  toBlock
);
```

To retrieve all executions across all agents for a specific mandate:

```js theme={null}
const events = await mandateRegistry.queryFilter(
  mandateRegistry.filters.MandateExecution(null, mandateId),
  fromBlock,
  toBlock
);
```

Each element in the returned array is an `ethers.js` `EventLog` object with a `args` property containing the decoded event fields. No Synclear API key or authentication is required to perform these queries — they run directly against any archive node with access to the contract's deployment block.

### Synclear Audit API

For higher-level queries — filtered by date range, action type, asset, or position — the Synclear Audit API provides a REST interface over the indexed event data:

```js theme={null}
const response = await fetch(
  `https://api.synclear.io/v1/agents/${agentAddress}/audit-trail?` +
  `from=2024-01-01T00:00:00Z&to=2024-03-31T23:59:59Z&actionType=DEPOSIT`,
  { headers: { Authorization: `Bearer ${apiKey}` } }
);
const { events, totalCount, nextCursor } = await response.json();
```

The API response includes all `MandateExecution` event fields plus enriched metadata: human-readable asset symbols, USD-equivalent amounts at execution time (sourced from the on-chain price oracle), and resolved mandate labels if set by the principal.

## Using the Audit Trail

<Tabs>
  <Tab title="Compliance Reporting">
    Compliance teams can reconstruct a complete agent activity history for any time period by querying the `MandateExecution` event log. Because events include both the mandate ID and the action type, it is straightforward to verify that every agent action was within the scope of an active mandate at the time of execution.

    The event log supports the following common compliance reporting needs:

    * **Transaction-level activity reports** — all agent transactions within a reporting period, with notional amounts and timestamps
    * **Mandate adherence verification** — confirmation that all activity was authorized by a valid, active mandate
    * **Position change reconstruction** — rebuilding the sequence of position modifications from `positionDelta` fields
    * **Counterparty and asset exposure summaries** — aggregations of volume by asset and action type
  </Tab>

  <Tab title="Reconciliation">
    Operations and finance teams can use the audit trail to reconcile on-chain agent activity against off-chain records (treasury management systems, accounting ledgers, risk systems). The `positionId` and `positionDelta` fields provide the necessary link between the event log and Synclear's position accounting.

    For reconciliation workflows, query the audit trail for the relevant time window and cross-reference `positionDelta` values against expected position movements. Any discrepancy between the on-chain record and off-chain systems should be investigated as a data quality issue in the off-chain system — the on-chain record is the authoritative source.
  </Tab>

  <Tab title="Agent Monitoring">
    Agent developers and operators can use the audit trail as a real-time operational monitoring feed. Subscribing to `MandateExecution` events via WebSocket provides low-latency confirmation of execution and position outcomes:

    ```js theme={null}
    mandateRegistry.on(
      mandateRegistry.filters.MandateExecution(agentAddress),
      (event) => {
        const { actionType, amount, asset, executionStatus } = event.args;
        // handle execution confirmation
        console.log(`Execution confirmed: ${actionType} ${amount} of ${asset}`);
        if (executionStatus !== 0n) {
          alertOps(`Non-success execution status: ${executionStatus}`);
        }
      }
    );
    ```

    This pattern allows agent implementations to confirm that their submitted transactions produced the expected on-chain outcomes and to detect partial execution or post-hook warnings that may require follow-up action.
  </Tab>

  <Tab title="Dispute Resolution">
    In the event of a dispute between a principal and an agent (or between Synclear and a counterparty), the `MandateExecution` event log provides a cryptographically verifiable record that neither party can alter. Any claim about what an agent did or did not do can be settled by reference to the on-chain log.

    The immutability of the record also means that auditors engaged by a principal can verify the completeness of any activity report produced by Synclear or by the agent operator — by comparing the report against a direct node query, they can confirm that no events have been omitted or altered.
  </Tab>
</Tabs>

## Data Retention and Archival

<Note>
  On-chain event data is retained permanently as part of the blockchain's canonical state and is accessible from any archive node indefinitely. Synclear's indexed API layer maintains a queryable index of all `MandateExecution` events from the contract's deployment block forward. For events older than 12 months, the API may route queries to a cold-storage archive tier with response times up to 30 seconds for large result sets. Direct on-chain queries via `queryFilter` are not subject to any retention policy and will always return the complete historical record, provided the querying node is a full archive node.
</Note>

Principals with regulatory obligations requiring long-term audit record retention are advised to maintain their own archive of `MandateExecution` events by running an event indexer against the contract. Synclear provides a reference indexer implementation and schema for common database backends in the developer resources section.
