-
Notifications
You must be signed in to change notification settings - Fork 5k
/
Copy pathtransfer.ts
382 lines (356 loc) · 12.8 KB
/
transfer.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import {
composeContext,
Content,
elizaLogger,
generateObjectArray,
ModelClass,
type Action,
type ActionExample,
type HandlerCallback,
type IAgentRuntime,
type Memory,
type State,
} from "@elizaos/core";
import Exception from "../types/exception";
import { getFlowConnectorInstance } from "../providers/connector.provider";
import {
FlowWalletProvider,
isCadenceIdentifier,
isEVMAddress,
isFlowAddress,
} from "../providers/wallet.provider";
import { transferTemplate } from "../templates";
import { validateFlowConfig } from "../environment";
import { TransactionResponse } from "../types";
import { transactions } from "../assets/transaction.defs";
import * as queries from "../queries";
/**
* The generated content for the transfer action
*/
export interface TransferContent extends Content {
token: string | null;
amount: string;
to: string;
matched: boolean;
}
/**
* Check if the content is a transfer content
*/
function isTransferContent(
runtime: IAgentRuntime,
content: any
): content is TransferContent {
elizaLogger.log("Content for transfer", content);
return (
(!content.token ||
(typeof content.token === "string" &&
(isCadenceIdentifier(content.token) ||
isEVMAddress(content.token)))) &&
typeof content.to === "string" &&
(isEVMAddress(content.to) || isFlowAddress(content.to)) &&
(typeof content.amount === "string" ||
typeof content.amount === "number") &&
typeof content.matched === "boolean"
);
}
// FIXME: We need to use dynamic key index
const USE_KEY_INDEX = 0;
export class TransferAction {
constructor(
private walletProvider: FlowWalletProvider,
public readonly useKeyIndex: number = USE_KEY_INDEX
) {}
/**
* Process the messages and generate the transfer content
*/
async processMessages(
runtime: IAgentRuntime,
message: Memory,
state: State
): Promise<TransferContent> {
// Initialize or update state
if (!state) {
state = (await runtime.composeState(message)) as State;
} else {
state = await runtime.updateRecentMessageState(state);
}
// Compose transfer context
const transferContext = composeContext({
state,
template: transferTemplate,
});
// Generate transfer content
const recommendations = await generateObjectArray({
runtime,
context: transferContext,
modelClass: ModelClass.MEDIUM,
});
elizaLogger.debug("Recommendations", recommendations);
// Convert array to object
const content = recommendations[recommendations.length - 1];
// Validate transfer content
if (!isTransferContent(runtime, content)) {
elizaLogger.error("Invalid content for SEND_COIN action.");
throw new Exception(50100, "Invalid transfer content");
}
// Check if the content is matched
if (!content.matched) {
elizaLogger.error("Content does not match the transfer template.");
throw new Exception(
50100,
"Content does not match the transfer template"
);
}
return content;
}
async transfer(
content: TransferContent,
callback?: HandlerCallback
): Promise<TransactionResponse> {
elizaLogger.log("Starting Flow Plugin's SEND_COIN handler...");
const resp: TransactionResponse = {
signer: {
address: this.walletProvider.address,
keyIndex: this.useKeyIndex,
},
txid: "",
};
const logPrefix = `Address: ${resp.signer.address}, using keyIdex: ${resp.signer.keyIndex}\n`;
// Parsed fields
const recipient = content.to;
const amount =
typeof content.amount === "number"
? content.amount
: parseFloat(content.amount);
// Check if the wallet has enough balance to transfer
const accountInfo = await queries.queryAccountBalanceInfo(
this.walletProvider,
this.walletProvider.address
);
const totalBalance =
accountInfo.balance + (accountInfo.coaBalance ?? 0);
// Check if the amount is valid
if (totalBalance < amount) {
elizaLogger.error("Insufficient balance to transfer.");
if (callback) {
callback({
text: `${logPrefix} Unable to process transfer request. Insufficient balance.`,
content: {
error: "Insufficient balance",
},
});
}
throw new Exception(50100, "Insufficient balance to transfer");
}
try {
// Execute transfer
const authz = this.walletProvider.buildAuthorization(
this.useKeyIndex
); // use default private key
// For different token types, we need to handle the token differently
if (!content.token) {
elizaLogger.log(
`${logPrefix} Sending ${amount} FLOW to ${recipient}...`
);
// Transfer FLOW token
resp.txid = await this.walletProvider.sendTransaction(
transactions.mainFlowTokenDynamicTransfer,
(arg, t) => [
arg(recipient, t.String),
arg(amount.toFixed(1), t.UFix64),
],
authz
);
} else if (isCadenceIdentifier(content.token)) {
// Transfer Fungible Token on Cadence side
const [_, tokenAddr, tokenContractName] =
content.token.split(".");
elizaLogger.log(
`${logPrefix} Sending ${amount} A.${tokenAddr}.${tokenContractName} to ${recipient}...`
);
resp.txid = await this.walletProvider.sendTransaction(
transactions.mainFTGenericTransfer,
(arg, t) => [
arg(amount.toFixed(1), t.UFix64),
arg(recipient, t.Address),
arg("0x" + tokenAddr, t.Address),
arg(tokenContractName, t.String),
],
authz
);
} else if (isEVMAddress(content.token)) {
// Transfer ERC20 token on EVM side
// we need to update the amount to be in the smallest unit
const decimals = await queries.queryEvmERC20Decimals(
this.walletProvider,
content.token
);
const adjustedAmount = BigInt(amount * Math.pow(10, decimals));
elizaLogger.log(
`${logPrefix} Sending ${adjustedAmount} ${content.token}(EVM) to ${recipient}...`
);
resp.txid = await this.walletProvider.sendTransaction(
transactions.mainEVMTransferERC20,
(arg, t) => [
arg(content.token, t.String),
arg(recipient, t.String),
// Convert the amount to string, the string should be pure number, not a scientific notation
arg(adjustedAmount.toString(), t.UInt256),
],
authz
);
}
elizaLogger.log(`${logPrefix} Sent transaction: ${resp.txid}`);
// call the callback with the transaction response
if (callback) {
const tokenName = content.token || "FLOW";
const baseUrl =
this.walletProvider.network === "testnet"
? "https://testnet.flowscan.io"
: "https://flowscan.io";
const txURL = `${baseUrl}/tx/${resp.txid}/events`;
callback({
text: `${logPrefix} Successfully transferred ${content.amount} ${tokenName} to ${content.to}\nTransaction: [${resp.txid}](${txURL})`,
content: {
success: true,
txid: resp.txid,
token: content.token,
to: content.to,
amount: content.amount,
},
});
}
} catch (e: any) {
elizaLogger.error("Error in sending transaction:", e.message);
if (callback) {
callback({
text: `${logPrefix} Unable to process transfer request. Error in sending transaction.`,
content: {
error: e.message,
},
});
}
if (e instanceof Exception) {
throw e;
} else {
throw new Exception(
50100,
"Error in sending transaction: " + e.message
);
}
}
elizaLogger.log("Completed Flow Plugin's SEND_COIN handler.");
return resp;
}
}
export const transferAction = {
name: "SEND_COIN",
similes: [
"SEND_TOKEN",
"SEND_TOKEN_ON_FLOW",
"TRANSFER_TOKEN_ON_FLOW",
"TRANSFER_TOKENS_ON_FLOW",
"TRANSFER_FLOW",
"SEND_FLOW",
"PAY_BY_FLOW",
],
description:
"Call this action to transfer any fungible token/coin from the agent's Flow wallet to another address",
validate: async (runtime: IAgentRuntime, _message: Memory) => {
await validateFlowConfig(runtime);
const flowConnector = await getFlowConnectorInstance(runtime);
const walletProvider = new FlowWalletProvider(runtime, flowConnector);
try {
await walletProvider.syncAccountInfo();
// TODO: We need to check if the key index is valid
} catch {
elizaLogger.error("Failed to sync account info");
return false;
}
return true;
},
handler: async (
runtime: IAgentRuntime,
message: Memory,
state: State,
_options: { [key: string]: unknown },
callback?: HandlerCallback
): Promise<boolean> => {
const flowConnector = await getFlowConnectorInstance(runtime);
const walletProvider = new FlowWalletProvider(runtime, flowConnector);
const action = new TransferAction(walletProvider);
let content: TransferContent;
try {
content = await action.processMessages(runtime, message, state);
} catch (err) {
elizaLogger.error("Error in processing messages:", err.message);
if (callback) {
callback({
text:
"Unable to process transfer request. Invalid content: " +
err.message,
content: {
error: "Invalid content",
},
});
}
return false;
}
try {
const res = await action.transfer(content, callback);
elizaLogger.log(
`Transfer action response: ${res.signer.address}[${res.signer.keyIndex}] - ${res.txid}`
);
} catch {
return false;
}
return true;
},
examples: [
[
{
user: "{{user1}}",
content: {
text: "Send 1 FLOW to 0xa2de93114bae3e73",
},
},
{
user: "{{user2}}",
content: {
text: "Sending 1 FLOW tokens now, pls wait...",
action: "SEND_COIN",
},
},
],
[
{
user: "{{user1}}",
content: {
text: "Send 1 FLOW - A.1654653399040a61.FlowToken to 0xa2de93114bae3e73",
},
},
{
user: "{{user2}}",
content: {
text: "Sending 1 FLOW tokens now, pls wait...",
action: "SEND_COIN",
},
},
],
[
{
user: "{{user1}}",
content: {
text: "Send 1000 FROTH - 0xb73bf8e6a4477a952e0338e6cc00cc0ce5ad04ba to 0x000000000000000000000002e44fbfbd00395de5",
},
},
{
user: "{{user2}}",
content: {
text: "Sending 1000 FROTH tokens now, pls wait...",
action: "SEND_COIN",
},
},
],
] as ActionExample[][],
} as Action;