Skip to content

Commit

Permalink
chore: playgrounds
Browse files Browse the repository at this point in the history
  • Loading branch information
ice-chillios committed Feb 11, 2025
1 parent 7696e62 commit dc77047
Show file tree
Hide file tree
Showing 13 changed files with 94 additions and 81 deletions.
2 changes: 2 additions & 0 deletions packages/plugins/chainflip/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ function plugin({ getWallet }: SwapKitPluginParams) {
maxBoostFeeBps: maxBoostFeeBps || chainflip.maxBoostFeeBps,
});

// @ts-expect-error TODO: right now it's inferred from toolboxes
// we need to simplify this to one object params
const tx = await wallet.transfer({
assetValue: sellAsset,
from: wallet.address,
Expand Down
6 changes: 5 additions & 1 deletion packages/swapkit/helpers/src/modules/swapKitConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ export type SKConfigState = {
type SwapKitConfigStore = SKState & {
setApiKey: (key: keyof SKState["apiKeys"], apiKey: string) => void;
setConfig: (config: SKConfigState) => void;
setEnv: <T extends keyof SKState["envs"]>(key: T, value: SKState["envs"][T]) => void;
setExplorerUrl: (chain: keyof SKState["explorerUrls"], url: string) => void;
setNodeUrl: (chain: keyof SKState["nodeUrls"], url: string) => void;
setRpcUrl: (chain: keyof SKState["rpcUrls"], url: string) => void;
Expand All @@ -90,6 +91,7 @@ const swapKitState = createStore<SwapKitConfigStore>((set) => ({
...initialState,

setApiKey: (key, apiKey) => set((s) => ({ apiKeys: { ...s.apiKeys, [key]: apiKey } })),
setEnv: (key, value) => set((s) => ({ envs: { ...s.envs, [key]: value } })),
setExplorerUrl: (chain, url) =>
set((s) => ({ explorerUrls: { ...s.explorerUrls, [chain]: url } })),
setNodeUrl: (chain, url) => set((s) => ({ nodeUrls: { ...s.nodeUrls, [chain]: url } })),
Expand All @@ -108,12 +110,14 @@ const swapKitState = createStore<SwapKitConfigStore>((set) => ({
}));

export const SKConfig = {
getState: swapKitState.getState,
get: <T extends keyof SKState>(key: T) => swapKitState.getState()[key],
set: <T extends SKConfigState>(config: T) => swapKitState.getState().setConfig(config),

getState: () => swapKitState.getState(),
setApiKey: <T extends keyof SKState["apiKeys"]>(key: T, apiKey: string) =>
swapKitState.getState().setApiKey(key, apiKey),
setEnv: <T extends keyof SKState["envs"]>(key: T, value: SKState["envs"][T]) =>
swapKitState.getState().setEnv(key, value),
setExplorerUrl: <T extends keyof SKState["explorerUrls"]>(chain: T, url: string) =>
swapKitState.getState().setExplorerUrl(chain, url),
setNodeUrl: <T extends keyof SKState["nodeUrls"]>(chain: T, url: string) =>
Expand Down
1 change: 1 addition & 0 deletions packages/swapkit/helpers/src/modules/swapKitError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ const errorCodes = {
wallet_keepkey_contract_address_not_provided: 20902,
wallet_keepkey_send_transaction_no_address: 20903,
wallet_bitkeep_not_found: 21001,
wallet_exodus_sign_transaction_error: 21100,
/**
* Chainflip
*/
Expand Down
2 changes: 1 addition & 1 deletion packages/toolboxes/utxo/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,5 @@ export type UTXOTransferParams = {
};

export type UTXOWalletTransferParams<T, U> = UTXOTransferParams & {
signTransaction?: (params: T) => U | Promise<U>;
signTransaction?: (params: T) => Promise<U>;
};
2 changes: 2 additions & 0 deletions packages/wallets/exodus/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
type AddChainType,
Chain,
EVMChains,
SwapKitError,
WalletOption,
filterSupportedChains,
prepareNetworkSwitch,
Expand Down Expand Up @@ -84,6 +85,7 @@ export const getWalletMethods = async ({
};

await satsSignTransaction(signPsbtOptions);
if (!signedPsbt) throw new SwapKitError("wallet_exodus_sign_transaction_error");
return signedPsbt;
}

Expand Down
5 changes: 3 additions & 2 deletions packages/wallets/keepkey/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
type AddChainType,
Chain,
type DerivationPathArray,
NetworkDerivationPath,
SKConfig,
WalletOption,
filterSupportedChains,
Expand Down Expand Up @@ -122,7 +123,7 @@ const checkAndLaunch = async (attempts = 0) => {
function connectKeepkey(addChain: AddChainType) {
return async function connectKeepkey(
chains: Chain[],
derivationPathMap: Record<Chain, DerivationPathArray>,
derivationPathMap?: Record<Chain, DerivationPathArray>,
) {
const supportedChains = filterSupportedChains(
chains,
Expand All @@ -141,7 +142,7 @@ function connectKeepkey(addChain: AddChainType) {
const toolboxPromises = supportedChains.map(async (chain) => {
const walletMethods = await getWalletMethods({
chain,
derivationPath: derivationPathMap[chain],
derivationPath: derivationPathMap?.[chain] || NetworkDerivationPath[chain],
sdk: keepKeySdk,
});

Expand Down
7 changes: 5 additions & 2 deletions packages/wallets/keystore/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,10 @@ const getWalletMethods = async ({ chain, phrase, derivationPath }: Params) => {
const keys = await toolbox.createKeysForPath({ phrase, derivationPath });
const address = toolbox.getAddressFromKeys(keys);

function signTransaction({ builder, utxos }: Awaited<ReturnType<typeof toolbox.buildBCHTx>>) {
async function signTransaction({
builder,
utxos,
}: Awaited<ReturnType<typeof toolbox.buildBCHTx>>) {
utxos.forEach((utxo, index) => {
builder.sign(index, keys, undefined, 0x41, utxo.witnessUtxo?.value);
});
Expand Down Expand Up @@ -104,7 +107,7 @@ const getWalletMethods = async ({ chain, phrase, derivationPath }: Params) => {
toolbox.transfer({
...params,
from: address,
signTransaction: (psbt: Psbt) => psbt.signAllInputs(keys),
signTransaction: async (psbt: Psbt) => psbt.signAllInputs(keys),
}),
},
};
Expand Down
20 changes: 11 additions & 9 deletions playgrounds/nextjs/src/lib/swapKit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,17 @@ export const useSwapKit = () => {

const swapKitClient = SwapKit({
config: {
blockchairApiKey:
process.env.NEXT_PUBLIC_BLOCKCHAIR_API_KEY || "A___Tcn5B16iC3mMj7QrzZCb2Ho1QBUf",
covalentApiKey:
process.env.NEXT_PUBLIC_COVALENT_API_KEY || "cqt_rQ6333MVWCVJFVX3DbCCGMVqRH4q",
ethplorerApiKey: process.env.NEXT_PUBLIC_ETHPLORER_API_KEY || "freekey",
walletConnectProjectId: "",
keepkeyConfig: {
apiKey: localStorage.getItem("keepkeyApiKey") || "",
pairingInfo: {
apiKeys: {
blockchair:
process.env.NEXT_PUBLIC_BLOCKCHAIR_API_KEY || "A___Tcn5B16iC3mMj7QrzZCb2Ho1QBUf",
covalent:
process.env.NEXT_PUBLIC_COVALENT_API_KEY || "cqt_rQ6333MVWCVJFVX3DbCCGMVqRH4q",
ethplorer: process.env.NEXT_PUBLIC_ETHPLORER_API_KEY || "freekey",
walletConnectProjectId: "",
keepKey: localStorage.getItem("keepkeyApiKey") || "",
},
integrations: {
keepKey: {
name: "THORSwap",
imageUrl: "https://www.thorswap.finance/logo.png",
basePath: "swap",
Expand Down
26 changes: 18 additions & 8 deletions playgrounds/vite/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AssetValue, type Chain, type FullWallet } from "@swapkit/core";
import { AssetValue, type Chain, type FullWallet, SKConfig } from "@swapkit/core";
import { useCallback, useEffect, useMemo, useState } from "react";

import { WalletWidget } from "@swapkit/wallet-exodus";
Expand Down Expand Up @@ -27,9 +27,11 @@ const App = () => {
* NOTE: Test API keys - please use your own API keys in app as those will timeout, reach limits, etc.
*/
const [keys, setKeys] = useState({
blockchairApiKey: import.meta.env.VITE_BLOCKCHAIR_API_KEY || "A___Tcn5B16iC3mMj7QrzZCb2Ho1QBUf",
covalentApiKey: import.meta.env.VITE_COVALENT_API_KEY || "cqt_rQ6333MVWCVJFVX3DbCCGMVqRH4q",
ethplorerApiKey: import.meta.env.VITE_ETHPLORER_API_KEY || "freekey",
blockchair: (import.meta.env.VITE_BLOCKCHAIR_API_KEY ||
"A___Tcn5B16iC3mMj7QrzZCb2Ho1QBUf") as string,
covalent: (import.meta.env.VITE_COVALENT_API_KEY ||
"cqt_rQ6333MVWCVJFVX3DbCCGMVqRH4q") as string,
ethplorer: (import.meta.env.VITE_ETHPLORER_API_KEY || "freekey") as string,
walletConnectProjectId: "",
brokerEndpoint: "https://dev-api.swapkit.dev/channel",
});
Expand All @@ -39,7 +41,15 @@ const App = () => {
outputAsset?: AssetValue;
}>({});

const skClient = getSwapKitClient({ ...keys, stagenet });
const skClient = getSwapKitClient(keys);

const toggleStagenet = useCallback(() => {
setStagenet((v) => {
const next = !v;
SKConfig.setEnv("isStagenet", next);
return next;
});
}, []);

useEffect(() => {
AssetValue.loadStaticAssets().then(({ ok }) => {
Expand Down Expand Up @@ -86,13 +96,13 @@ const App = () => {
send: skClient ? <Send inputAsset={inputAsset} skClient={skClient} /> : null,
earn: <div>Earn</div>,
multisig: skClient ? (
<Multisig inputAsset={inputAsset} phrase={phrase} skClient={skClient} stagenet={stagenet} />
<Multisig inputAsset={inputAsset} phrase={phrase} skClient={skClient} />
) : null,
liquidity: skClient ? (
<Liquidity otherAsset={outputAsset} nativeAsset={inputAsset} skClient={skClient} />
) : null,
}),
[skClient, inputAsset, outputAsset, phrase, stagenet],
[skClient, inputAsset, outputAsset, phrase],
);

return (
Expand All @@ -110,7 +120,7 @@ const App = () => {
/>
))}
</div>
<button onClick={() => setStagenet((v) => !v)} type="button">
<button onClick={toggleStagenet} type="button">
Toggle Stagenet - Currently = {`${stagenet}`.toUpperCase()}
</button>
</h3>
Expand Down
4 changes: 1 addition & 3 deletions playgrounds/vite/src/Multisig/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,13 @@ import type { SwapKitClient } from "../swapKitClient";
export default function Multisig({
inputAsset,
skClient,
stagenet,
phrase,
}: {
skClient?: SwapKitClient;
inputAsset?: AssetValue;
stagenet?: boolean;
phrase: string;
}) {
const toolbox = useMemo(() => ThorchainToolbox({ stagenet }), [stagenet]);
const toolbox = useMemo(() => ThorchainToolbox(), []);
const [pubkeys, setPubkeys] = useState({ 0: "", 1: "" });
const [threshold, setThreshold] = useState(2);
const [recipient, setRecipient] = useState("");
Expand Down
16 changes: 7 additions & 9 deletions playgrounds/vite/src/Send/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AssetValue, Chain, CryptoChain } from "@swapkit/core";
import type { AssetValue } from "@swapkit/core";
import { useCallback, useState } from "react";
import type { SwapKitClient } from "../swapKitClient";

Expand Down Expand Up @@ -29,14 +29,12 @@ export default function Send({
if (!(inputAsset && inputAssetValue?.gt(0) && skClient)) return;

const from = skClient.getAddress(inputAsset.chain);
const txHash = await skClient
.getWallet(inputAssetValue.chain as Exclude<CryptoChain, Chain.Radix>)
.transfer({
from,
assetValue: inputAssetValue,
memo: "",
recipient,
});
const txHash = await skClient.transfer({
from,
assetValue: inputAssetValue,
memo: "",
recipient,
});

window.open(
`${skClient.getExplorerTxUrl({ chain: inputAssetValue.chain, txHash: txHash as string })}`,
Expand Down
25 changes: 11 additions & 14 deletions playgrounds/vite/src/Swap/SwapInputs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,20 +38,17 @@ export const SwapInputs = ({ skClient, inputAsset, outputAsset, handleSwap }: Pr
// const providers = Object.values(ProviderName);

try {
const { routes } = await SwapKitApi.getSwapQuoteV2(
{
sellAsset: inputAsset.toString(),
sellAmount: inputAssetValue.getValue("string"),
buyAsset: outputAsset.toString(),
sourceAddress,
destinationAddress,
slippage: 3,
affiliate: "t",
affiliateFee: 0,
includeTx: true,
},
true,
);
const { routes } = await SwapKitApi.getSwapQuote({
sellAsset: inputAsset.toString(),
sellAmount: inputAssetValue.getValue("string"),
buyAsset: outputAsset.toString(),
sourceAddress,
destinationAddress,
slippage: 3,
affiliate: "t",
affiliateFee: 0,
includeTx: true,
});

setRoutes(routes || []);
} finally {
Expand Down
59 changes: 27 additions & 32 deletions playgrounds/vite/src/swapKitClient.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,39 @@
import { createSwapKit } from "@swapkit/sdk";
import { SwapKit } from "@swapkit/sdk";

export type SwapKitClient = ReturnType<typeof createSwapKit>;

let oldKey = "";
let client: SwapKitClient;

export const getSwapKitClient = (
params: {
ethplorerApiKey?: string;
covalentApiKey?: string;
blockchairApiKey?: string;
walletConnectProjectId?: string;
stagenet?: boolean;
brokerEndpoint?: string;
} = {},
) => {
const key = JSON.stringify(params);

if (key === oldKey) {
return client;
}

oldKey = key;

client = createSwapKit({
export const getSwapKitClient = ({
ethplorer,
covalent,
blockchair,
walletConnectProjectId,
brokerEndpoint,
}: {
ethplorer?: string;
covalent?: string;
blockchair?: string;
walletConnectProjectId?: string;
brokerEndpoint?: string;
} = {}) => {
return SwapKit({
config: {
...params,
keepkeyConfig: {
apiKey: localStorage.getItem("keepkeyApiKey") || "1234",
pairingInfo: {
apiKeys: {
ethplorer,
covalent,
blockchair,
walletConnectProjectId,
keepKey: localStorage.getItem("keepkeyApiKey") || "1234",
},
integrations: {
keepKey: {
name: "swapKit-demo-app",
imageUrl:
"https://repository-images.githubusercontent.com/587472295/feec8a61-39b2-4615-b293-145e97f49b5a",
basePath: "http://localhost:1646/spec/swagger.json",
url: "http://localhost:1646",
},
chainflip: {
brokerUrl: brokerEndpoint || "",
},
},
chainflipBrokerUrl: params.brokerEndpoint,
},
});

return client;
};

0 comments on commit dc77047

Please sign in to comment.