-
Notifications
You must be signed in to change notification settings - Fork 266
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
jlin27
wants to merge
2
commits into
coinbase:master
Choose a base branch
from
jlin27:feat/ts-cross-chain-swap
base: master
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.
+1,121
−1,352
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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 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 |
---|---|---|
|
@@ -2,6 +2,10 @@ | |
|
||
## Unreleased | ||
|
||
### Added | ||
|
||
- Added `cross_chain_swap` action. | ||
|
||
## [0.0.13] - 2025-01-22 | ||
|
||
### Added | ||
|
This file contains 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
120 changes: 120 additions & 0 deletions
120
cdp-agentkit-core/typescript/src/actions/cdp/cross_chain_swap.ts
This file contains 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,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); | ||
|
||
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; | ||
} |
This file contains 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
63 changes: 63 additions & 0 deletions
63
cdp-agentkit-core/typescript/src/tests/cross_chain_swap_test.ts
This file contains 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,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"); | ||
}); | ||
}); |
This file contains 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
Oops, something went wrong.
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.
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
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.
Great to hear about the simplified wallet support coming soon!
Will check in and update once it's out. Cheers.