Skip to content
SwapDK is a powerful suite of tools for building blockchain applications.

Vite

This guide will help you integrate SwapDK into your Vite application with proper Node.js polyfills and WebAssembly support.

Install SwapDK and required dependencies:

bash bun add @swapdk/sdk vite-plugin-node-polyfills

Update your vite.config.ts to include necessary polyfills and WebAssembly support:

// @noErrorValidation
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import wasm from "vite-plugin-wasm";
import topLevelAwait from "vite-plugin-top-level-await";
import { nodePolyfills } from "vite-plugin-node-polyfills";
export default defineConfig({
plugins: [
react(),
wasm(),
topLevelAwait(),
nodePolyfills({
exclude: ["fs"],
globals: {
Buffer: true,
global: true,
process: true,
},
protocolImports: true,
}),
],
define: {
"process.env": {},
global: "globalThis",
},
optimizeDeps: {
esbuildOptions: {
target: "esnext",
},
},
build: {
target: "esnext",
},
});

Create a SwapDK client instance:

// @noErrorValidation
import { createSwapKit } from "@swapdk/sdk";
export const swapKitClient = createSwapKit();

Here’s a basic example of using SwapDK in a React component:

import { useState, useEffect } from "react";
import { swapKitClient } from "./swapKitClient";
import { Chain, WalletOption } from "@swapdk/sdk";
function App() {
const [isConnected, setIsConnected] = useState(false);
const [address, setAddress] = useState<string>("");
const connectWallet = async () => {
try {
await swapKitClient.connectEVMWallet(
[Chain.Ethereum],
WalletOption.METAMASK
);
setIsConnected(true);
const ethAddress = await swapKitClient.getAddress(Chain.Ethereum);
setAddress(ethAddress);
} catch (error) {
console.error("Failed to connect wallet:", error);
}
};
const disconnectWallet = () => {
swapKitClient.disconnectWallet(Chain.Ethereum);
setIsConnected(false);
setAddress("");
};
return (
<div>
<h1>SwapKit + Vite</h1>
{!isConnected ? (
<button onClick={connectWallet}>Connect Wallet</button>
) : (
<div>
<p>Connected: {address}</p>
<button onClick={disconnectWallet}>Disconnect</button>
</div>
)}
</div>
);
}
export default App;

For environment variables in Vite, use the VITE_ prefix:

.env
VITE_SWAPDK_API_KEY=your_api_key_here
VITE_WALLETCONNECT_PROJECT_ID=your_project_id_here

Then configure SwapDK:

// @noErrorValidation
import { createSwapKit, SKConfig } from "@swapdk/sdk";
SKConfig.setApiKey("swapKit", import.meta.env.VITE_SWAPDK_API_KEY);
SKConfig.setApiKey(
"walletConnectProjectId",
import.meta.env.VITE_WALLETCONNECT_PROJECT_ID
);
export const swapKitClient = createSwapKit();

If you encounter WebAssembly-related errors, ensure you have the required plugins installed:

bash bun add -D vite-plugin-wasm vite-plugin-top-level-await

For a complete working example, check out the Vite playground