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

Vite

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

Install SwapKit and required dependencies:

Terminal window
bun add @swapkit/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 SwapKit client instance:

src/swapKitClient.ts
// @noErrorValidation
import { createSwapKit } from '@swapkit/sdk';
export const swapKitClient = createSwapKit();

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

src/App.tsx
// @noErrorValidation
import { useState, useEffect } from 'react';
import { swapKitClient } from './swapKitClient';
import { Chain, WalletOption } from '@swapkit/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_SWAPKIT_API_KEY=your_api_key_here
VITE_WALLETCONNECT_PROJECT_ID=your_project_id_here

Then configure SwapKit:

// @noErrorValidation
import { createSwapKit, SKConfig } from '@swapkit/sdk';
// Configure API keys
SKConfig.setApiKey('swapKit', import.meta.env.VITE_SWAPKIT_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:

Terminal window
bun add -D vite-plugin-wasm vite-plugin-top-level-await

For a complete working example, check out the Vite playground in the SwapKit repository.