forked from ephemeraHQ/xmtp-agent-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcdp.ts
357 lines (314 loc) · 11 KB
/
cdp.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import {
Coinbase,
TimeoutError,
Wallet,
type Transfer,
type WalletData,
} from "@coinbase/coinbase-sdk";
import { isAddress } from "viem";
import { validateEnvironment } from ".";
import { getWalletData, saveWalletData } from "./storage";
const { coinbaseApiKeyName, coinbaseApiKeyPrivateKey, networkId } =
validateEnvironment();
class WalletStorage {
async get(inboxId: string): Promise<string | undefined> {
try {
const data = await getWalletData(inboxId, networkId);
return data ?? undefined;
} catch (error: unknown) {
const errorMessage =
error instanceof Error ? error.message : String(error);
console.error(`Error getting wallet data for ${inboxId}:`, errorMessage);
return undefined;
}
}
async set(inboxId: string, value: string): Promise<void> {
try {
await saveWalletData(inboxId, value, networkId);
} catch (error: unknown) {
const errorMessage =
error instanceof Error ? error.message : String(error);
console.error(`Error saving wallet data for ${inboxId}:`, errorMessage);
}
}
async del(inboxId: string): Promise<void> {
try {
await saveWalletData(inboxId, "", networkId);
} catch (error: unknown) {
const errorMessage =
error instanceof Error ? error.message : String(error);
console.error(`Error deleting wallet data for ${inboxId}:`, errorMessage);
}
}
}
// Initialize Coinbase SDK
function initializeCoinbaseSDK(): boolean {
try {
Coinbase.configure({
apiKeyName: coinbaseApiKeyName,
privateKey: coinbaseApiKeyPrivateKey,
});
console.log("Coinbase SDK initialized successfully, network:", networkId);
return true;
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error("Failed to initialize Coinbase SDK:", errorMessage);
return false;
}
}
// Agent wallet data
export type AgentWalletData = {
id: string;
wallet: Wallet;
data: WalletData;
agent_address: string;
blockchain?: string;
state?: string;
inboxId: string;
};
// Wallet service class based on cointoss implementation
export class WalletService {
private walletStorage: WalletStorage;
private inboxId: string;
private sdkInitialized: boolean;
constructor(inboxId: string) {
this.sdkInitialized = initializeCoinbaseSDK();
this.walletStorage = new WalletStorage();
this.inboxId = inboxId;
console.log("WalletService initialized with sender inboxId", this.inboxId);
}
async createWallet(): Promise<AgentWalletData> {
try {
console.log(`Creating new wallet for key ${this.inboxId}...`);
// Initialize SDK if not already done
if (!this.sdkInitialized) {
this.sdkInitialized = initializeCoinbaseSDK();
}
// Log the network we're using
console.log(`Creating wallet on network: ${networkId}`);
// Create wallet
const wallet = await Wallet.create({
networkId: networkId,
}).catch((err: unknown) => {
const errorDetails =
typeof err === "object" ? JSON.stringify(err, null, 2) : err;
console.error("Detailed wallet creation error:", errorDetails);
throw err;
});
console.log("Wallet created successfully, exporting data...");
const data = wallet.export();
console.log("Getting default address...");
const address = await wallet.getDefaultAddress();
const walletAddress = address.getId();
const walletInfo: AgentWalletData = {
id: walletAddress,
wallet: wallet,
data: data,
agent_address: walletAddress,
inboxId: this.inboxId,
};
console.log("Saving wallet data to storage...");
const walletInfoToStore = {
data: data,
agent_address: walletAddress,
inboxId: this.inboxId,
};
await this.walletStorage.set(
this.inboxId,
JSON.stringify(walletInfoToStore),
);
console.log("Wallet created and saved successfully");
return walletInfo;
} catch (error: unknown) {
console.error("Failed to create wallet:", error);
// Provide more detailed error information
if (error instanceof Error) {
throw new Error(`Wallet creation failed: ${error.message}`);
}
throw new Error(`Failed to create wallet: ${String(error)}`);
}
}
async getWallet(
inboxId: string,
createIfNotFound: boolean = true,
): Promise<AgentWalletData | undefined> {
console.log("Getting wallet for:", inboxId);
const walletData = await this.walletStorage.get(inboxId);
// If no wallet exists, create one
if (!walletData) {
console.log("No wallet found for", inboxId);
if (createIfNotFound) {
console.log("Creating new wallet as none was found");
try {
const wallet = await this.createWallet();
console.log("Successfully created new wallet, returning wallet data");
return wallet;
} catch (error: unknown) {
const errorMessage =
error instanceof Error ? error.message : String(error);
console.error("Failed to create wallet in getWallet:", errorMessage);
throw error;
}
}
return undefined;
}
try {
console.log("Found existing wallet data, decrypting...");
const walletInfo = JSON.parse(walletData) as AgentWalletData;
console.log("Importing wallet from stored data...");
const importedWallet = await Wallet.import(walletInfo.data).catch(
(err: unknown) => {
const errorMessage = err instanceof Error ? err.message : String(err);
console.error("Error importing wallet:", errorMessage);
throw new Error(`Failed to import wallet: ${errorMessage}`);
},
);
console.log("Wallet imported successfully");
return {
id: importedWallet.getId() ?? "",
wallet: importedWallet,
data: walletInfo.data,
agent_address: walletInfo.agent_address,
inboxId: walletInfo.inboxId,
};
} catch (error: unknown) {
const errorMessage =
error instanceof Error ? error.message : String(error);
console.error("Failed to decrypt or import wallet data:", errorMessage);
// If we failed to import, but have wallet data, attempt to recreate
if (createIfNotFound) {
console.log("Attempting to recreate wallet after import failure");
return this.createWallet();
}
throw new Error("Invalid wallet access");
}
}
async checkBalance(
inboxId: string,
): Promise<{ address: string | undefined; balance: number }> {
console.log(`⚖️ Checking balance for user with inboxId: ${inboxId}...`);
const walletData = await this.getWallet(inboxId);
if (!walletData) {
console.log(`❌ No wallet found for user with inboxId: ${inboxId}`);
return { address: undefined, balance: 0 };
}
console.log(
`✅ Retrieved wallet with address: ${walletData.agent_address} for user with inboxId: ${inboxId}`,
);
try {
console.log(
`💰 Fetching USDC balance for address: ${walletData.agent_address}...`,
);
const balance = await walletData.wallet.getBalance(Coinbase.assets.Usdc);
console.log(
`💵 USDC Balance for user with inboxId: ${inboxId}: ${Number(balance)} USDC`,
);
console.log(Coinbase.assets.Usdc);
return {
address: walletData.agent_address,
balance: Number(balance),
};
} catch (error: unknown) {
const errorMessage =
error instanceof Error ? error.message : String(error);
console.error(
`❌ Error getting balance for user with inboxId: ${inboxId}:`,
errorMessage,
);
return {
address: walletData.agent_address,
balance: 0,
};
}
}
async transfer(
inboxId: string,
toAddress: string,
amount: number,
): Promise<Transfer | undefined> {
toAddress = toAddress.toLowerCase();
console.log("📤 TRANSFER INITIATED");
console.log(`💸 Amount: ${amount} USDC`);
console.log(`🔍 From user: ${inboxId}`);
console.log(`🔍 To: ${toAddress}`);
// Get the source wallet
console.log(`🔑 Retrieving source wallet for user: ${inboxId}...`);
const from = await this.getWallet(inboxId);
if (!from) {
console.error(`❌ No wallet found for sender: ${inboxId}`);
return undefined;
}
console.log(`✅ Source wallet found: ${from.agent_address}`);
if (!Number(amount)) {
console.error(`❌ Invalid amount: ${amount}`);
return undefined;
}
// Check balance
console.log(
`💰 Checking balance for source wallet: ${from.agent_address}...`,
);
const balance = await from.wallet.getBalance(Coinbase.assets.Usdc);
console.log(`💵 Available balance: ${Number(balance)} USDC`);
if (Number(balance) < amount) {
console.error(
`❌ Insufficient balance. Required: ${amount} USDC, Available: ${Number(balance)} USDC`,
);
return undefined;
}
if (!isAddress(toAddress) && !toAddress.includes(":")) {
// If this is not an address, and not a user ID, we can't transfer
console.error(`❌ Invalid destination address: ${toAddress}`);
return undefined;
}
// Get or validate destination wallet
let destinationAddress = toAddress;
console.log(`🔑 Validating destination: ${toAddress}...`);
const to = await this.getWallet(toAddress, false);
if (to) {
destinationAddress = to.agent_address;
console.log(`✅ Destination wallet found: ${destinationAddress}`);
} else {
console.log(`ℹ️ Using raw address as destination: ${destinationAddress}`);
}
if (destinationAddress.includes(":")) {
console.error(
`❌ Invalid destination address format: ${destinationAddress}`,
);
return undefined;
}
try {
console.log(
`🚀 Executing transfer of ${amount} USDC from ${from.agent_address} to ${destinationAddress}...`,
);
const transfer = await from.wallet.createTransfer({
amount,
assetId: Coinbase.assets.Usdc,
destination: destinationAddress,
gasless: true,
});
console.log(`⏳ Waiting for transfer to complete...`);
try {
await transfer.wait();
console.log(`✅ Transfer completed successfully!`);
} catch (err) {
if (err instanceof TimeoutError) {
console.log(
`⚠️ Waiting for transfer timed out, but transaction may still complete`,
);
} else {
const errorMessage = err instanceof Error ? err.message : String(err);
console.error(
`❌ Error while waiting for transfer to complete:`,
errorMessage,
);
}
}
return transfer;
} catch (error: unknown) {
const errorMessage =
error instanceof Error ? error.message : String(error);
console.error(`❌ Transfer failed:`, errorMessage);
throw error;
}
}
}