Last active
March 22, 2024 02:01
-
-
Save olegpetroveth/f2b73f052c5a55442c975a41eafa93fa to your computer and use it in GitHub Desktop.
Up to date SwapKit Client example
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
import type { AssetValue, ConnectWalletParams, SwapKit } from "@swapkit/core"; | |
import type { ThorchainProvider } from "@swapkit/thorchain"; | |
import type { keystoreWallet } from "@swapkit/wallet-keystore"; | |
import { SwapKitApi } from "@swapkit/api"; | |
import { FeeOption } from "@swapkit/core"; | |
import { Chain } from "@swapkit/types"; | |
import { logger } from "@thorswap/logger"; | |
type SupportedWallet = typeof keystoreWallet; | |
type ConnectWalletType = Record< | |
SupportedWallet["connectMethodName"][number], | |
(connectParams: ConnectWalletParams) => string | undefined | |
>; | |
export type SwapKitReturnType = ReturnType< | |
typeof SwapKit< | |
{ | |
thorchain: ReturnType<typeof ThorchainProvider>["methods"]; | |
}, | |
ConnectWalletType | |
> | |
>; | |
let sdkClient: SwapKitReturnType; | |
export const getSwapKitClient = async (phrase?: string) => { | |
if (sdkClient) return sdkClient; | |
const { SwapKit } = await import("@swapkit/core"); | |
const { keystoreWallet } = await import("@swapkit/wallet-keystore"); | |
const { ThorchainProvider } = await import("@swapkit/thorchain"); | |
if (!phrase) { | |
throw new Error("Phrase is required to initialize SwapKit client."); | |
} | |
const supportedWallets = [keystoreWallet]; | |
const core = SwapKit< | |
{ | |
thorchain: ReturnType<typeof ThorchainProvider>["methods"]; | |
}, | |
ConnectWalletType | |
>({ | |
apis: {}, | |
rpcUrls: {}, | |
stagenet: false, | |
config: { | |
stagenet: false, | |
ethplorerApiKey: process.env.ETHPLORER_API_KEY, | |
covalentApiKey: process.env.COVALENT_API_KEY, | |
}, | |
// @ts-expect-error bypass | |
wallets: supportedWallets, | |
// @ts-expect-error bypass | |
plugins: [ThorchainProvider], | |
}); | |
try { | |
// @ts-expect-error bypass | |
// eslint-disable-next-line @typescript-eslint/await-thenable | |
await core.connectKeystore([Chain.THORChain], phrase); | |
} catch (error) { | |
logger.error("Error connecting keystore", error); | |
} | |
sdkClient = core; | |
return sdkClient; | |
}; | |
export const executeSwap = async ({ | |
from, | |
recipient = "", | |
to, | |
}: { | |
from: AssetValue; | |
recipient?: string; | |
to: AssetValue; | |
}) => { | |
try { | |
const skClient = await getSwapKitClient(); | |
const buyAsset = to.toString(); | |
const sellAsset = from.toString(); | |
const quote = await SwapKitApi.getQuote({ | |
buyAsset, | |
sellAsset, | |
sellAmount: from.getValue("string"), | |
slippage: "1", | |
senderAddress: skClient.getAddress(from.chain), | |
recipientAddress: recipient ?? skClient.getAddress(to.chain), | |
}); | |
const route = quote?.routes?.[0]; | |
if (quote?.quoteId && route) { | |
const tx = await skClient.swap({ | |
streamSwap: true, | |
route, | |
feeOptionKey: FeeOption.Fast, | |
recipient, | |
}); | |
logger.info(`Swap executed: ${skClient.getExplorerTxUrl(from.chain, tx)} | |
In Asset: ${sellAsset.toString()} | |
In Asset amount: ${from.getValue("string")} | |
Out Asset: ${buyAsset.toString()} | |
Out Asset amount: ${route.streamingSwap?.expectedOutput ?? route?.expectedOutput} | |
Streaming swap: ${route.streamingSwap?.expectedOutput ? "Yes" : "No"} | |
Recipient: ${recipient} | |
`); | |
} | |
} catch (error) { | |
logger.error( | |
`Error executing swap: (from: ${from.toString()}, to: ${to.toString()}, amount: ${from.getValue("string")})`, | |
error, | |
); | |
} | |
}; | |
export const executeSend = async ({ | |
assetValue, | |
recipient, | |
}: { | |
assetValue: AssetValue; | |
recipient: string; | |
}) => { | |
try { | |
const skClient = await getSwapKitClient(); | |
const tx = await skClient.getWallet(assetValue.chain)?.transfer({ | |
assetValue, | |
recipient, | |
}); | |
if (!tx) { | |
throw new Error( | |
`Error executing send: (asset: ${assetValue.toString()}, recipient: ${recipient})`, | |
); | |
} | |
logger.info(`Send executed: ${skClient.getExplorerTxUrl(assetValue.chain, tx)}`); | |
} catch (error) { | |
logger.error( | |
`Error executing send: (asset: ${assetValue.toString()}, recipient: ${recipient})`, | |
error, | |
); | |
} | |
}; | |
export const getBalances = async () => { | |
try { | |
const skClient = await getSwapKitClient(); | |
const balance = skClient.getBalance(Chain.THORChain); | |
return balance; | |
} catch (error) { | |
logger.error("Error getting balances", error); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment