-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate-vault.ts
255 lines (235 loc) · 7.01 KB
/
create-vault.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import {
type Action,
type HandlerCallback,
type IAgentRuntime,
type Memory,
type RAGKnowledgeItem,
type State,
type UUID,
elizaLogger,
} from '@elizaos/core';
import { v4 as uuidv4 } from 'uuid';
import type { Address, PublicClient, WalletClient } from 'viem';
import { z } from 'zod';
import { ethereumAddressSchema } from '../../../validators/ethereum';
import { VAULT_FACTORY_ABI } from '../constants/vault-factory-abi';
import { initSonicProvider } from '../providers/sonic';
// TODO Move this to a type
interface MessageMetadata {
walletAddress?: Address;
[key: string]: unknown;
}
const createVaultContentSchema = z.object({
userId: z.string().uuid(),
walletAddress: ethereumAddressSchema,
agentAddress: ethereumAddressSchema,
vaultFactoryAddress: ethereumAddressSchema,
// FIXME Should be typed
publicClient: z.unknown(),
walletClient: z.unknown(),
});
type CreateVaultContent = z.infer<typeof createVaultContentSchema>;
interface CreateVaultResponse {
success: boolean;
vaultAddress?: string;
error?: string;
}
async function createVault(
params: CreateVaultContent & { runtime: IAgentRuntime },
): Promise<CreateVaultResponse> {
try {
const parsedParams = createVaultContentSchema.parse(params);
const {
userId,
walletAddress,
vaultFactoryAddress,
agentAddress,
publicClient,
walletClient,
} = parsedParams;
const typedPublicClient = publicClient as PublicClient;
const typedWalletClient = walletClient as WalletClient;
const { runtime } = params;
// Create vault through factory
// Approve from the vault address
const { request } = await typedPublicClient.simulateContract({
account: agentAddress,
address: vaultFactoryAddress,
abi: VAULT_FACTORY_ABI,
functionName: 'createVault',
args: [agentAddress],
});
const hash = await typedWalletClient.writeContract(request);
const receipt = await typedPublicClient.waitForTransactionReceipt({ hash });
// Log the transaction receipt for debugging
elizaLogger.info('Successfully created vault', {
contractAddress: receipt.contractAddress,
});
// TODO Add viem parsing here
// Look for the VaultCreated event in the transaction receipt
const vaultCreatedEvent = receipt.logs.find(
(log) =>
log.topics[0] ===
'0x897c133dfbfe1f6239e98b4ffd7e4f6c86a62350a131a7a37790419f58af02f9',
);
if (!vaultCreatedEvent) {
throw new Error('VaultCreated event not found in transaction receipt');
}
// The vault address is the first indexed parameter in the event
const vaultAddress = vaultCreatedEvent.topics[1] as `0x${string}`;
// Create knowledge about the vault with Sonic-specific information
const vaultKnowledge: RAGKnowledgeItem = {
id: uuidv4() as UUID,
agentId: runtime.agentId,
content: {
text: `Sonic Vault created for user ${userId}`,
metadata: {
source: 'sonic_plugin',
type: 'vault_info',
isMain: true,
isShared: true,
vaultAddress,
userId,
walletAddress,
createdAt: new Date().toISOString(),
transactionHash: hash,
},
},
embedding: new Float32Array(1536).fill(0),
createdAt: Date.now(),
};
// Store the vault knowledge
await runtime.databaseAdapter.createKnowledge(vaultKnowledge);
// Log the vault creation details
elizaLogger.info('Created Sonic vault:', {
userId,
walletAddress,
vaultAddress,
agentId: runtime.agentId,
transactionHash: hash,
});
return {
success: true,
vaultAddress,
};
} catch (error) {
elizaLogger.error('Error in vault creation:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred',
};
}
}
export const createVaultAction: Action = {
name: 'CREATE_VAULT',
description: 'Creates a new vault for a user using the VaultFactory contract',
similes: [
'CREATE_NEW_VAULT',
'INITIALIZE_VAULT',
'SETUP_VAULT',
'OPEN_VAULT',
],
examples: [
[
{
user: '{{user1}}',
content: {
text: 'Create a new vault for my wallet',
action: 'CREATE_VAULT',
},
},
{
user: '{{agentName}}',
content: {
text: 'Successfully created a new vault for your wallet',
action: 'CREATE_VAULT',
},
},
],
],
validate: async (runtime: IAgentRuntime, message: Memory) => {
const vaultFactoryAddress = runtime.getSetting('VAULT_FACTORY_ADDRESS');
if (!vaultFactoryAddress) {
return false;
}
const rpcUrl = runtime.getSetting('SONIC_RPC_URL');
if (!rpcUrl) {
return false;
}
const privateKey = runtime.getSetting('SONIC_PRIVATE_KEY') as `0x${string}`;
if (!privateKey) {
return false;
}
const metadata = message.content.metadata as MessageMetadata;
const walletAddress = metadata?.walletAddress;
if (!walletAddress) {
return false;
}
return true;
},
handler: async (
runtime: IAgentRuntime,
message: Memory,
_state?: State,
_options?: {
[key: string]: unknown;
},
callback?: HandlerCallback,
) => {
elizaLogger.log('Create Vault handler called');
const sonicProvider = await initSonicProvider(runtime);
// Extract wallet address from message metadata
const metadata = message.content.metadata as MessageMetadata;
const walletAddress = metadata?.walletAddress;
// Should not happen, it is validated
if (!walletAddress) {
elizaLogger.error('No wallet address provided in message metadata');
if (callback) {
callback({
text: 'Error: No wallet address provided',
});
}
return false;
}
// Use the userId from the message
const createVaultContent: CreateVaultContent = {
userId: message.userId,
walletAddress,
agentAddress: sonicProvider.account.address,
vaultFactoryAddress: sonicProvider.vaultFactoryAddress,
publicClient: sonicProvider.getPublicClient(),
walletClient: sonicProvider.getWalletClient(),
};
try {
const response = await createVault({
...createVaultContent,
runtime,
});
if (response.success) {
if (callback) {
callback({
text: `Successfully created a new vault at ${response.vaultAddress}`,
content: {
success: true,
vaultAddress: response.vaultAddress,
action: 'CREATE_VAULT',
},
});
}
return true;
}
throw new Error(response.error || 'Failed to create vault');
} catch (error) {
elizaLogger.error(
'Error in create vault handler:',
error instanceof Error ? error.message : String(error),
);
if (callback) {
callback({
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
});
}
return false;
}
},
};