forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswap.ts
337 lines (301 loc) · 10.5 KB
/
swap.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
import {
ActionExample,
HandlerCallback,
elizaLogger,
IAgentRuntime,
Memory,
ModelClass,
State,
type Action,
composeContext,
generateObject,
} from "@elizaos/core";
import { connect, keyStores, utils } from "near-api-js";
import {
init_env,
ftGetTokenMetadata,
estimateSwap,
instantSwap,
fetchAllPools,
FT_MINIMUM_STORAGE_BALANCE_LARGE,
ONE_YOCTO_NEAR,
} from "@ref-finance/ref-sdk";
import { walletProvider } from "../providers/wallet";
import { KeyPairString } from "near-api-js/lib/utils";
async function checkStorageBalance(
account: any,
contractId: string
): Promise<boolean> {
try {
const balance = await account.viewFunction({
contractId,
methodName: "storage_balance_of",
args: { account_id: account.accountId },
});
return balance !== null && balance.total !== "0";
} catch (error) {
elizaLogger.log(`Error checking storage balance: ${error}`);
return false;
}
}
async function swapToken(
runtime: IAgentRuntime,
inputTokenId: string,
outputTokenId: string,
amount: string,
slippageTolerance: number = Number(
runtime.getSetting("SLIPPAGE_TOLERANCE")
) || 0.01
): Promise<any> {
try {
// Get token metadata
const tokenIn = await ftGetTokenMetadata(inputTokenId);
const tokenOut = await ftGetTokenMetadata(outputTokenId);
const networkId = runtime.getSetting("NEAR_NETWORK") || "testnet";
const nodeUrl =
runtime.getSetting("RPC_URL") || "https://rpc.testnet.near.org";
// Get all pools for estimation
// ratedPools, unRatedPools,
const { simplePools } = await fetchAllPools();
const swapTodos = await estimateSwap({
tokenIn,
tokenOut,
amountIn: amount,
simplePools,
options: {
enableSmartRouting: true,
},
});
if (!swapTodos || swapTodos.length === 0) {
throw new Error("No valid swap route found");
}
// Get account ID from runtime settings
const accountId = runtime.getSetting("NEAR_ADDRESS");
if (!accountId) {
throw new Error("NEAR_ADDRESS not configured");
}
const secretKey = runtime.getSetting("NEAR_WALLET_SECRET_KEY");
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);
// Check storage balance for both tokens
const hasStorageIn = await checkStorageBalance(account, inputTokenId);
const hasStorageOut = await checkStorageBalance(account, outputTokenId);
const transactions = await instantSwap({
tokenIn,
tokenOut,
amountIn: amount,
swapTodos,
slippageTolerance,
AccountId: accountId,
});
// If storage deposit is needed, add it to transactions
if (!hasStorageIn) {
transactions.unshift({
receiverId: inputTokenId,
functionCalls: [
{
methodName: "storage_deposit",
args: {
account_id: accountId,
registration_only: true,
},
gas: "30000000000000",
amount: FT_MINIMUM_STORAGE_BALANCE_LARGE,
},
],
});
}
if (!hasStorageOut) {
transactions.unshift({
receiverId: outputTokenId,
functionCalls: [
{
methodName: "storage_deposit",
args: {
account_id: accountId,
registration_only: true,
},
gas: "30000000000000",
amount: FT_MINIMUM_STORAGE_BALANCE_LARGE,
},
],
});
}
return transactions;
} catch (error) {
elizaLogger.error("Error in swapToken:", error);
throw error;
}
}
const swapTemplate = `Respond with a JSON markdown block containing only the extracted values. Use null for any values that cannot be determined.
Example response:
\`\`\`json
{
"inputTokenId": "wrap.testnet",
"outputTokenId": "ref.fakes.testnet",
"amount": "1.5"
}
\`\`\`
{{recentMessages}}
Given the recent messages and wallet information below:
{{walletInfo}}
Extract the following information about the requested token swap:
- Input token ID (the token being sold)
- Output token ID (the token being bought)
- Amount to swap
Respond with a JSON markdown block containing only the extracted values. Use null for any values that cannot be determined. The result should be a valid JSON object with the following schema:
\`\`\`json
{
"inputTokenId": string | null,
"outputTokenId": string | null,
"amount": string | null
}
\`\`\``;
export const executeSwap: Action = {
name: "EXECUTE_SWAP_NEAR",
similes: [
"SWAP_TOKENS_NEAR",
"TOKEN_SWAP_NEAR",
"TRADE_TOKENS_NEAR",
"EXCHANGE_TOKENS_NEAR",
],
validate: async (_runtime: IAgentRuntime, message: Memory) => {
elizaLogger.log("Message:", message);
return true;
},
description: "Perform a token swap using Ref Finance.",
handler: async (
runtime: IAgentRuntime,
message: Memory,
state: State,
_options: { [key: string]: unknown },
callback?: HandlerCallback
): Promise<boolean> => {
// Initialize Ref SDK with testnet environment
init_env(runtime.getSetting("NEAR_NETWORK") || "testnet");
// Compose state
if (!state) {
state = (await runtime.composeState(message)) as State;
} else {
state = await runtime.updateRecentMessageState(state);
}
const walletInfo = await walletProvider.get(runtime, message, state);
state.walletInfo = walletInfo;
const swapContext = composeContext({
state,
template: swapTemplate,
});
const response = await generateObject({
runtime,
context: swapContext,
modelClass: ModelClass.LARGE,
});
elizaLogger.log("Response:", response);
if (
!response.inputTokenId ||
!response.outputTokenId ||
!response.amount
) {
elizaLogger.log("Missing required parameters, skipping swap");
const responseMsg = {
text: "I need the input token ID, output token ID, and amount to perform the swap",
};
callback?.(responseMsg);
return true;
}
try {
// Get account credentials
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");
}
// Create keystore and connect to NEAR
const keyStore = new keyStores.InMemoryKeyStore();
const keyPair = utils.KeyPair.fromString(
secretKey as KeyPairString
);
await keyStore.setKey("testnet", accountId, keyPair);
const nearConnection = await connect({
networkId: runtime.getSetting("NEAR_NETWORK") || "testnet",
keyStore,
nodeUrl:
runtime.getSetting("RPC_URL") ||
"https://rpc.testnet.near.org",
});
// Execute swap
const swapResult = await swapToken(
runtime,
response.inputTokenId,
response.outputTokenId,
response.amount,
Number(runtime.getSetting("SLIPPAGE_TOLERANCE")) || 0.01
);
// Sign and send transactions
const account = await nearConnection.account(accountId);
const results = [];
for (const tx of swapResult) {
for (const functionCall of tx.functionCalls) {
const result = await account.functionCall({
contractId: tx.receiverId,
methodName: functionCall.methodName,
args: functionCall.args,
gas: functionCall.gas,
attachedDeposit: BigInt(
functionCall.amount === ONE_YOCTO_NEAR
? "1"
: functionCall.amount
),
});
results.push(result);
}
}
elizaLogger.log("Swap completed successfully!");
const txHashes = results.map((r) => r.transaction.hash).join(", ");
const responseMsg = {
text: `Swap completed successfully! Transaction hashes: ${txHashes}`,
};
callback?.(responseMsg);
return true;
} catch (error) {
elizaLogger.error("Error during token swap:", error);
const responseMsg = {
text: `Error during swap: ${error instanceof Error ? error.message : String(error)}`,
};
callback?.(responseMsg);
return false;
}
},
examples: [
[
{
user: "{{user1}}",
content: {
inputTokenId: "wrap.testnet",
outputTokenId: "ref.fakes.testnet",
amount: "1.0",
},
},
{
user: "{{user2}}",
content: {
text: "Swapping 1.0 NEAR for REF...",
action: "TOKEN_SWAP",
},
},
{
user: "{{user2}}",
content: {
text: "Swap completed successfully! Transaction hash: ...",
},
},
],
] as ActionExample[][],
} as Action;