|
| 1 | +import { elizaLogger } from "@ai16z/eliza"; |
| 2 | +import { |
| 3 | + ActionExample, |
| 4 | + Content, |
| 5 | + HandlerCallback, |
| 6 | + IAgentRuntime, |
| 7 | + Memory, |
| 8 | + ModelClass, |
| 9 | + State, |
| 10 | + type Action, |
| 11 | +} from "@ai16z/eliza"; |
| 12 | +import { composeContext } from "@ai16z/eliza"; |
| 13 | +import { generateObjectV2 } from "@ai16z/eliza"; |
| 14 | +import { z } from "zod"; |
| 15 | + |
| 16 | +import { SuiClient, getFullnodeUrl } from "@mysten/sui/client"; |
| 17 | +import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519"; |
| 18 | +import { SUI_DECIMALS } from "@mysten/sui/utils"; |
| 19 | +import { Transaction } from "@mysten/sui/transactions"; |
| 20 | + |
| 21 | +import { walletProvider } from "../providers/wallet"; |
| 22 | + |
| 23 | +type SuiNetwork = "mainnet" | "testnet" | "devnet" | "localnet"; |
| 24 | + |
| 25 | +export interface TransferContent extends Content { |
| 26 | + recipient: string; |
| 27 | + amount: string | number; |
| 28 | +} |
| 29 | + |
| 30 | +function isTransferContent(content: Content): content is TransferContent { |
| 31 | + console.log("Content for transfer", content); |
| 32 | + return ( |
| 33 | + typeof content.recipient === "string" && |
| 34 | + (typeof content.amount === "string" || |
| 35 | + typeof content.amount === "number") |
| 36 | + ); |
| 37 | +} |
| 38 | + |
| 39 | +const transferTemplate = `Respond with a JSON markdown block containing only the extracted values. Use null for any values that cannot be determined. |
| 40 | +
|
| 41 | +Example response: |
| 42 | +\`\`\`json |
| 43 | +{ |
| 44 | + "recipient": "0xaa000b3651bd1e57554ebd7308ca70df7c8c0e8e09d67123cc15c8a8a79342b3", |
| 45 | + "amount": "1" |
| 46 | +} |
| 47 | +\`\`\` |
| 48 | +
|
| 49 | +{{recentMessages}} |
| 50 | +
|
| 51 | +Given the recent messages, extract the following information about the requested token transfer: |
| 52 | +- Recipient wallet address |
| 53 | +- Amount to transfer |
| 54 | +
|
| 55 | +Respond with a JSON markdown block containing only the extracted values.`; |
| 56 | + |
| 57 | +export default { |
| 58 | + name: "SEND_TOKEN", |
| 59 | + similes: [ |
| 60 | + "TRANSFER_TOKEN", |
| 61 | + "TRANSFER_TOKENS", |
| 62 | + "SEND_TOKENS", |
| 63 | + "SEND_SUI", |
| 64 | + "PAY", |
| 65 | + ], |
| 66 | + validate: async (runtime: IAgentRuntime, message: Memory) => { |
| 67 | + console.log("Validating sui transfer from user:", message.userId); |
| 68 | + //add custom validate logic here |
| 69 | + /* |
| 70 | + const adminIds = runtime.getSetting("ADMIN_USER_IDS")?.split(",") || []; |
| 71 | + //console.log("Admin IDs from settings:", adminIds); |
| 72 | +
|
| 73 | + const isAdmin = adminIds.includes(message.userId); |
| 74 | +
|
| 75 | + if (isAdmin) { |
| 76 | + //console.log(`Authorized transfer from user: ${message.userId}`); |
| 77 | + return true; |
| 78 | + } |
| 79 | + else |
| 80 | + { |
| 81 | + //console.log(`Unauthorized transfer attempt from user: ${message.userId}`); |
| 82 | + return false; |
| 83 | + } |
| 84 | + */ |
| 85 | + return true; |
| 86 | + }, |
| 87 | + description: "Transfer tokens from the agent's wallet to another address", |
| 88 | + handler: async ( |
| 89 | + runtime: IAgentRuntime, |
| 90 | + message: Memory, |
| 91 | + state: State, |
| 92 | + _options: { [key: string]: unknown }, |
| 93 | + callback?: HandlerCallback |
| 94 | + ): Promise<boolean> => { |
| 95 | + elizaLogger.log("Starting SEND_TOKEN handler..."); |
| 96 | + |
| 97 | + const walletInfo = await walletProvider.get(runtime, message, state); |
| 98 | + state.walletInfo = walletInfo; |
| 99 | + |
| 100 | + // Initialize or update state |
| 101 | + if (!state) { |
| 102 | + state = (await runtime.composeState(message)) as State; |
| 103 | + } else { |
| 104 | + state = await runtime.updateRecentMessageState(state); |
| 105 | + } |
| 106 | + |
| 107 | + // Define the schema for the expected output |
| 108 | + const transferSchema = z.object({ |
| 109 | + recipient: z.string(), |
| 110 | + amount: z.union([z.string(), z.number()]), |
| 111 | + }); |
| 112 | + |
| 113 | + // Compose transfer context |
| 114 | + const transferContext = composeContext({ |
| 115 | + state, |
| 116 | + template: transferTemplate, |
| 117 | + }); |
| 118 | + |
| 119 | + // Generate transfer content with the schema |
| 120 | + const content = await generateObjectV2({ |
| 121 | + runtime, |
| 122 | + context: transferContext, |
| 123 | + schema: transferSchema, |
| 124 | + modelClass: ModelClass.SMALL, |
| 125 | + }); |
| 126 | + |
| 127 | + const transferContent = content.object as TransferContent; |
| 128 | + |
| 129 | + // Validate transfer content |
| 130 | + if (!isTransferContent(transferContent)) { |
| 131 | + console.error("Invalid content for TRANSFER_TOKEN action."); |
| 132 | + if (callback) { |
| 133 | + callback({ |
| 134 | + text: "Unable to process transfer request. Invalid content provided.", |
| 135 | + content: { error: "Invalid transfer content" }, |
| 136 | + }); |
| 137 | + } |
| 138 | + return false; |
| 139 | + } |
| 140 | + |
| 141 | + try { |
| 142 | + const privateKey = runtime.getSetting("SUI_PRIVATE_KEY"); |
| 143 | + const suiAccount = Ed25519Keypair.deriveKeypair(privateKey); |
| 144 | + const network = runtime.getSetting("SUI_NETWORK"); |
| 145 | + const suiClient = new SuiClient({ |
| 146 | + url: getFullnodeUrl(network as SuiNetwork), |
| 147 | + }); |
| 148 | + |
| 149 | + const adjustedAmount = BigInt( |
| 150 | + Number(transferContent.amount) * Math.pow(10, SUI_DECIMALS) |
| 151 | + ); |
| 152 | + console.log( |
| 153 | + `Transferring: ${transferContent.amount} tokens (${adjustedAmount} base units)` |
| 154 | + ); |
| 155 | + const tx = new Transaction(); |
| 156 | + const [coin] = tx.splitCoins(tx.gas, [adjustedAmount]); |
| 157 | + tx.transferObjects([coin], transferContent.recipient); |
| 158 | + const executedTransaction = |
| 159 | + await suiClient.signAndExecuteTransaction({ |
| 160 | + signer: suiAccount, |
| 161 | + transaction: tx, |
| 162 | + }); |
| 163 | + |
| 164 | + console.log("Transfer successful:", executedTransaction.digest); |
| 165 | + |
| 166 | + if (callback) { |
| 167 | + callback({ |
| 168 | + text: `Successfully transferred ${transferContent.amount} SUI to ${transferContent.recipient}, Transaction: ${executedTransaction.digest}`, |
| 169 | + content: { |
| 170 | + success: true, |
| 171 | + hash: executedTransaction.digest, |
| 172 | + amount: transferContent.amount, |
| 173 | + recipient: transferContent.recipient, |
| 174 | + }, |
| 175 | + }); |
| 176 | + } |
| 177 | + |
| 178 | + return true; |
| 179 | + } catch (error) { |
| 180 | + console.error("Error during token transfer:", error); |
| 181 | + if (callback) { |
| 182 | + callback({ |
| 183 | + text: `Error transferring tokens: ${error.message}`, |
| 184 | + content: { error: error.message }, |
| 185 | + }); |
| 186 | + } |
| 187 | + return false; |
| 188 | + } |
| 189 | + }, |
| 190 | + |
| 191 | + examples: [ |
| 192 | + [ |
| 193 | + { |
| 194 | + user: "{{user1}}", |
| 195 | + content: { |
| 196 | + text: "Send 1 SUI tokens to 0x4f2e63be8e7fe287836e29cde6f3d5cbc96eefd0c0e3f3747668faa2ae7324b0", |
| 197 | + }, |
| 198 | + }, |
| 199 | + { |
| 200 | + user: "{{user2}}", |
| 201 | + content: { |
| 202 | + text: "I'll send 1 SUI tokens now...", |
| 203 | + action: "SEND_TOKEN", |
| 204 | + }, |
| 205 | + }, |
| 206 | + { |
| 207 | + user: "{{user2}}", |
| 208 | + content: { |
| 209 | + text: "Successfully sent 1 SUI tokens to 0x4f2e63be8e7fe287836e29cde6f3d5cbc96eefd0c0e3f3747668faa2ae7324b0, Transaction: 0x39a8c432d9bdad993a33cc1faf2e9b58fb7dd940c0425f1d6db3997e4b4b05c0", |
| 210 | + }, |
| 211 | + }, |
| 212 | + ], |
| 213 | + ] as ActionExample[][], |
| 214 | +} as Action; |
0 commit comments