Skip to content

Commit a3133ed

Browse files
authored
feat(new-plugin): support apro plugin (elizaOS#2794)
* feat: add plugin-apro * fix: improve error handling and update dependencies in plugin-apro * fix: update logging and improve message handling in priceQuery and verifyData actions * feat: enhance templates for agent configuration and trading pair extraction with strict validation rules * feat: refine trading pair extraction rules and enhance price query action logging * Create README.MD for plugin-apro * feat: implement ATTPS price query action with validation and API integration * feat: add number cleaning function for price data formatting in ATTPS price query
1 parent 4e62ac9 commit a3133ed

11 files changed

+1090
-0
lines changed

packages/plugin-apro/README.MD

+172
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
2+
# @elizaos/plugin-apro
3+
4+
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.
5+
6+
## Overview
7+
8+
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.
9+
10+
## Features
11+
12+
### Agent Operations
13+
- **Agent Creation**: Deploy new agents with custom settings
14+
- **Registration**: Register agents on-chain or via standardized processes
15+
- **Multi-Signer Framework**: Supports threshold-based approval flows
16+
17+
### Data Verification
18+
- **Chain Validation**: Verify data authenticity on-chain
19+
- **Transaction Execution**: Handle verification logic with built-in security checks
20+
- **Auto-Hashing**: Convert raw data to hashed formats when needed
21+
- **Metadata Parsing**: Validate content type, encoding, and compression
22+
23+
### Price Queries
24+
- **Live Price Data**: Fetch price information for various pairs
25+
- **Format Validation**: Normalize user query inputs to standard trading-pair formats
26+
- **APIs Integration**: Retrieve real-time or near-real-time pricing information
27+
28+
## Security Features
29+
30+
### Access Control
31+
- **Private Key Management**: Safe usage of private keys for transaction signing
32+
- **Environment Variables**: Secure injection of credentials
33+
- **On-Chain Validation**: Leverage on-chain contract checks
34+
35+
### Verification
36+
- **Input Validation**: Strict schema checks before on-chain operations
37+
- **Transaction Receipts**: Provide verifiable transaction details
38+
- **Error Handling**: Detailed error logs for quick debugging
39+
40+
## Installation
41+
42+
```bash
43+
npm install @elizaos/plugin-apro
44+
```
45+
46+
## Configuration
47+
48+
Configure the plugin by setting environment variables or runtime settings:
49+
- APRO_RPC_URL
50+
- APRO_PROXY_ADDRESS
51+
- APRO_PRIVATE_KEY
52+
- APRO_CONVERTER_ADDRESS
53+
- APRO_AUTO_HASH_DATA
54+
55+
## Usage
56+
57+
### Basic Setup
58+
```typescript
59+
import { aproPlugin } from "@elizaos/plugin-apro";
60+
61+
// Initialize the plugin
62+
const runtime = await initializeRuntime({
63+
plugins: [aproPlugin],
64+
});
65+
```
66+
67+
### Actions
68+
69+
#### CREATE_AND_REGISTER_AGENT
70+
Creates and registers an agent using specified settings.
71+
72+
```typescript
73+
const result = await runtime.executeAction("CREATE_AND_REGISTER_AGENT", {
74+
signers: [...],
75+
threshold: 3,
76+
agentHeader: { ... },
77+
// ...other fields...
78+
});
79+
```
80+
81+
#### VERIFY
82+
Verifies data on-chain via the Agent SDK.
83+
84+
```typescript
85+
const result = await runtime.executeAction("VERIFY", {
86+
payload: {
87+
data: "0x...hexData",
88+
signatures: [...],
89+
},
90+
agent: "0x...agentAddress",
91+
digest: "0x...digestString",
92+
});
93+
```
94+
95+
#### PRICE_QUERY
96+
Fetches live price data for a specified trading pair.
97+
98+
```typescript
99+
const result = await runtime.executeAction("PRICE_QUERY", {
100+
pair: "BTC/USD",
101+
});
102+
```
103+
104+
## Performance Optimization
105+
106+
1. **Cache Management**
107+
- Implement caching for frequent queries
108+
- Monitor retrieval times and cache hits
109+
110+
2. **Network Efficiency**
111+
- Batch requests where possible
112+
- Validate response parsing to reduce overhead
113+
114+
## System Requirements
115+
- Node.js 16.x or higher
116+
- Sufficient network access to on-chain endpoints
117+
- Basic configuration of environment variables
118+
- Minimum 4GB RAM recommended
119+
120+
## Troubleshooting
121+
122+
1. **Invalid Agent Settings**
123+
- Ensure signers and threshold are correct
124+
- Validate agentHeader for proper UUIDs and numeric values
125+
126+
2. **Verification Failures**
127+
- Check the input data formats
128+
- Confirm environment variables are set
129+
130+
3. **Price Query Errors**
131+
- Verify the trading pair format
132+
- Check external API availability
133+
134+
## Safety & Security
135+
136+
1. **Credential Management**
137+
- Store private keys securely
138+
- Do not commit secrets to version control
139+
140+
2. **Transaction Limits**
141+
- Configure thresholds to mitigate abuse
142+
- Log transaction attempts and failures
143+
144+
3. **Monitoring & Logging**
145+
- Track unusual activity
146+
- Maintain detailed audit logs
147+
148+
## Support
149+
150+
For issues or feature requests:
151+
1. Check existing documentation
152+
2. Submit a GitHub issue with relevant details
153+
3. Include transaction logs and system info if applicable
154+
155+
## Contributing
156+
157+
We welcome pull requests! Refer to the project’s CONTRIBUTING.md and open discussions to coordinate efforts.
158+
159+
## Credits
160+
161+
- [APRO](https://www.apro.com/) - Plugin sponsor and partner
162+
- [ai-agent-sdk-js](https://github.com/APRO-com/ai-agent-sdk-js) - Underlying agent SDK
163+
- [ethers.js](https://docs.ethers.io/) - Transaction and contract interaction
164+
- Community contributors for feedback and testing
165+
166+
For more information about Apro plugin capabilities:
167+
168+
- [Apro Documentation](https://docs.apro.com/en)
169+
170+
## License
171+
172+
This plugin is part of the Eliza project. Refer to the main project repository for licensing details.

packages/plugin-apro/package.json

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
{
2+
"name": "@elizaos/plugin-apro",
3+
"version": "0.0.1",
4+
"type": "module",
5+
"main": "dist/index.js",
6+
"module": "dist/index.js",
7+
"types": "dist/index.d.ts",
8+
"exports": {
9+
"./package.json": "./package.json",
10+
".": {
11+
"import": {
12+
"@elizaos/source": "./src/index.ts",
13+
"types": "./dist/index.d.ts",
14+
"default": "./dist/index.js"
15+
}
16+
}
17+
},
18+
"files": [
19+
"dist"
20+
],
21+
"dependencies": {
22+
"@elizaos/core": "workspace:*",
23+
"ai-agent-sdk-js": "^0.0.2"
24+
},
25+
"scripts": {
26+
"build": "tsup --format esm --dts",
27+
"dev": "tsup --format esm --dts --watch",
28+
"test": "vitest run"
29+
},
30+
"devDependencies": {
31+
"tsup": "8.3.5",
32+
"vitest": "2.1.4"
33+
}
34+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
import { Action, composeContext, elizaLogger, generateObject, HandlerCallback, IAgentRuntime, Memory, ModelClass, State } from "@elizaos/core";
2+
import { attpsPriceQueryTemplate } from "../templates";
3+
import { AttpsPriceQuery, AttpsPriceQueryResponse, AttpsPriceQuerySchema, isAttpsPriceQuery } from "../types";
4+
5+
async function fetchPriceData(sourceAgentId: string, feedId: string) {
6+
const response = await fetch(`https://ai-agent-test.apro.com/api/ai-agent/price-detail?sourceAgentId=${sourceAgentId}&feedId=${feedId}`);
7+
const { result, code, message } = await response.json();
8+
if (code !== 0) {
9+
throw new Error(message);
10+
}
11+
return result as AttpsPriceQueryResponse;
12+
}
13+
14+
function cleanNumber(numStr: string) {
15+
return parseFloat(numStr).toString();
16+
}
17+
18+
export const attpsPriceQuery: Action = {
19+
name: "ATTPS_PRICE_QUERY",
20+
similes: [
21+
'ATTPS_PRICE_FETCH',
22+
],
23+
description: "Call remote API to fetch price data for a given source agent id and feed id.",
24+
validate: async (runtime: IAgentRuntime, message: Memory) => {
25+
return true;
26+
},
27+
handler: async (
28+
runtime: IAgentRuntime,
29+
message: Memory,
30+
state?: State,
31+
_options?: { [key: string]: unknown },
32+
callback?: HandlerCallback
33+
) => {
34+
if (!state) {
35+
state = (await runtime.composeState(message)) as State;
36+
} else {
37+
state = await runtime.updateRecentMessageState(state);
38+
}
39+
40+
// Generate price query params
41+
let attpsPriceQuery: AttpsPriceQuery;
42+
try {
43+
const response = await generateObject({
44+
runtime,
45+
context: composeContext({
46+
state,
47+
template: attpsPriceQueryTemplate,
48+
}),
49+
modelClass: ModelClass.LARGE,
50+
schema: AttpsPriceQuerySchema,
51+
});
52+
attpsPriceQuery = response.object as AttpsPriceQuery;
53+
elizaLogger.info('The price query params received:', attpsPriceQuery);
54+
} catch (error: any) {
55+
elizaLogger.error('Failed to generate price query params:', error);
56+
callback({
57+
text: 'Failed to generate price query params. Please provide valid input.',
58+
});
59+
return;
60+
}
61+
62+
// Validate price query params
63+
if (!isAttpsPriceQuery(attpsPriceQuery)) {
64+
elizaLogger.error('Invalid price query params:', attpsPriceQuery);
65+
callback({
66+
text: 'Invalid price query params. Please provide valid input.',
67+
});
68+
return;
69+
}
70+
71+
// Fetch price data
72+
try {
73+
const { sourceAgentId, feedId } = attpsPriceQuery;
74+
const priceData = await fetchPriceData(sourceAgentId, feedId);
75+
elizaLogger.info('The Price data received:', priceData);
76+
77+
const message = `Ask price: ${cleanNumber(priceData.askPrice)}\nBid price: ${cleanNumber(priceData.bidPrice)}\nMid price: ${cleanNumber(priceData.midPrice)}\nTimestamp: ${priceData.validTimeStamp}`;
78+
callback({
79+
text: `Here is the price data:\n${message}`,
80+
});
81+
} catch (error: any) {
82+
elizaLogger.error(`Error fetching price data, error: `, error);
83+
callback({
84+
text: 'Error fetching price data, error: ' + error.message,
85+
})
86+
}
87+
},
88+
examples: [
89+
[
90+
{
91+
user: "{{user1}}",
92+
content: {
93+
text: "Can you fetch price data for source agent id ... and feed id ...?",
94+
},
95+
},
96+
{
97+
user: "{{user2}}",
98+
content: {
99+
text: "I'll fetch price data for you. Give me a moment.",
100+
action: 'ATTPS_PRICE_QUERY',
101+
},
102+
}
103+
],
104+
],
105+
}

0 commit comments

Comments
 (0)