-
Notifications
You must be signed in to change notification settings - Fork 43
feat(tools): add getAccountInfo tool for Stellar account lookup #82
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
OmcarSN
wants to merge
1
commit into
Stellar-Tools:main
Choose a base branch
from
OmcarSN:feat/get-account-info-tool
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| /** | ||
| * Unit tests for getAccountInfoTool | ||
| * | ||
| * Run with: npx jest tools/getAccountInfo.test.ts | ||
| */ | ||
|
|
||
| import { getAccountInfoTool } from "./getAccountInfo"; | ||
|
|
||
| // ── Helpers ──────────────────────────────────────────────────────────────── | ||
|
|
||
| const VALID_TESTNET_KEY = "GAAZI4TCR3TY5OJHCTJC2A4QSY6CJWJH5IAJTGKIN2ER7LBNVKOCCWN"; | ||
| const INVALID_KEY_SHORT = "GABC123"; | ||
| const INVALID_KEY_WRONG_PREFIX = "XAAZI4TCR3TY5OJHCTJC2A4QSY6CJWJH5IAJTGKIN2ER7LBNVKOCCWN"; | ||
| const UNFUNDED_KEY = "GDQJUTQYK2MQX2VGDR2FYWLIYAQIEGXTQVTFEMGH532XDG3NH8QIXHF"; | ||
|
|
||
| // ── Schema Validation Tests ──────────────────────────────────────────────── | ||
|
|
||
| describe("getAccountInfoTool — schema validation", () => { | ||
| it("should reject a public key that is too short", async () => { | ||
| const result = await getAccountInfoTool.invoke({ | ||
| publicKey: INVALID_KEY_SHORT, | ||
| network: "testnet", | ||
| }); | ||
| // Zod will throw and LangChain surfaces it as an error string | ||
| expect(result).toMatch(/invalid/i); | ||
| }); | ||
|
|
||
| it("should reject a public key that does not start with G", async () => { | ||
| const result = await getAccountInfoTool.invoke({ | ||
| publicKey: INVALID_KEY_WRONG_PREFIX, | ||
| network: "testnet", | ||
| }); | ||
| expect(result).toMatch(/invalid/i); | ||
| }); | ||
|
|
||
| it("should default to testnet when network is omitted", async () => { | ||
| // We only test that the call doesn't crash due to missing network. | ||
| // The actual network response is tested in integration tests. | ||
| const schema = getAccountInfoTool.schema; | ||
| const parsed = schema.parse({ publicKey: VALID_TESTNET_KEY }); | ||
| expect(parsed.network).toBe("testnet"); | ||
| }); | ||
| }); | ||
|
|
||
| // ── Output Format Tests ──────────────────────────────────────────────────── | ||
|
|
||
| describe("getAccountInfoTool — output format", () => { | ||
| it("should include account header in successful response", async () => { | ||
| const result = await getAccountInfoTool.invoke({ | ||
| publicKey: VALID_TESTNET_KEY, | ||
| network: "testnet", | ||
| }); | ||
| // Whether the account exists or not, the response should be a non-empty string | ||
| expect(typeof result).toBe("string"); | ||
| expect(result.length).toBeGreaterThan(0); | ||
| }); | ||
|
|
||
| it("should return a descriptive message for an unfunded account", async () => { | ||
| const result = await getAccountInfoTool.invoke({ | ||
| publicKey: UNFUNDED_KEY, | ||
| network: "testnet", | ||
| }); | ||
| // Should mention the account doesn't exist or failed to fetch | ||
| expect(result).toMatch(/does not exist|not.*fund|failed/i); | ||
| }); | ||
|
|
||
| it("should include 'testnet' in the response for testnet queries", async () => { | ||
| const result = await getAccountInfoTool.invoke({ | ||
| publicKey: VALID_TESTNET_KEY, | ||
| network: "testnet", | ||
| }); | ||
| // Either the account info header or the error message should mention testnet | ||
| expect(result).toMatch(/testnet/i); | ||
| }); | ||
| }); | ||
|
|
||
| // ── Tool Metadata Tests ──────────────────────────────────────────────────── | ||
|
|
||
| describe("getAccountInfoTool — metadata", () => { | ||
| it("should have the correct tool name", () => { | ||
| expect(getAccountInfoTool.name).toBe("get_account_info"); | ||
| }); | ||
|
|
||
| it("should have a non-empty description", () => { | ||
| expect(getAccountInfoTool.description.length).toBeGreaterThan(20); | ||
| }); | ||
|
|
||
| it("should mention 'balance' in the description", () => { | ||
| expect(getAccountInfoTool.description.toLowerCase()).toContain("balance"); | ||
| }); | ||
|
|
||
| it("should accept mainnet as a valid network option", () => { | ||
| const schema = getAccountInfoTool.schema; | ||
| expect(() => | ||
| schema.parse({ publicKey: VALID_TESTNET_KEY, network: "mainnet" }) | ||
| ).not.toThrow(); | ||
| }); | ||
|
|
||
| it("should reject an unknown network value", () => { | ||
| const schema = getAccountInfoTool.schema; | ||
| expect(() => | ||
| schema.parse({ publicKey: VALID_TESTNET_KEY, network: "devnet" }) | ||
| ).toThrow(); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,184 @@ | ||
| import { DynamicStructuredTool } from "@langchain/core/tools"; | ||
| import { z } from "zod"; | ||
| import * as StellarSdk from "@stellar/stellar-sdk"; | ||
|
|
||
| /** | ||
| * Input schema for the getAccountInfo tool. | ||
| * Validates that a proper Stellar public key (G...) is supplied, | ||
| * and allows the caller to choose between testnet and mainnet. | ||
| */ | ||
| const GetAccountInfoSchema = z.object({ | ||
| publicKey: z | ||
| .string() | ||
| .min(56) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: Public key validation is only length/prefix-based, so malformed Stellar addresses can pass schema validation instead of being rejected immediately. Prompt for AI agents |
||
| .max(56) | ||
| .startsWith("G") | ||
| .describe( | ||
| "The Stellar public key (G... address) of the account to look up." | ||
| ), | ||
| network: z | ||
| .enum(["testnet", "mainnet"]) | ||
| .default("testnet") | ||
| .describe("Which Stellar network to query. Defaults to testnet."), | ||
| }); | ||
|
|
||
| /** | ||
| * Represents a single asset balance on a Stellar account. | ||
| */ | ||
| interface AssetBalance { | ||
| asset: string; // "native" → XLM; otherwise "CODE:ISSUER" | ||
| balance: string; // String to preserve decimal precision | ||
| limit?: string; // Trustline limit (non-native assets only) | ||
| } | ||
|
|
||
| /** | ||
| * Structured result returned by getAccountInfo. | ||
| */ | ||
| interface AccountInfoResult { | ||
| publicKey: string; | ||
| sequence: string; | ||
| balances: AssetBalance[]; | ||
| subentryCount: number; | ||
| isAuthRequired: boolean; | ||
| isAuthRevocable: boolean; | ||
| isAuthImmutable: boolean; | ||
| homeDomain?: string; | ||
| network: string; | ||
| } | ||
|
|
||
| /** | ||
| * Fetch full account information from the Stellar Horizon API. | ||
| * | ||
| * @param publicKey - Stellar G-address | ||
| * @param network - "testnet" | "mainnet" | ||
| * @returns Structured account info or a human-readable error string | ||
| */ | ||
| async function fetchAccountInfo( | ||
| publicKey: string, | ||
| network: "testnet" | "mainnet" | ||
| ): Promise<AccountInfoResult | string> { | ||
| const horizonUrl = | ||
| network === "mainnet" | ||
| ? "https://horizon.stellar.org" | ||
| : "https://horizon-testnet.stellar.org"; | ||
|
|
||
| const server = new StellarSdk.Horizon.Server(horizonUrl); | ||
|
|
||
| try { | ||
| const account = await server.loadAccount(publicKey); | ||
|
|
||
| const balances: AssetBalance[] = account.balances.map((b) => { | ||
| if (b.asset_type === "native") { | ||
| return { asset: "XLM (native)", balance: b.balance }; | ||
| } | ||
| // Type-safe narrowing: non-native balances always have asset_code + asset_issuer | ||
| const nonNative = b as StellarSdk.Horizon.HorizonApi.BalanceLine & { | ||
| asset_code: string; | ||
| asset_issuer: string; | ||
| limit: string; | ||
| }; | ||
| return { | ||
| asset: `${nonNative.asset_code}:${nonNative.asset_issuer}`, | ||
| balance: nonNative.balance, | ||
| limit: nonNative.limit, | ||
| }; | ||
| }); | ||
|
|
||
| return { | ||
| publicKey, | ||
| sequence: account.sequence, | ||
| balances, | ||
| subentryCount: account.subentry_count, | ||
| isAuthRequired: account.flags.auth_required, | ||
| isAuthRevocable: account.flags.auth_revocable, | ||
| isAuthImmutable: account.flags.auth_immutable, | ||
| homeDomain: account.home_domain, | ||
| network, | ||
| }; | ||
| } catch (err: unknown) { | ||
| // Horizon returns a structured error for unknown accounts | ||
| if ( | ||
| err instanceof StellarSdk.Horizon.NetworkError && | ||
| (err as unknown as { response?: { status: number } }).response?.status === 404 | ||
| ) { | ||
| return `Account ${publicKey} does not exist on ${network}. It may not have been funded yet.`; | ||
| } | ||
| const message = err instanceof Error ? err.message : String(err); | ||
| return `Failed to fetch account info: ${message}`; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Format the account info result into a human-readable string | ||
| * suitable for use as a LangChain tool response. | ||
| */ | ||
| function formatResult(result: AccountInfoResult | string): string { | ||
| if (typeof result === "string") { | ||
| return result; // Already a human-readable error | ||
| } | ||
|
|
||
| const balanceLines = result.balances | ||
| .map((b) => { | ||
| const limitStr = b.limit ? ` (limit: ${b.limit})` : ""; | ||
| return ` • ${b.asset}: ${b.balance}${limitStr}`; | ||
| }) | ||
| .join("\n"); | ||
|
|
||
| const flags = [ | ||
| result.isAuthRequired ? "auth_required" : null, | ||
| result.isAuthRevocable ? "auth_revocable" : null, | ||
| result.isAuthImmutable ? "auth_immutable" : null, | ||
| ] | ||
| .filter(Boolean) | ||
| .join(", ") || "none"; | ||
|
|
||
| return [ | ||
| `═══ Stellar Account Info (${result.network}) ═══`, | ||
| `Public Key : ${result.publicKey}`, | ||
| `Sequence : ${result.sequence}`, | ||
| `Subentries : ${result.subentryCount}`, | ||
| `Flags : ${flags}`, | ||
| result.homeDomain ? `Home Domain : ${result.homeDomain}` : null, | ||
| ``, | ||
| `Balances:`, | ||
| balanceLines || " (no balances found)", | ||
| ] | ||
| .filter((line) => line !== null) | ||
| .join("\n"); | ||
| } | ||
|
|
||
| /** | ||
| * LangChain DynamicStructuredTool: getAccountInfo | ||
| * | ||
| * Allows an AI agent to look up any Stellar account's balances, | ||
| * sequence number, trustlines, and account flags before executing | ||
| * swaps, payments, or other DeFi operations. | ||
| * | ||
| * @example | ||
| * // Agent can call: | ||
| * // "Check the balance of GABC...XYZ on testnet" | ||
| * // → returns structured account info with all asset balances | ||
| */ | ||
| export const getAccountInfoTool = new DynamicStructuredTool({ | ||
| name: "get_account_info", | ||
| description: ` | ||
| Fetches complete information for a Stellar account including: | ||
| - All asset balances (XLM and any tokens/trustlines) | ||
| - Account sequence number | ||
| - Account flags (auth_required, auth_revocable, auth_immutable) | ||
| - Trustline limits for non-native assets | ||
| - Home domain (if set) | ||
|
|
||
| Use this tool BEFORE performing swaps, payments, or LP operations | ||
| to verify the account exists and has sufficient balance. | ||
|
|
||
| Supports both testnet and mainnet. | ||
| `.trim(), | ||
| schema: GetAccountInfoSchema, | ||
| func: async ({ publicKey, network }) => { | ||
| const result = await fetchAccountInfo(publicKey, network); | ||
| return formatResult(result); | ||
| }, | ||
| }); | ||
|
|
||
| export type { AccountInfoResult, AssetBalance }; | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P2: Invalid-input tests assert a resolved string from
invoke(), but schema validation rejects before a normal result is returned.Prompt for AI agents