forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransfer.ts
201 lines (176 loc) · 5.84 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
import {
ActionExample,
Content,
HandlerCallback,
IAgentRuntime,
Memory,
ModelClass,
State,
elizaLogger,
type Action,
composeContext,
generateObject,
} from "@elizaos/core";
import { connect, keyStores, utils } from "near-api-js";
import { KeyPairString } from "near-api-js/lib/utils";
import { utils as nearUtils } from "near-api-js";
// import BigNumber from "bignumber.js";
export interface TransferContent extends Content {
recipient: string;
amount: string | number;
tokenAddress?: string; // Optional for native NEAR transfers
}
function isTransferContent(
runtime: IAgentRuntime,
content: any
): content is TransferContent {
return (
typeof content.recipient === "string" &&
(typeof content.amount === "string" ||
typeof content.amount === "number")
);
}
const transferTemplate = `Respond with a JSON markdown block containing only the extracted values. Use null for any values that cannot be determined.
Example response:
\`\`\`json
{
"recipient": "bob.near",
"amount": "1.5",
"tokenAddress": null
}
\`\`\`
{{recentMessages}}
Given the recent messages and wallet information below:
{{walletInfo}}
Extract the following information about the requested token transfer:
- Recipient address (NEAR account)
- Amount to transfer
- Token contract address (null for native NEAR transfers)
Respond with a JSON markdown block containing only the extracted values.`;
async function transferNEAR(
runtime: IAgentRuntime,
recipient: string,
amount: string
): Promise<string> {
const networkId = runtime.getSetting("NEAR_NETWORK") || "testnet";
const nodeUrl =
runtime.getSetting("RPC_URL") || "https://rpc.testnet.near.org";
const accountId = runtime.getSetting("NEAR_ADDRESS");
const secretKey = runtime.getSetting("NEAR_WALLET_SECRET_KEY");
if (!accountId || !secretKey) {
throw new Error("NEAR wallet credentials not configured");
}
// Convert amount to yoctoNEAR (1 NEAR = 10^24 yoctoNEAR)
// const yoctoAmount = new BigNumber(amount).multipliedBy(new BigNumber(10).pow(24)).toFixed(0);
// Create keystore and connect to NEAR
const keyStore = new keyStores.InMemoryKeyStore();
const keyPair = utils.KeyPair.fromString(secretKey as KeyPairString);
await keyStore.setKey(networkId, accountId, keyPair);
const nearConnection = await connect({
networkId,
keyStore,
nodeUrl,
});
const account = await nearConnection.account(accountId);
// Execute transfer
const result = await account.sendMoney(
recipient,
BigInt(nearUtils.format.parseNearAmount(amount)!)
);
return result.transaction.hash;
}
export const executeTransfer: Action = {
name: "SEND_NEAR",
similes: ["TRANSFER_NEAR", "SEND_TOKENS", "TRANSFER_TOKENS", "PAY_NEAR"],
validate: async (_runtime: IAgentRuntime, _message: Memory) => {
return true; // Add your validation logic here
},
description: "Transfer NEAR tokens to another account",
handler: async (
runtime: IAgentRuntime,
message: Memory,
state: State,
_options: { [key: string]: unknown },
callback?: HandlerCallback
): Promise<boolean> => {
// 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 content = await generateObject({
runtime,
context: transferContext,
modelClass: ModelClass.SMALL,
});
// Validate transfer content
if (!isTransferContent(runtime, content)) {
elizaLogger.error("Invalid content for TRANSFER_NEAR action.");
if (callback) {
callback({
text: "Unable to process transfer request. Invalid content provided.",
content: { error: "Invalid transfer content" },
});
}
return false;
}
try {
const txHash = await transferNEAR(
runtime,
content.recipient,
content.amount.toString()
);
if (callback) {
callback({
text: `Successfully transferred ${content.amount} NEAR to ${content.recipient}\nTransaction: ${txHash}`,
content: {
success: true,
signature: txHash,
amount: content.amount,
recipient: content.recipient,
},
});
}
return true;
} catch (error) {
elizaLogger.error("Error during NEAR transfer:", error);
if (callback) {
callback({
text: `Error transferring NEAR: ${error}`,
content: { error: error },
});
}
return false;
}
},
examples: [
[
{
user: "{{user1}}",
content: {
text: "Send 1.5 NEAR to bob.testnet",
},
},
{
user: "{{user2}}",
content: {
text: "I'll send 1.5 NEAR now...",
action: "SEND_NEAR",
},
},
{
user: "{{user2}}",
content: {
text: "Successfully sent 1.5 NEAR to bob.testnet\nTransaction: ABC123XYZ",
},
},
],
] as ActionExample[][],
} as Action;