|
| 1 | +import { |
| 2 | + ActionExample, |
| 3 | + HandlerCallback, |
| 4 | + IAgentRuntime, |
| 5 | + Memory, |
| 6 | + ModelClass, |
| 7 | + State, |
| 8 | + type Action, |
| 9 | + composeContext, |
| 10 | + generateObject, |
| 11 | +} from "@ai16z/eliza"; |
| 12 | +import { connect, keyStores, utils } from "near-api-js"; |
| 13 | +import BigNumber from "bignumber.js"; |
| 14 | +import { init_env, ftGetTokenMetadata, estimateSwap, instantSwap, fetchAllPools, FT_MINIMUM_STORAGE_BALANCE_LARGE } from '@ref-finance/ref-sdk'; |
| 15 | +import { walletProvider } from "../providers/wallet"; |
| 16 | +import { KeyPairString } from "near-api-js/lib/utils"; |
| 17 | + |
| 18 | +// Initialize Ref SDK with testnet environment |
| 19 | +init_env('testnet'); |
| 20 | + |
| 21 | +async function swapToken( |
| 22 | + runtime: IAgentRuntime, |
| 23 | + inputTokenId: string, |
| 24 | + outputTokenId: string, |
| 25 | + amount: string, |
| 26 | + slippageTolerance: number = 0.1 |
| 27 | +): Promise<any> { |
| 28 | + try { |
| 29 | + // Get token metadata |
| 30 | + const tokenIn = await ftGetTokenMetadata(inputTokenId); |
| 31 | + const tokenOut = await ftGetTokenMetadata(outputTokenId); |
| 32 | + |
| 33 | + // Get all pools for estimation |
| 34 | + const { ratedPools, unRatedPools, simplePools} = await fetchAllPools(200); |
| 35 | + |
| 36 | + console.log("Pools:", simplePools); |
| 37 | + const swapTodos = await estimateSwap({ |
| 38 | + tokenIn, |
| 39 | + tokenOut, |
| 40 | + amountIn: amount, |
| 41 | + simplePools, |
| 42 | + options: { |
| 43 | + enableSmartRouting: true, |
| 44 | + } |
| 45 | + }); |
| 46 | + |
| 47 | + if (!swapTodos || swapTodos.length === 0) { |
| 48 | + throw new Error('No valid swap route found'); |
| 49 | + } |
| 50 | + |
| 51 | + // Get account ID from runtime settings |
| 52 | + const accountId = runtime.getSetting("NEAR_ADDRESS"); |
| 53 | + if (!accountId) { |
| 54 | + throw new Error("NEAR_ADDRESS not configured"); |
| 55 | + } |
| 56 | + |
| 57 | + // Execute swap |
| 58 | + const transactions = await instantSwap({ |
| 59 | + tokenIn, |
| 60 | + tokenOut, |
| 61 | + amountIn: amount, |
| 62 | + swapTodos, |
| 63 | + slippageTolerance, |
| 64 | + AccountId: accountId |
| 65 | + }); |
| 66 | + |
| 67 | + return transactions; |
| 68 | + } catch (error) { |
| 69 | + console.error("Error in swapToken:", error); |
| 70 | + throw error; |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +const swapTemplate = `Respond with a JSON markdown block containing only the extracted values. Use null for any values that cannot be determined. |
| 75 | +
|
| 76 | +Example response: |
| 77 | +\`\`\`json |
| 78 | +{ |
| 79 | + "inputTokenId": "wrap.testnet", |
| 80 | + "outputTokenId": "ref.fakes.testnet", |
| 81 | + "amount": "1.5" |
| 82 | +} |
| 83 | +\`\`\` |
| 84 | +
|
| 85 | +{{recentMessages}} |
| 86 | +
|
| 87 | +Given the recent messages and wallet information below: |
| 88 | +
|
| 89 | +{{walletInfo}} |
| 90 | +
|
| 91 | +Extract the following information about the requested token swap: |
| 92 | +- Input token ID (the token being sold) |
| 93 | +- Output token ID (the token being bought) |
| 94 | +- Amount to swap |
| 95 | +
|
| 96 | +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: |
| 97 | +\`\`\`json |
| 98 | +{ |
| 99 | + "inputTokenId": string | null, |
| 100 | + "outputTokenId": string | null, |
| 101 | + "amount": string | null |
| 102 | +} |
| 103 | +\`\`\``; |
| 104 | + |
| 105 | +export const executeSwap: Action = { |
| 106 | + name: "EXECUTE_SWAP_NEAR", |
| 107 | + similes: ["SWAP_TOKENS_NEAR", "TOKEN_SWAP_NEAR", "TRADE_TOKENS_NEAR", "EXCHANGE_TOKENS_NEAR"], |
| 108 | + validate: async (runtime: IAgentRuntime, message: Memory) => { |
| 109 | + console.log("Message:", message); |
| 110 | + return true; |
| 111 | + }, |
| 112 | + description: "Perform a token swap using Ref Finance.", |
| 113 | + handler: async ( |
| 114 | + runtime: IAgentRuntime, |
| 115 | + message: Memory, |
| 116 | + state: State, |
| 117 | + _options: { [key: string]: unknown }, |
| 118 | + callback?: HandlerCallback |
| 119 | + ): Promise<boolean> => { |
| 120 | + // Compose state |
| 121 | + if (!state) { |
| 122 | + state = (await runtime.composeState(message)) as State; |
| 123 | + } else { |
| 124 | + state = await runtime.updateRecentMessageState(state); |
| 125 | + } |
| 126 | + |
| 127 | + const walletInfo = await walletProvider.get(runtime, message, state); |
| 128 | + state.walletInfo = walletInfo; |
| 129 | + |
| 130 | + const swapContext = composeContext({ |
| 131 | + state, |
| 132 | + template: swapTemplate, |
| 133 | + }); |
| 134 | + |
| 135 | + const response = await generateObject({ |
| 136 | + runtime, |
| 137 | + context: swapContext, |
| 138 | + modelClass: ModelClass.LARGE, |
| 139 | + }); |
| 140 | + |
| 141 | + console.log("Response:", response); |
| 142 | + |
| 143 | + if (!response.inputTokenId || !response.outputTokenId || !response.amount) { |
| 144 | + console.log("Missing required parameters, skipping swap"); |
| 145 | + const responseMsg = { |
| 146 | + text: "I need the input token ID, output token ID, and amount to perform the swap", |
| 147 | + }; |
| 148 | + callback?.(responseMsg); |
| 149 | + return true; |
| 150 | + } |
| 151 | + |
| 152 | + try { |
| 153 | + // Get account credentials |
| 154 | + const accountId = runtime.getSetting("NEAR_ADDRESS"); |
| 155 | + const secretKey = runtime.getSetting("NEAR_WALLET_SECRET_KEY"); |
| 156 | + |
| 157 | + if (!accountId || !secretKey) { |
| 158 | + throw new Error("NEAR wallet credentials not configured"); |
| 159 | + } |
| 160 | + |
| 161 | + // Create keystore and connect to NEAR |
| 162 | + const keyStore = new keyStores.InMemoryKeyStore(); |
| 163 | + const keyPair = utils.KeyPair.fromString(secretKey as KeyPairString); |
| 164 | + await keyStore.setKey("testnet", accountId, keyPair); |
| 165 | + |
| 166 | + const nearConnection = await connect({ |
| 167 | + networkId: "testnet", |
| 168 | + keyStore, |
| 169 | + nodeUrl: "https://rpc.testnet.near.org", |
| 170 | + }); |
| 171 | + |
| 172 | + // Execute swap |
| 173 | + const swapResult = await swapToken( |
| 174 | + runtime, |
| 175 | + response.inputTokenId, |
| 176 | + response.outputTokenId, |
| 177 | + response.amount, |
| 178 | + 0.1 // 1% slippage tolerance |
| 179 | + ); |
| 180 | + |
| 181 | + // Sign and send transactions |
| 182 | + const account = await nearConnection.account(accountId); |
| 183 | + const results = []; |
| 184 | + |
| 185 | + for (const tx of swapResult) { |
| 186 | + for (const functionCall of tx.functionCalls) { |
| 187 | + const result = await account.functionCall({ |
| 188 | + contractId: tx.receiverId, |
| 189 | + methodName: functionCall.methodName, |
| 190 | + args: functionCall.args, |
| 191 | + gas: functionCall.gas, |
| 192 | + attachedDeposit: BigInt(1), |
| 193 | + }); |
| 194 | + results.push(result); |
| 195 | + } |
| 196 | + } |
| 197 | + |
| 198 | + console.log("Swap completed successfully!"); |
| 199 | + const txHashes = results.map(r => r.transaction.hash).join(", "); |
| 200 | + |
| 201 | + const responseMsg = { |
| 202 | + text: `Swap completed successfully! Transaction hashes: ${txHashes}`, |
| 203 | + }; |
| 204 | + |
| 205 | + callback?.(responseMsg); |
| 206 | + return true; |
| 207 | + } catch (error) { |
| 208 | + console.error("Error during token swap:", error); |
| 209 | + const responseMsg = { |
| 210 | + text: `Error during swap: ${error instanceof Error ? error.message : String(error)}`, |
| 211 | + }; |
| 212 | + callback?.(responseMsg); |
| 213 | + return false; |
| 214 | + } |
| 215 | + }, |
| 216 | + examples: [ |
| 217 | + [ |
| 218 | + { |
| 219 | + user: "{{user1}}", |
| 220 | + content: { |
| 221 | + inputTokenId: "wrap.testnet", |
| 222 | + outputTokenId: "ref.fakes.testnet", |
| 223 | + amount: "1.0", |
| 224 | + }, |
| 225 | + }, |
| 226 | + { |
| 227 | + user: "{{user2}}", |
| 228 | + content: { |
| 229 | + text: "Swapping 1.0 NEAR for REF...", |
| 230 | + action: "TOKEN_SWAP", |
| 231 | + }, |
| 232 | + }, |
| 233 | + { |
| 234 | + user: "{{user2}}", |
| 235 | + content: { |
| 236 | + text: "Swap completed successfully! Transaction hash: ...", |
| 237 | + }, |
| 238 | + }, |
| 239 | + ], |
| 240 | + ] as ActionExample[][], |
| 241 | +} as Action; |
0 commit comments