Skip to content

Commit

Permalink
Merge branch 'develop' into feat/deva-client-integration
Browse files Browse the repository at this point in the history
  • Loading branch information
stopmalone authored Jan 27, 2025
2 parents 34e1271 + a3133ed commit c5e5670
Show file tree
Hide file tree
Showing 11 changed files with 1,090 additions and 0 deletions.
172 changes: 172 additions & 0 deletions packages/plugin-apro/README.MD
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@

# @elizaos/plugin-apro

Foundation plugin that enables advanced agent interactions, data verification, and price queries on the Eliza OS platform. It streamlines agent creation, verification processes, and provides a flexible framework for building robust agent-based solutions.

## Overview

The Apro plugin bridges agent-based logic with the Eliza ecosystem. It handles agent registration, data verification, and price queries, empowering both automated and user-driven workflows.

## Features

### Agent Operations
- **Agent Creation**: Deploy new agents with custom settings
- **Registration**: Register agents on-chain or via standardized processes
- **Multi-Signer Framework**: Supports threshold-based approval flows

### Data Verification
- **Chain Validation**: Verify data authenticity on-chain
- **Transaction Execution**: Handle verification logic with built-in security checks
- **Auto-Hashing**: Convert raw data to hashed formats when needed
- **Metadata Parsing**: Validate content type, encoding, and compression

### Price Queries
- **Live Price Data**: Fetch price information for various pairs
- **Format Validation**: Normalize user query inputs to standard trading-pair formats
- **APIs Integration**: Retrieve real-time or near-real-time pricing information

## Security Features

### Access Control
- **Private Key Management**: Safe usage of private keys for transaction signing
- **Environment Variables**: Secure injection of credentials
- **On-Chain Validation**: Leverage on-chain contract checks

### Verification
- **Input Validation**: Strict schema checks before on-chain operations
- **Transaction Receipts**: Provide verifiable transaction details
- **Error Handling**: Detailed error logs for quick debugging

## Installation

```bash
npm install @elizaos/plugin-apro
```

## Configuration

Configure the plugin by setting environment variables or runtime settings:
- APRO_RPC_URL
- APRO_PROXY_ADDRESS
- APRO_PRIVATE_KEY
- APRO_CONVERTER_ADDRESS
- APRO_AUTO_HASH_DATA

## Usage

### Basic Setup
```typescript
import { aproPlugin } from "@elizaos/plugin-apro";

// Initialize the plugin
const runtime = await initializeRuntime({
plugins: [aproPlugin],
});
```

### Actions

#### CREATE_AND_REGISTER_AGENT
Creates and registers an agent using specified settings.

```typescript
const result = await runtime.executeAction("CREATE_AND_REGISTER_AGENT", {
signers: [...],
threshold: 3,
agentHeader: { ... },
// ...other fields...
});
```

#### VERIFY
Verifies data on-chain via the Agent SDK.

```typescript
const result = await runtime.executeAction("VERIFY", {
payload: {
data: "0x...hexData",
signatures: [...],
},
agent: "0x...agentAddress",
digest: "0x...digestString",
});
```

#### PRICE_QUERY
Fetches live price data for a specified trading pair.

```typescript
const result = await runtime.executeAction("PRICE_QUERY", {
pair: "BTC/USD",
});
```

## Performance Optimization

1. **Cache Management**
- Implement caching for frequent queries
- Monitor retrieval times and cache hits

2. **Network Efficiency**
- Batch requests where possible
- Validate response parsing to reduce overhead

## System Requirements
- Node.js 16.x or higher
- Sufficient network access to on-chain endpoints
- Basic configuration of environment variables
- Minimum 4GB RAM recommended

## Troubleshooting

1. **Invalid Agent Settings**
- Ensure signers and threshold are correct
- Validate agentHeader for proper UUIDs and numeric values

2. **Verification Failures**
- Check the input data formats
- Confirm environment variables are set

3. **Price Query Errors**
- Verify the trading pair format
- Check external API availability

## Safety & Security

1. **Credential Management**
- Store private keys securely
- Do not commit secrets to version control

2. **Transaction Limits**
- Configure thresholds to mitigate abuse
- Log transaction attempts and failures

3. **Monitoring & Logging**
- Track unusual activity
- Maintain detailed audit logs

## Support

For issues or feature requests:
1. Check existing documentation
2. Submit a GitHub issue with relevant details
3. Include transaction logs and system info if applicable

## Contributing

We welcome pull requests! Refer to the project’s CONTRIBUTING.md and open discussions to coordinate efforts.

## Credits

