UNPKG

story-build

Version:

MCP library for AI-assisted IP registration and licensing on Story Protocol

1,264 lines (1,252 loc) 132 kB
#!/usr/bin/env node "use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); // src/config.ts var import_core_sdk = require("@story-protocol/core-sdk"); var import_viem = require("viem"); var import_accounts = require("viem/accounts"); var import_dotenv = __toESM(require("dotenv")); import_dotenv.default.config(); var getArgs = () => process.argv.reduce((args, arg) => { if (arg.slice(0, 2) === "--") { const longArg = arg.split("="); const longArgFlag = longArg[0].slice(2); const longArgValue = longArg.length > 1 ? longArg[1] : true; args[longArgFlag] = longArgValue; } else if (arg[0] === "-") { const flags = arg.slice(1).split(""); flags.forEach((flag) => { args[flag] = true; }); } return args; }, {}); var networkConfigs = { aeneid: { rpcProviderUrl: "https://aeneid.storyrpc.io", blockExplorer: "https://aeneid.storyscan.io", protocolExplorer: "https://aeneid.explorer.story.foundation", defaultNFTContractAddress: "0x937bef10ba6fb941ed84b8d249abc76031429a9a", defaultSPGNFTContractAddress: "0xc32A8a0FF3beDDDa58393d022aF433e78739FAbc", chain: import_core_sdk.aeneid }, mainnet: { rpcProviderUrl: "https://mainnet.storyrpc.io", blockExplorer: "https://storyscan.io", protocolExplorer: "https://explorer.story.foundation", defaultNFTContractAddress: null, defaultSPGNFTContractAddress: "0x98971c660ac20880b60F86Cc3113eBd979eb3aAE", chain: import_core_sdk.mainnet } }; var getNetwork = () => { const args = getArgs(); const network2 = args?.story_network || process.env.STORY_NETWORK || "aeneid"; if (network2 && !(network2 in networkConfigs)) { throw new Error(`Invalid network: ${network2}. Must be one of: ${Object.keys(networkConfigs).join(", ")}`); } return network2 || "aeneid"; }; var getAccount = () => { const args = getArgs(); const hasPrivateKey = !!(args?.wallet_private_key || process.env.WALLET_PRIVATE_KEY); if (!hasPrivateKey) { throw new Error("WALLET_PRIVATE_KEY environment variable is required"); } return (0, import_accounts.privateKeyToAccount)(`0x${args?.wallet_private_key || process.env.WALLET_PRIVATE_KEY}`); }; var network = getNetwork(); var networkInfo = { ...networkConfigs[network], rpcProviderUrl: networkConfigs[network].rpcProviderUrl }; var account = getAccount(); var config = { account, transport: (0, import_viem.http)(networkInfo.rpcProviderUrl), chainId: network }; var client = import_core_sdk.StoryClient.newClient(config); var baseConfig = { chain: networkInfo.chain, transport: (0, import_viem.http)(networkInfo.rpcProviderUrl) }; var publicClient = (0, import_viem.createPublicClient)(baseConfig); var walletClient = (0, import_viem.createWalletClient)({ ...baseConfig, account }); function validateEnvironment() { try { getAccount(); getNetwork(); console.error(`\u2705 Story Protocol environment configuration valid (${network})`); console.error(`\u{1F4CD} RPC URL: ${networkInfo.rpcProviderUrl}`); console.error(`\u{1F4CD} Account: ${account.address}`); } catch (error) { console.error("\u274C Invalid environment configuration:", error); throw error; } } // src/index.ts var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js"); var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js"); // src/mcp/wallet/get_wallet_info_tool.ts var GetWalletInfoTool = { name: "story_get_wallet_info", description: "Get wallet address and basic account information", schema: {}, handler: async (agent, input) => { try { await agent.connect(); const balance = await agent.publicClient.getBalance({ address: agent.account.address }); const balanceInETH = Number(balance) / 1e18; return { status: "success", message: "\u2705 Wallet information retrieved successfully", wallet_details: { address: agent.account.address, network: agent.network, balance: `${balanceInETH.toFixed(6)} IP`, balance_in_wei: balance.toString(), chain_id: await agent.publicClient.getChainId(), block_explorer: agent.networkInfo.blockExplorer, protocol_explorer: agent.networkInfo.protocolExplorer }, account_status: { activated: true, minimum_balance_required: "0.01 IP", can_register_ip: balanceInETH >= 0.01, ready_for_operations: balanceInETH >= 1e-3 }, recommendations: balanceInETH < 0.01 ? [ "\u26A0\uFE0F Low IP balance detected", "Fund wallet with at least 0.01 IP for IP registration", "Gas fees required for all Story Protocol operations", `Current balance: ${balanceInETH.toFixed(6)} IP` ] : [ "\u2705 Wallet has sufficient balance for operations", "Ready to register IP assets", "Ready to create license terms and mint tokens" ] }; } catch (error) { throw new Error(`Failed to get wallet info: ${error.message}`); } finally { await agent.disconnect(); } } }; // src/mcp/wallet/get_account_balances_tool.ts var import_zod = require("zod"); var import_viem2 = require("viem"); var import_core_sdk2 = require("@story-protocol/core-sdk"); var GetAccountBalancesTool = { name: "story_get_account_balances", description: "Get all token balances including IP, WIP tokens, and license tokens", schema: { account_address: import_zod.z.string().regex(/^0x[0-9a-fA-F]{40}$/).optional().describe("Ethereum address to check (optional, defaults to wallet address)") }, handler: async (agent, input) => { try { await agent.connect(); const targetAddress = input.account_address || agent.account.address; const ethBalance = await agent.publicClient.getBalance({ address: targetAddress }); let wipBalance = BigInt(0); try { wipBalance = await agent.publicClient.readContract({ address: import_core_sdk2.WIP_TOKEN_ADDRESS, abi: [ { name: "balanceOf", type: "function", stateMutability: "view", inputs: [{ name: "account", type: "address" }], outputs: [{ name: "", type: "uint256" }] } ], functionName: "balanceOf", args: [targetAddress] }); } catch (error) { console.error("Error fetching WIP balance:", error); } return { status: "success", message: `\u2705 Account balances retrieved for ${targetAddress}`, account_info: { address: targetAddress, network: agent.network, is_own_wallet: targetAddress.toLowerCase() === agent.account.address.toLowerCase() }, native_balance: { symbol: "IP", balance: (0, import_viem2.formatEther)(ethBalance), balance_wei: ethBalance.toString(), usd_value: "N/A" // Could integrate price feeds later }, story_protocol_tokens: { wip: { symbol: "WIP", name: "Wrapped IP Token", balance: (0, import_viem2.formatEther)(wipBalance), balance_wei: wipBalance.toString(), contract_address: import_core_sdk2.WIP_TOKEN_ADDRESS, purpose: "Used for licensing fees and royalty payments" } }, portfolio_summary: { total_ip_balance: (0, import_viem2.formatEther)(ethBalance), total_wip_balance: (0, import_viem2.formatEther)(wipBalance), can_pay_gas: Number((0, import_viem2.formatEther)(ethBalance)) > 1e-3, can_pay_licensing_fees: wipBalance > 0, ready_for_ip_operations: Number((0, import_viem2.formatEther)(ethBalance)) > 1e-3 }, next_steps: Number((0, import_viem2.formatEther)(ethBalance)) < 1e-3 ? [ "\u{1F50B} Fund wallet with ETH for gas fees", "\u{1F48E} Acquire WIP tokens for licensing operations", "\u{1F3A8} Ready to register IP assets once funded" ] : [ "\u2705 Sufficient ETH for gas fees", "\u{1F3A8} Ready to register IP assets", "\u{1F3AB} Ready to mint and purchase licenses", wipBalance === BigInt(0) ? "\u{1F4A1} Consider acquiring WIP tokens for licensing" : "\u{1F48E} WIP tokens available for licensing" ] }; } catch (error) { throw new Error(`Failed to get account balances: ${error.message}`); } finally { await agent.disconnect(); } } }; // src/mcp/wallet/send_eth_tool.ts var import_zod2 = require("zod"); var import_viem3 = require("viem"); var SendETHTool = { name: "story_send_native_ip", description: "Send native IP token to another address for gas fees or payments", schema: { destination: import_zod2.z.string().regex(/^0x[0-9a-fA-F]{40}$/).describe("Recipient's Ethereum address"), amount: import_zod2.z.number().positive().describe("Amount of IP to send"), memo: import_zod2.z.string().optional().describe("Optional memo for the transaction") }, handler: async (agent, input) => { try { await agent.connect(); const destination = input.destination; const amount = (0, import_viem3.parseEther)(input.amount.toString()); const balance = await agent.publicClient.getBalance({ address: agent.account.address }); if (balance < amount) { throw new Error(`Insufficient balance. Available: ${Number(balance) / 1e18} IP, Required: ${input.amount} IP`); } let gasEstimate; try { gasEstimate = await agent.publicClient.estimateGas({ account: agent.account.address, to: destination, value: amount }); } catch (error) { throw new Error(`Transaction simulation failed: ${error.message}. Check recipient address and amount.`); } const gasPrice = await agent.publicClient.getGasPrice(); const gasCost = gasEstimate * gasPrice; if (balance < amount + gasCost) { throw new Error(`Insufficient balance for transaction + gas. Total needed: ${Number(amount + gasCost) / 1e18} IP`); } console.error(`\u2705 Native IP transfer simulation successful. Gas estimate: ${gasEstimate.toString()}`); const txHash = await agent.walletClient.sendTransaction({ account: agent.account, to: destination, value: amount, gas: gasEstimate }); const receipt = await agent.publicClient.waitForTransactionReceipt({ hash: txHash, confirmations: 1 }); return { status: "success", message: `\u2705 Successfully sent ${input.amount} IP to ${destination}`, transaction_details: { transaction_hash: txHash, from: agent.account.address, to: destination, amount: `${input.amount} IP`, amount_wei: amount.toString(), gas_used: receipt.gasUsed.toString(), gas_price: gasPrice.toString(), total_cost: `${Number(amount + receipt.gasUsed * gasPrice) / 1e18} IP`, block_number: receipt.blockNumber.toString(), confirmations: 1, memo: input.memo || "N/A" }, network_info: { network: agent.network, explorer_url: `${agent.networkInfo.blockExplorer}/tx/${txHash}` }, next_steps: [ "\u2705 Transaction confirmed on blockchain", "\u{1F50D} View transaction details on block explorer", "\u{1F4B0} Recipient can now use IP for Story Protocol operations" ] }; } catch (error) { throw new Error(`Failed to send IP: ${error.message}`); } finally { await agent.disconnect(); } } }; // src/mcp/wallet/send_token_tool.ts var import_zod3 = require("zod"); var import_viem4 = require("viem"); var import_core_sdk3 = require("@story-protocol/core-sdk"); var SendTokenTool = { name: "story_send_token", description: "Send Story Protocol tokens (WIP, or custom tokens) to another address", schema: { token_address: import_zod3.z.string().regex(/^0x[0-9a-fA-F]{40}$/).describe("Token contract address (use 'WIP' for WIP token shortcut)"), destination: import_zod3.z.string().regex(/^0x[0-9a-fA-F]{40}$/).describe("Recipient's Ethereum address"), amount: import_zod3.z.number().positive().describe("Amount of tokens to send"), memo: import_zod3.z.string().optional().describe("Optional memo for the transaction") }, handler: async (agent, input) => { try { await agent.connect(); const destination = input.destination; let tokenAddress = input.token_address; if (input.token_address === "WIP") { tokenAddress = import_core_sdk3.WIP_TOKEN_ADDRESS; } const amount = (0, import_viem4.parseEther)(input.amount.toString()); const erc20Abi = [ { name: "transfer", type: "function", stateMutability: "nonpayable", inputs: [ { name: "to", type: "address" }, { name: "amount", type: "uint256" } ], outputs: [{ name: "", type: "bool" }] }, { name: "balanceOf", type: "function", stateMutability: "view", inputs: [{ name: "account", type: "address" }], outputs: [{ name: "", type: "uint256" }] }, { name: "symbol", type: "function", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "string" }] }, { name: "decimals", type: "function", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "uint8" }] } ]; const [balance, symbol, decimals] = await Promise.all([ agent.publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "balanceOf", args: [agent.account.address] }), agent.publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "symbol" }), agent.publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "decimals" }) ]); if (balance < amount) { throw new Error(`Insufficient ${symbol} balance. Available: ${(0, import_viem4.formatEther)(balance)}, Required: ${input.amount}`); } const { request, result } = await agent.publicClient.simulateContract({ address: tokenAddress, abi: erc20Abi, functionName: "transfer", args: [destination, amount], account: agent.account.address }); console.error(`\u2705 Transfer simulation successful. Proceeding with transaction...`); const txHash = await agent.walletClient.writeContract(request); const receipt = await agent.publicClient.waitForTransactionReceipt({ hash: txHash, confirmations: 1 }); return { status: "success", message: `\u2705 Successfully sent ${input.amount} ${symbol} to ${destination}`, transaction_details: { transaction_hash: txHash, from: agent.account.address, to: destination, token_address: tokenAddress, token_symbol: symbol, amount: `${input.amount} ${symbol}`, amount_wei: amount.toString(), decimals, gas_used: receipt.gasUsed.toString(), block_number: receipt.blockNumber.toString(), confirmations: 1, memo: input.memo || "N/A" }, token_info: { contract_address: tokenAddress, symbol, decimals, is_story_protocol_token: tokenAddress === import_core_sdk3.WIP_TOKEN_ADDRESS }, network_info: { network: agent.network, explorer_url: `${agent.networkInfo.blockExplorer}/tx/${txHash}` }, next_steps: [ "\u2705 Token transfer confirmed on blockchain", "\u{1F50D} View transaction details on block explorer", `\u{1F48E} Recipient can now use ${symbol} tokens for Story Protocol operations` ] }; } catch (error) { throw new Error(`Failed to send tokens: ${error.message}`); } finally { await agent.disconnect(); } } }; // src/mcp/wallet/approve_token_tool.ts var import_zod4 = require("zod"); var import_viem5 = require("viem"); var import_core_sdk4 = require("@story-protocol/core-sdk"); var ApproveTokenTool = { name: "story_approve_token", description: "Approve Story Protocol contracts to spend your tokens (required for licensing operations)", schema: { token_address: import_zod4.z.string().regex(/^0x[0-9a-fA-F]{40}$/).describe("Token contract address (use 'WIP' for WIP token shortcut)"), spender: import_zod4.z.string().regex(/^0x[0-9a-fA-F]{40}$/).describe("Contract address to approve (Story Protocol contracts)"), amount: import_zod4.z.number().positive().optional().describe("Amount to approve (optional, defaults to unlimited)"), unlimited: import_zod4.z.boolean().default(true).describe("Set unlimited approval (recommended for convenience)") }, handler: async (agent, input) => { try { await agent.connect(); let tokenAddress = input.token_address; const spender = input.spender; if (input.token_address === "WIP") { tokenAddress = import_core_sdk4.WIP_TOKEN_ADDRESS; } const amount = input.unlimited || !input.amount ? import_viem5.maxUint256 : (0, import_viem5.parseEther)(input.amount.toString()); const erc20Abi = [ { name: "approve", type: "function", stateMutability: "nonpayable", inputs: [ { name: "spender", type: "address" }, { name: "amount", type: "uint256" } ], outputs: [{ name: "", type: "bool" }] }, { name: "allowance", type: "function", stateMutability: "view", inputs: [ { name: "owner", type: "address" }, { name: "spender", type: "address" } ], outputs: [{ name: "", type: "uint256" }] }, { name: "symbol", type: "function", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "string" }] }, { name: "balanceOf", type: "function", stateMutability: "view", inputs: [{ name: "account", type: "address" }], outputs: [{ name: "", type: "uint256" }] } ]; const [currentAllowance, symbol, balance] = await Promise.all([ agent.publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "allowance", args: [agent.account.address, spender] }), agent.publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "symbol" }), agent.publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "balanceOf", args: [agent.account.address] }) ]); if (currentAllowance >= amount && amount !== import_viem5.maxUint256) { return { status: "success", message: `\u2705 Sufficient approval already exists for ${symbol}`, approval_details: { token_address: tokenAddress, token_symbol: symbol, spender, current_allowance: input.unlimited ? "Unlimited" : (0, import_viem5.formatEther)(currentAllowance), requested_amount: input.unlimited ? "Unlimited" : input.amount?.toString(), approval_needed: false }, wallet_info: { balance: (0, import_viem5.formatEther)(balance), address: agent.account.address }, next_steps: [ "\u2705 Approval already sufficient", "\u{1F3A8} Ready to proceed with Story Protocol operations", "\u{1F4A1} No additional transaction needed" ] }; } const { request, result } = await agent.publicClient.simulateContract({ address: tokenAddress, abi: erc20Abi, functionName: "approve", args: [spender, amount], account: agent.account.address }); console.error(`\u2705 Approval simulation successful. Proceeding with transaction...`); const txHash = await agent.walletClient.writeContract(request); const receipt = await agent.publicClient.waitForTransactionReceipt({ hash: txHash, confirmations: 1 }); const newAllowance = await agent.publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "allowance", args: [agent.account.address, spender] }); return { status: "success", message: `\u2705 Successfully approved ${symbol} spending for Story Protocol contract`, transaction_details: { transaction_hash: txHash, from: agent.account.address, token_address: tokenAddress, token_symbol: symbol, spender, approved_amount: input.unlimited ? "Unlimited" : input.amount?.toString(), gas_used: receipt.gasUsed.toString(), block_number: receipt.blockNumber.toString(), confirmations: 1 }, approval_details: { previous_allowance: (0, import_viem5.formatEther)(currentAllowance), new_allowance: amount === import_viem5.maxUint256 ? "Unlimited" : (0, import_viem5.formatEther)(newAllowance), is_unlimited: amount === import_viem5.maxUint256, spender_contract: spender }, wallet_info: { balance: (0, import_viem5.formatEther)(balance), address: agent.account.address }, network_info: { network: agent.network, explorer_url: `${agent.networkInfo.blockExplorer}/tx/${txHash}` }, next_steps: [ "\u2705 Token approval confirmed on blockchain", "\u{1F3A8} Ready to register IP assets and mint licenses", "\u{1F48E} Story Protocol contracts can now spend your tokens", "\u{1F50D} View transaction details on block explorer" ] }; } catch (error) { throw new Error(`Failed to approve tokens: ${error.message}`); } finally { await agent.disconnect(); } } }; // src/mcp/wallet/check_allowance_tool.ts var import_zod5 = require("zod"); var import_viem6 = require("viem"); var import_core_sdk5 = require("@story-protocol/core-sdk"); var CheckAllowanceTool = { name: "story_check_allowance", description: "Check token allowance for Story Protocol contracts and other spenders", schema: { token_address: import_zod5.z.string().regex(/^0x[0-9a-fA-F]{40}$/).describe("Token contract address (use 'WIP' for WIP token shortcut)"), owner: import_zod5.z.string().regex(/^0x[0-9a-fA-F]{40}$/).optional().describe("Token owner address (optional, defaults to wallet address)"), spender: import_zod5.z.string().regex(/^0x[0-9a-fA-F]{40}$/).describe("Spender contract address to check allowance for") }, handler: async (agent, input) => { try { await agent.connect(); let tokenAddress = input.token_address; const owner = input.owner || agent.account.address; const spender = input.spender; if (input.token_address === "WIP") { tokenAddress = import_core_sdk5.WIP_TOKEN_ADDRESS; } const erc20Abi = [ { name: "allowance", type: "function", stateMutability: "view", inputs: [ { name: "owner", type: "address" }, { name: "spender", type: "address" } ], outputs: [{ name: "", type: "uint256" }] }, { name: "balanceOf", type: "function", stateMutability: "view", inputs: [{ name: "account", type: "address" }], outputs: [{ name: "", type: "uint256" }] }, { name: "symbol", type: "function", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "string" }] }, { name: "decimals", type: "function", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "uint8" }] }, { name: "name", type: "function", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "string" }] } ]; const [allowance, balance, symbol, decimals, name] = await Promise.all([ agent.publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "allowance", args: [owner, spender] }), agent.publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "balanceOf", args: [owner] }), agent.publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "symbol" }), agent.publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "decimals" }), agent.publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "name" }) ]); const maxUint2562 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); const isUnlimited = allowance >= maxUint2562 / BigInt(2); const allowanceFormatted = isUnlimited ? "Unlimited" : (0, import_viem6.formatEther)(allowance); const balanceFormatted = (0, import_viem6.formatEther)(balance); const canSpendBalance = allowance >= balance; const needsApproval = allowance === BigInt(0); const getRecommendations = () => { if (needsApproval) { return [ "\u26A0\uFE0F No allowance set - approval required", `Use story_approve_token to approve ${symbol} spending`, "Recommend setting unlimited approval for convenience" ]; } else if (!canSpendBalance && !isUnlimited) { return [ "\u26A0\uFE0F Allowance is less than current balance", `Current allowance: ${allowanceFormatted} ${symbol}`, `Current balance: ${balanceFormatted} ${symbol}`, "Consider increasing allowance for full balance access" ]; } else if (isUnlimited) { return [ "\u2705 Unlimited allowance set", "No further approvals needed for this token", "Ready for all Story Protocol operations" ]; } else { return [ "\u2705 Sufficient allowance for current balance", `Can spend up to ${allowanceFormatted} ${symbol}`, "Ready for Story Protocol operations" ]; } }; return { status: "success", message: `\u2705 Allowance checked for ${symbol} token`, allowance_details: { token_address: tokenAddress, token_name: name, token_symbol: symbol, token_decimals: decimals, owner, spender, allowance: allowanceFormatted, allowance_wei: allowance.toString(), is_unlimited: isUnlimited, is_zero: allowance === BigInt(0) }, balance_comparison: { owner_balance: balanceFormatted, owner_balance_wei: balance.toString(), can_spend_full_balance: canSpendBalance, allowance_vs_balance: allowance >= balance ? "sufficient" : "insufficient" }, contract_info: { is_story_protocol_token: tokenAddress === import_core_sdk5.WIP_TOKEN_ADDRESS, spender_contract: spender, is_own_wallet: owner.toLowerCase() === agent.account.address.toLowerCase() }, operational_status: { needs_approval: needsApproval, ready_for_operations: !needsApproval, can_spend_tokens: allowance > 0, approval_sufficient: canSpendBalance || isUnlimited }, network_info: { network: agent.network, block_explorer: agent.networkInfo.blockExplorer, token_explorer_url: `${agent.networkInfo.blockExplorer}/token/${tokenAddress}`, approval_explorer_url: `${agent.networkInfo.blockExplorer}/token/${tokenAddress}?a=${owner}` }, recommendations: getRecommendations(), next_steps: needsApproval ? [ `\u{1F527} Run: story_approve_token with token_address=${symbol === "WIP" ? "WIP" : tokenAddress}`, `\u{1F4C4} Specify spender=${spender}`, "\u{1F4A1} Consider unlimited approval for convenience", "\u{1F3A8} Then proceed with Story Protocol operations" ] : [ "\u2705 Allowance is properly configured", "\u{1F3A8} Ready to proceed with Story Protocol operations", `\u{1F48E} Can spend ${canSpendBalance ? "full balance" : "partial balance"} of ${symbol}`, "\u{1F50D} View token details on block explorer" ] }; } catch (error) { throw new Error(`Failed to check allowance: ${error.message}`); } finally { await agent.disconnect(); } } }; // src/mcp/wallet/get_token_info_tool.ts var import_zod6 = require("zod"); var import_viem7 = require("viem"); var import_core_sdk6 = require("@story-protocol/core-sdk"); var GetTokenInfoTool = { name: "story_get_token_info", description: "Get comprehensive information about ERC20 tokens including metadata and user balances", schema: { token_address: import_zod6.z.string().regex(/^0x[0-9a-fA-F]{40}$/).describe("Token contract address (use 'WIP' for WIP token shortcut)"), account_address: import_zod6.z.string().regex(/^0x[0-9a-fA-F]{40}$/).optional().describe("Address to check balance for (optional, defaults to wallet address)") }, handler: async (agent, input) => { try { await agent.connect(); let tokenAddress = input.token_address; const accountAddress = input.account_address || agent.account.address; if (input.token_address === "WIP") { tokenAddress = import_core_sdk6.WIP_TOKEN_ADDRESS; } const erc20Abi = [ { name: "name", type: "function", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "string" }] }, { name: "symbol", type: "function", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "string" }] }, { name: "decimals", type: "function", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "uint8" }] }, { name: "totalSupply", type: "function", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "uint256" }] }, { name: "balanceOf", type: "function", stateMutability: "view", inputs: [{ name: "account", type: "address" }], outputs: [{ name: "", type: "uint256" }] } ]; const [name, symbol, decimals, totalSupply, balance] = await Promise.all([ agent.publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "name" }), agent.publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "symbol" }), agent.publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "decimals" }), agent.publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "totalSupply" }), agent.publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "balanceOf", args: [accountAddress] }) ]); const bytecode = await agent.publicClient.getBytecode({ address: tokenAddress }); const isContract = !!(bytecode && bytecode !== "0x"); const totalSupplyFormatted = (0, import_viem7.formatEther)(totalSupply); const balanceFormatted = (0, import_viem7.formatEther)(balance); const balancePercentage = totalSupply > 0 ? Number(balance) / Number(totalSupply) * 100 : 0; const getTokenInfo = () => { if (tokenAddress === import_core_sdk6.WIP_TOKEN_ADDRESS) { return { type: "story_protocol_token", category: "wrapped_token", purpose: "Used for licensing fees and royalty payments on Story Protocol", official: true }; } else { return { type: "erc20_token", category: "custom", purpose: "Custom ERC20 token - verify legitimacy before use", official: false }; } }; const tokenInfo = getTokenInfo(); return { status: "success", message: `\u2705 Token information retrieved for ${symbol}`, token_metadata: { contract_address: tokenAddress, name, symbol, decimals, total_supply: totalSupplyFormatted, total_supply_wei: totalSupply.toString(), is_contract: isContract, ...tokenInfo }, account_balance: { address: accountAddress, balance: balanceFormatted, balance_wei: balance.toString(), percentage_of_supply: balancePercentage.toFixed(6) + "%", is_holder: balance > 0, is_own_wallet: accountAddress.toLowerCase() === agent.account.address.toLowerCase() }, supply_analysis: { total_supply_formatted: totalSupplyFormatted, user_balance_formatted: balanceFormatted, supply_concentration: balancePercentage > 1 ? "significant_holder" : balancePercentage > 0.1 ? "moderate_holder" : balancePercentage > 0 ? "small_holder" : "non_holder" }, story_protocol_integration: { is_story_token: tokenInfo.official, can_use_for_licensing: tokenAddress === import_core_sdk6.WIP_TOKEN_ADDRESS, can_use_for_governance: false, purpose: tokenInfo.purpose, recommended_for_ip_operations: tokenInfo.official }, network_info: { network: agent.network, block_explorer: agent.networkInfo.blockExplorer, token_explorer_url: `${agent.networkInfo.blockExplorer}/token/${tokenAddress}`, account_explorer_url: `${agent.networkInfo.blockExplorer}/token/${tokenAddress}?a=${accountAddress}` }, operational_status: { has_balance: balance > 0, can_transfer: balance > 0, ready_for_story_operations: tokenInfo.official && balance > 0, needs_acquisition: balance === BigInt(0) && tokenInfo.official }, next_steps: balance === BigInt(0) ? [ `\u{1F4B0} Acquire ${symbol} tokens to use for Story Protocol`, tokenInfo.official ? `\u{1F3AF} ${symbol} is required for licensing operations` : "\u26A0\uFE0F Verify token legitimacy before acquiring", `\u{1F50D} View token details on ${agent.networkInfo.blockExplorer}`, "\u{1F4A1} Use story_send_token to receive tokens from others" ] : [ `\u2705 You have ${balanceFormatted} ${symbol} tokens`, tokenInfo.official ? "\u{1F3A8} Ready for Story Protocol operations" : "\u26A0\uFE0F Verify token legitimacy before using", "\u{1F48E} Use story_approve_token to enable contract spending", "\u{1F504} Use story_send_token to transfer to others" ] }; } catch (error) { throw new Error(`Failed to get token info: ${error.message}`); } finally { await agent.disconnect(); } } }; // src/mcp/wallet/get_transaction_history_tool.ts var import_zod7 = require("zod"); var import_viem8 = require("viem"); var GetTransactionHistoryTool = { name: "story_get_transaction_history", description: "Get recent transaction history for the wallet or specified address", schema: { account_address: import_zod7.z.string().regex(/^0x[0-9a-fA-F]{40}$/).optional().describe("Address to check (optional, defaults to wallet address)"), limit: import_zod7.z.number().min(1).max(100).default(20).describe("Number of transactions to retrieve (max 100)") }, handler: async (agent, input) => { try { await agent.connect(); const targetAddress = input.account_address || agent.account.address; const limit = input.limit || 20; const currentBlock = await agent.publicClient.getBlockNumber(); const fromBlock = currentBlock - BigInt(1e4); const recentTransactions = []; const blocksToCheck = Math.min(Number(limit * 5), 1e3); for (let i = 0; i < blocksToCheck && recentTransactions.length < limit; i++) { try { const blockNumber = currentBlock - BigInt(i); const block = await agent.publicClient.getBlock({ blockNumber, includeTransactions: true }); for (const tx of block.transactions) { if (typeof tx === "object") { if ((tx.from?.toLowerCase() === targetAddress.toLowerCase() || tx.to?.toLowerCase() === targetAddress.toLowerCase()) && recentTransactions.length < limit) { try { const receipt = await agent.publicClient.getTransactionReceipt({ hash: tx.hash }); recentTransactions.push({ hash: tx.hash, block_number: block.number?.toString(), timestamp: new Date(Number(block.timestamp) * 1e3).toISOString(), from: tx.from, to: tx.to, value: tx.value ? (0, import_viem8.formatEther)(tx.value) : "0", gas_used: receipt.gasUsed.toString(), gas_price: tx.gasPrice?.toString(), status: receipt.status === "success" ? "success" : "failed", type: tx.from?.toLowerCase() === targetAddress.toLowerCase() ? "sent" : "received", is_contract_interaction: tx.to && tx.input !== "0x" }); } catch (receiptError) { recentTransactions.push({ hash: tx.hash, block_number: block.number?.toString(), timestamp: new Date(Number(block.timestamp) * 1e3).toISOString(), from: tx.from, to: tx.to, value: tx.value ? (0, import_viem8.formatEther)(tx.value) : "0", gas_used: "N/A", gas_price: tx.gasPrice?.toString(), status: "unknown", type: tx.from?.toLowerCase() === targetAddress.toLowerCase() ? "sent" : "received", is_contract_interaction: tx.to && tx.input !== "0x" }); } } } } } catch (blockError) { console.error(`Error fetching block ${currentBlock - BigInt(i)}:`, blockError); continue; } } recentTransactions.sort((a, b) => { const blockA = parseInt(a.block_number || "0"); const blockB = parseInt(b.block_number || "0"); return blockB - blockA; }); const sentTransactions = recentTransactions.filter((tx) => tx.type === "sent"); const receivedTransactions = recentTransactions.filter((tx) => tx.type === "received"); const contractInteractions = recentTransactions.filter((tx) => tx.is_contract_interaction); const totalSent = sentTransactions.reduce((sum, tx) => sum + parseFloat(tx.value), 0); const totalReceived = receivedTransactions.reduce((sum, tx) => sum + parseFloat(tx.value), 0); return { status: "success", message: `\u2705 Retrieved ${recentTransactions.length} recent transactions for ${targetAddress}`, account_info: { address: targetAddress, network: agent.network, is_own_wallet: targetAddress.toLowerCase() === agent.account.address.toLowerCase(), blocks_searched: blocksToCheck, from_block: fromBlock.toString(), to_block: currentBlock.toString() }, transaction_summary: { total_transactions: recentTransactions.length, sent_transactions: sentTransactions.length, received_transactions: receivedTransactions.length, contract_interactions: contractInteractions.length, total_eth_sent: `${totalSent.toFixed(6)} ETH`, total_eth_received: `${totalReceived.toFixed(6)} ETH`, net_eth_flow: `${(totalReceived - totalSent).toFixed(6)} ETH` }, transactions: recentTransactions.map((tx) => ({ ...tx, explorer_url: `${agent.networkInfo.blockExplorer}/tx/${tx.hash}`, age: tx.timestamp ? getTimeAgo(new Date(tx.timestamp)) : "Unknown" })), network_info: { network: agent.network, block_explorer: agent.networkInfo.blockExplorer, current_block: currentBlock.toString() }, story_protocol_activity: { ip_registrations: contractInteractions.filter( (tx) => tx.to?.toLowerCase().includes("story") || tx.to?.toLowerCase().includes("ip") ).length, licensing_transactions: contractInteractions.filter( (tx) => tx.to?.toLowerCase().includes("license") ).length, total_protocol_interactions: contractInteractions.length }, next_steps: recentTransactions.length === 0 ? [ "\u{1F50D} No recent transactions found", "\u{1F4A1} Start by funding your wallet with ETH", "\u{1F3A8} Begin registering IP assets on Story Protocol" ] : [ "\u2705 Transaction history retrieved successfully", "\u{1F50D} Click explorer URLs to view detailed transaction info", `\u{1F4CA} Found ${contractInteractions.length} smart contract interactions`, "\u{1F48E} Ready to analyze Story Protocol activity" ] }; } catch (error) { throw new Error(`Failed to get transaction history: ${error.message}`); } finally { await agent.disconnect(); } } }; var getTimeAgo = (date) => { const now = /* @__PURE__ */ new Date(); const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1e3); if (diffInSeconds < 60) return `${diffInSeconds} seconds ago`; if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)} minutes ago`; if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)} hours ago`; return `${Math.floor(diffInSeconds / 86400)} days ago`; }; // src/mcp/wallet/validate_address_tool.ts var import_zod8 = require("zod"); var import_viem9 = require("viem"); var ValidateAddressTool = { name: "story_validate_address", description: "Validate Ethereum address format and check if account exists on Story Protocol network", schema: { address: import_zod8.z.string().describe("Ethereum address to validate") }, handler: async (agent, input) => { try { await agent.connect(); const address = input.address; const isValidFormat = (0, import_viem9.isAddress)(address); if (!isValidFormat) { return { status: "invalid", message: `\u274C Invalid Ethereum address format: ${address}`, validation_details: { address, is_valid_format: false, is_checksum_valid: false, exists_on_network: false, error: "Invalid address format - must be 42 characters starting with 0x" }, recommendations: [ "\u{1F50D} Check that address starts with '0x'", "\u{1F4CF} Ensure address is exactly 42 characters long", "\u{1F524} Verify hexadecimal characters (0-9, a-f, A-F)", "\u{1F4CB} Copy address directly from source to avoid typos" ] }; } const validAddress = address; const checksumAddress = address; const isChecksumValid = (0, import_viem9.isAddress)(address); return { status: "valid", message: `\u2705 Valid Ethereum address: ${validAddress}`, validation_details: { address: validAddress, is_valid_format: isValidFormat, is_checksum_valid: isChecksumValid, network: agent.network }, network_info: { network: agent.network, chain_id: await agent.publicClient.getChainId(), block_explorer: agent.networkInfo.blockExplorer, explorer_url: `${agent.networkInfo.blockExplorer}/address/${validAddress}` } }; } catch (error) { throw new Error(`Failed to validate address: ${error.message}`); } finally { await agent.disconnect(); } } }; // src/mcp/wallet/wrap_ip_tool.ts var import_zod9 = require("zod"); var import_viem10 = require("viem"); var import_core_sdk7 = require("@story-protocol/core-sdk"); var WrapIPTool = { name: "story_wrap_ip", description: "Wrap IP tokens to WIP tokens for use in licensing and trading", schema: { amount: import_zod9.z.number().positive().describe("Amount of IP tokens to wrap into WIP tokens"), check_balance: import_zod9.z.boolean().default(true).describe("Check IP balance before wrapping") }, handler: async (agent, input) => { try { await agent.connect(); const amount = input.amount; const amountWei = (0, import_viem10.parseEther)(amount.toString()); console.error(`\u{1F504} Wrapping ${amount} IP tokens to WIP...`); if (input.check_balance) { console.error(`\u{1F4B0} Checking IP token balance...`); try { const ipBalance = await agent.publicClient.getBalance({ address: agent.account.address }); const ipBalanceFormatted = Number((0, import_viem10.formatEther)(ipBalance)); if (ipBalanceFormatted < amount) { throw new Error(`Insufficient IP balance. Required: ${amount} IP, Available: ${ipBalanceFormatted} IP`); } console.error(`\u2705 Sufficient IP balance: ${ipBalanceFormatted} IP`); } catch (error) { console.error(`\u26A0\uFE0F Could not verify IP balance: ${error}`); } } console.error(`\u{1F504} Executing wrap transaction...`); const response = await agent.client.wipClient.deposit({ amount: amountWei }); console.error(`\u{1F4CA} Fetching updated balances...`); let newWIPBalance = "0"; try { const wipBalance = await agent.publicClient.readContract({ address: import_core_sdk7.WIP_TOKEN_ADDRESS, // WIP token address abi: [ { name: "balanceOf", type: "function", stateMutability: "view", inputs: [{ name: "account", type: "address" }], outputs: [{ name: "", type: "uint256" }] } ], functionName: "balanceOf", args: [agent.account.address] }); newWIPBalance = (0, import_viem10.formatEther)(wipBalance); } catch (error) { console.error(`\u26A0\uFE0F Could not fetch updated balances: ${error}`); } console.error(`\u2705 Successfully wrapped ${amount} IP to WIP!`); return { status: "success", message: `\u2705 Successfully wrapped ${amount} IP tokens to WIP`, wrap_details: { amount_wrapped: `${amount} IP`, received: `${amount} WIP`, exchange_rate: "1:1 (IP to WIP)", wrapped_at: (/* @__PURE__ */ new Date()).toISOString() }, transaction_info: { tx_hash: response.txHash, block_explorer: `${agent.networkInfo.blockExplorer}/tx/${response.txHash}`, gas_used: "Varies by network congestion" }, balance_changes: { wip_bala