Skip to content
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

feat(ts): add cross-chain swap action #156

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions cdp-agentkit-core/typescript/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### Added

- Added `cross_chain_swap` action.

## [0.0.13] - 2025-01-22

### Added
Expand Down
1 change: 1 addition & 0 deletions cdp-agentkit-core/typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
],
"dependencies": {
"@coinbase/coinbase-sdk": "^0.14.1",
"@lifi/sdk": "^3.5.2",
"twitter-api-v2": "^1.18.2",
"viem": "^2.21.51",
"zod": "^3.23.8"
Expand Down
120 changes: 120 additions & 0 deletions cdp-agentkit-core/typescript/src/actions/cdp/cross_chain_swap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { CdpAction } from "./cdp_action";
import { Wallet } from "@coinbase/coinbase-sdk";
import {
createConfig,
EVM,
getQuote,
QuoteRequest,
convertQuoteToRoute,
executeRoute,
} from "@lifi/sdk";
import { base } from "viem/chains";
import { privateKeyToAccount } from "viem/accounts";
import { http, createWalletClient, publicActions } from "viem";
import { z } from "zod";

const CROSS_CHAIN_SWAP_PROMPT = `
This tool enables cross-chain token swaps using the LiFi protocol. It allows you to find a route to swap tokens from one chain to another. You'll need to specify:
- The source chain ID
- The destination chain ID
- The token on the source chain (address)
- The token on the destination chain (address)
- The amount to transfer (in the smallest unit of the token)
- The address from which the tokens are being transferred
`;

/**
* Input schema for cross-chain swap action.
*/

export const CrossChainSwapInput = z.object({
fromChain: z.number().describe("Source chain ID. e.g. 8453 for Base mainnet"),
toChain: z.number().describe("Destination chain ID. e.g. 10 for Optimism mainnet"),
fromToken: z
.string()
.describe(
"The contract address of the token on the source chain. Ensure this address corresponds to the specified fromChain.",
),
toToken: z
.string()
.describe(
"The contract address of the token on the destination chain. Ensure this address corresponds to the specified toChain.",
),
fromAmount: z
.string()
.describe(
"The amount to be transferred from the source chain, specified in the smallest unit of the token (e.g., wei for ETH).",
),
fromAddress: z.string().describe("The address from which the tokens are being transferred."),
});

/**
* Executes a cross-chain token swap using the LiFi protocol
*
* @param wallet - The wallet to execute the swap from
* @param args - The swap parameters including chains, tokens, and amounts
* @returns A string describing the transaction result
*/
export async function crossChainSwap(
wallet: Wallet,
args: z.infer<typeof CrossChainSwapInput>,
): Promise<string> {
try {
const walletAddress = await wallet.getDefaultAddress();
const privateKey = walletAddress.export();

console.log("Wallet address:", walletAddress.getId());
console.log("Wallet address type:", typeof walletAddress);

const client = createWalletClient({
account: privateKeyToAccount(privateKey as `0x${string}`),
chain: base,
transport: http("https://base-mainnet.g.alchemy.com/v2/2yW47qv-8qJlPfJEg0lzt3VPSSR51H2P"),
}).extend(publicActions);
Comment on lines +63 to +73
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the contribution @jlin27 !

We are working on extending AgentKit's wallet support to a more generic interface that will simplify this flow. We anticipate releasing the wallet provider interface in next week's release. I will circle back to this PR once the wallet provider interface is in master.

cc: @murrlincoln

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great to hear about the simplified wallet support coming soon!

Will check in and update once it's out. Cheers.


createConfig({
integrator: "CDP-AgentKit",
providers: [
EVM({
getWalletClient: async () => client,
}),
],
});

const quoteRequest: QuoteRequest = {
fromChain: args.fromChain,
toChain: args.toChain,
fromToken: args.fromToken,
toToken: args.toToken,
fromAmount: args.fromAmount,
fromAddress: walletAddress.getId(),
};

console.log("Quote request:", JSON.stringify(quoteRequest, null, 2));

const quote = await getQuote(quoteRequest);

const route = convertQuoteToRoute(quote);
const executedRoute = await executeRoute(route, {
// Gets called once the route object gets new updates
updateRouteHook(route) {
console.log(route);
},
});

return `Cross-chain swap executed successfully: ${JSON.stringify(executedRoute)}`;
} catch (error) {
console.error("Error:", error);
throw error;
}
}

/**
* Action for executing cross-chain token swaps using the LiFi protocol
*/
export class CrossChainSwapAction implements CdpAction<typeof CrossChainSwapInput> {
public name = "cross_chain_swap";
public description = CROSS_CHAIN_SWAP_PROMPT;
public argsSchema = CrossChainSwapInput;
public func = crossChainSwap;
}
3 changes: 3 additions & 0 deletions cdp-agentkit-core/typescript/src/actions/cdp/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { WrapEthAction } from "./wrap_eth";
import { MORPHO_ACTIONS } from "./defi/morpho";
import { PYTH_ACTIONS } from "./data/pyth";
import { WOW_ACTIONS } from "./defi/wow";
import { CrossChainSwapAction } from "./cross_chain_swap";

/**
* Retrieves all CDP action instances.
Expand All @@ -38,6 +39,7 @@ export function getAllCdpActions(): CdpAction<CdpActionSchemaAny>[] {
new TransferAction(),
new TransferNftAction(),
new WrapEthAction(),
new CrossChainSwapAction(),
];
}

Expand All @@ -62,4 +64,5 @@ export {
TransferAction,
TransferNftAction,
WrapEthAction,
CrossChainSwapAction,
};
63 changes: 63 additions & 0 deletions cdp-agentkit-core/typescript/src/tests/cross_chain_swap_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { Wallet } from "@coinbase/coinbase-sdk";
import { crossChainSwap, CrossChainSwapInput } from "../actions/cdp/cross_chain_swap";
import { getQuote, executeRoute } from "@lifi/sdk";
import { z } from "zod";

// Mock the dependencies
jest.mock("@lifi/sdk", () => ({
getQuote: jest.fn(),
executeRoute: jest.fn(),
}));

describe("crossChainSwap", () => {
let mockWallet: Wallet;
let mockArgs: z.infer<typeof CrossChainSwapInput>;

beforeEach(() => {
mockWallet = {
getDefaultAddress: jest.fn().mockResolvedValue({
getId: jest.fn().mockReturnValue("0xMockAddress"),
export: jest.fn().mockReturnValue("0xMockPrivateKey"),
}),
} as unknown as Wallet;

mockArgs = {
fromChain: 8453,
toChain: 10,
fromToken: "0xMockFromToken",
toToken: "0xMockToToken",
fromAmount: "1000000000000000000", // 1 token in smallest unit
fromAddress: "0xMockAddress",
};

(getQuote as jest.Mock).mockResolvedValue({
// Mocked quote response
});

(executeRoute as jest.Mock).mockResolvedValue({
// Mocked executed route response
});
});

it("should execute a cross-chain swap successfully", async () => {
const result = await crossChainSwap(mockWallet, mockArgs);

expect(getQuote).toHaveBeenCalledWith({
fromChain: mockArgs.fromChain,
toChain: mockArgs.toChain,
fromToken: mockArgs.fromToken,
toToken: mockArgs.toToken,
fromAmount: mockArgs.fromAmount,
fromAddress: "0xMockAddress",
});

expect(executeRoute).toHaveBeenCalled();
expect(result).toContain("Cross-chain swap executed successfully");
});

it("should throw an error if the swap fails", async () => {
(executeRoute as jest.Mock).mockRejectedValue(new Error("Swap failed"));

await expect(crossChainSwap(mockWallet, mockArgs)).rejects.toThrow("Swap failed");
});
});
1 change: 1 addition & 0 deletions cdp-langchain/typescript/src/toolkits/cdp_toolkit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import { CdpTool } from "../tools/cdp_tool";
* // - transfer
* // - transfer_nft
* // - trade
* // - cross_chain_swap
* // - deploy_token
* // - mint_nft
* // - deploy_nft
Expand Down
Loading