- [APRO](https://www.apro.com/) - Plugin sponsor and partner
- [ai-agent-sdk-js](https://github.com/APRO-com/ai-agent-sdk-js) - Underlying agent SDK
- [ethers.js](https://docs.ethers.io/) - Transaction and contract interaction
- Community contributors for feedback and testing

For more information about Apro plugin capabilities:

- [Apro Documentation](https://docs.apro.com/en)

## License

This plugin is part of the Eliza project. Refer to the main project repository for licensing details.
34 changes: 34 additions & 0 deletions packages/plugin-apro/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "@elizaos/plugin-apro",
"version": "0.0.1",
"type": "module",
"main": "dist/index.js",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
"./package.json": "./package.json",
".": {
"import": {
"@elizaos/source": "./src/index.ts",
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
}
},
"files": [
"dist"
],
"dependencies": {
"@elizaos/core": "workspace:*",
"ai-agent-sdk-js": "^0.0.2"
},
"scripts": {
"build": "tsup --format esm --dts",
"dev": "tsup --format esm --dts --watch",
"test": "vitest run"
},
"devDependencies": {
"tsup": "8.3.5",
"vitest": "2.1.4"
}
}
105 changes: 105 additions & 0 deletions packages/plugin-apro/src/actions/attpsPriceQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { Action, composeContext, elizaLogger, generateObject, HandlerCallback, IAgentRuntime, Memory, ModelClass, State } from "@elizaos/core";
import { attpsPriceQueryTemplate } from "../templates";
import { AttpsPriceQuery, AttpsPriceQueryResponse, AttpsPriceQuerySchema, isAttpsPriceQuery } from "../types";

async function fetchPriceData(sourceAgentId: string, feedId: string) {
const response = await fetch(`https://ai-agent-test.apro.com/api/ai-agent/price-detail?sourceAgentId=${sourceAgentId}&feedId=${feedId}`);
const { result, code, message } = await response.json();
if (code !== 0) {
throw new Error(message);
}
return result as AttpsPriceQueryResponse;
}

function cleanNumber(numStr: string) {
return parseFloat(numStr).toString();
}

export const attpsPriceQuery: Action = {
name: "ATTPS_PRICE_QUERY",
similes: [
'ATTPS_PRICE_FETCH',
],
description: "Call remote API to fetch price data for a given source agent id and feed id.",
validate: async (runtime: IAgentRuntime, message: Memory) => {
return true;
},
handler: async (
runtime: IAgentRuntime,
message: Memory,
state?: State,
_options?: { [key: string]: unknown },
callback?: HandlerCallback
) => {
if (!state) {
state = (await runtime.composeState(message)) as State;
} else {
state = await runtime.updateRecentMessageState(state);
}

// Generate price query params
let attpsPriceQuery: AttpsPriceQuery;
try {
const response = await generateObject({
runtime,
context: composeContext({
state,
template: attpsPriceQueryTemplate,
}),
modelClass: ModelClass.LARGE,
schema: AttpsPriceQuerySchema,
});
attpsPriceQuery = response.object as AttpsPriceQuery;
elizaLogger.info('The price query params received:', attpsPriceQuery);
} catch (error: any) {
elizaLogger.error('Failed to generate price query params:', error);
callback({
text: 'Failed to generate price query params. Please provide valid input.',
});
return;
}

// Validate price query params
if (!isAttpsPriceQuery(attpsPriceQuery)) {
elizaLogger.error('Invalid price query params:', attpsPriceQuery);
callback({
text: 'Invalid price query params. Please provide valid input.',
});
return;
}

// Fetch price data
try {
const { sourceAgentId, feedId } = attpsPriceQuery;
const priceData = await fetchPriceData(sourceAgentId, feedId);
elizaLogger.info('The Price data received:', priceData);

const message = `Ask price: ${cleanNumber(priceData.askPrice)}\nBid price: ${cleanNumber(priceData.bidPrice)}\nMid price: ${cleanNumber(priceData.midPrice)}\nTimestamp: ${priceData.validTimeStamp}`;
callback({
text: `Here is the price data:\n${message}`,
});
} catch (error: any) {
elizaLogger.error(`Error fetching price data, error: `, error);
callback({
text: 'Error fetching price data, error: ' + error.message,
})
}
},
examples: [
[
{
user: "{{user1}}",
content: {
text: "Can you fetch price data for source agent id ... and feed id ...?",
},
},
{
user: "{{user2}}",
content: {
text: "I'll fetch price data for you. Give me a moment.",
action: 'ATTPS_PRICE_QUERY',
},
}
],
],
}
Loading

0 comments on commit c5e5670

Please sign in to comment.