Vite
This guide will help you integrate SwapKit into your Vite application with proper Node.js polyfills and WebAssembly support.
Installation
Section titled “Installation”Install SwapKit and required dependencies:
bun add @swapkit/sdk vite-plugin-node-polyfills
pnpm add @swapkit/sdk vite-plugin-node-polyfills
npm install @swapkit/sdk vite-plugin-node-polyfills
yarn add @swapkit/sdk vite-plugin-node-polyfills
Vite Configuration
Section titled “Vite Configuration”Update your vite.config.ts
to include necessary polyfills and WebAssembly support:
import { function defineConfig(config: UserConfig): UserConfig (+5 overloads)
Type helper to make it easier to use vite.config.ts
accepts a direct
{@link
UserConfig
}
object, or a function that returns it.
The function receives a
{@link
ConfigEnv
}
object.defineConfig } from 'vite';
import function react(opts?: Options): PluginOption[]
react from '@vitejs/plugin-react';
import function wasm(): any
wasm from "vite-plugin-wasm";
import function topLevelAwait(options?: Options): Plugin
topLevelAwait from "vite-plugin-top-level-await";
import { const nodePolyfills: (options?: PolyfillOptions) => Plugin
Returns a Vite plugin to polyfill Node's Core Modules for browser environments. Supports `node:` protocol imports.nodePolyfills } from 'vite-plugin-node-polyfills';
export default function defineConfig(config: UserConfig): UserConfig (+5 overloads)
Type helper to make it easier to use vite.config.ts
accepts a direct
{@link
UserConfig
}
object, or a function that returns it.
The function receives a
{@link
ConfigEnv
}
object.defineConfig({
UserConfig.plugins?: PluginOption[] | undefined
Array of vite plugins to use.plugins: [
function react(opts?: Options): PluginOption[]
react(),
function wasm(): any
wasm(),
function topLevelAwait(options?: Options): Plugin
topLevelAwait(),
function nodePolyfills(options?: PolyfillOptions): Plugin
Returns a Vite plugin to polyfill Node's Core Modules for browser environments. Supports `node:` protocol imports.nodePolyfills({
exclude: ['fs'],
globals?: {
Buffer?: BooleanOrBuildTarget;
global?: BooleanOrBuildTarget;
process?: BooleanOrBuildTarget;
} | undefined
Specify whether specific globals should be polyfilled.globals: {
Buffer?: BooleanOrBuildTarget | undefined
Buffer: true,
global?: BooleanOrBuildTarget | undefined
global: true,
process?: BooleanOrBuildTarget | undefined
process: true,
},
protocolImports?: boolean | undefined
Specify whether the Node protocol version of an import (e.g. `node:buffer`) should be polyfilled too.protocolImports: true,
}),
],
define?: Record<string, any> | undefined
Define global variable replacements.
Entries will be defined on `window` during dev and replaced during build.define: {
'process.env': {},
global: string
global: 'globalThis',
},
UserConfig.optimizeDeps?: DepOptimizationOptions | undefined
Dep optimization optionsoptimizeDeps: {
DepOptimizationConfig.esbuildOptions?: Omit<BuildOptions, "bundle" | "entryPoints" | "external" | "write" | "watch" | "outdir" | "outfile" | "outbase" | "outExtension" | "metafile"> | undefined
Options to pass to esbuild during the dep scanning and optimization
Certain options are omitted since changing them would not be compatible
with Vite's dep optimization.
- `external` is also omitted, use Vite's `optimizeDeps.exclude` option
- `plugins` are merged with Vite's dep plugin
https://esbuild.github.io/apiesbuildOptions: {
target?: string | string[] | undefined
Documentation: https://esbuild.github.io/api/#targettarget: 'esnext',
},
},
build?: BuildEnvironmentOptions | undefined
Build specific optionsbuild: {
BuildEnvironmentOptions.target?: string | false | string[] | undefined
Compatibility transform target. The transform is performed with esbuild
and the lowest supported target is es2015. Note this only handles
syntax transformation and does not cover polyfills
Default: 'modules' - transpile targeting browsers that natively support
dynamic es module imports and `import.meta`
(Chrome 87+, Firefox 78+, Safari 14+, Edge 88+).
Another special value is 'esnext' - which only performs minimal transpiling
(for minification compat).
For custom targets, see https://esbuild.github.io/api/#target and
https://esbuild.github.io/content-types/#javascript for more details.target: 'esnext',
},
});
Basic Setup
Section titled “Basic Setup”Create a SwapKit client instance:
// src/swapKitClient.ts
import { function createSwapKit(config?: Parameters<typeof SwapKit>[0]): {
chainflip: {
supportedSwapkitProviders: ProviderName[];
} & {
swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
};
... 5 more ...;
near: {
...;
} & {
...;
};
} & {
...;
} & {
...;
}
createSwapKit } from '@swapkit/sdk';
export const const swapKitClient: {
chainflip: {
supportedSwapkitProviders: ProviderName[];
} & {
swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
};
... 5 more ...;
near: {
...;
} & {
...;
};
} & {
...;
} & {
...;
}
swapKitClient = function createSwapKit(config?: Parameters<typeof SwapKit>[0]): {
chainflip: {
supportedSwapkitProviders: ProviderName[];
} & {
swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
};
... 5 more ...;
near: {
...;
} & {
...;
};
} & {
...;
} & {
...;
}
createSwapKit();
React Component Example
Section titled “React Component Example”Here’s a basic example of using SwapKit in a React component:
// src/App.tsx
import { function useState<S>(initialState: S | (() => S)): [S, React.Dispatch<React.SetStateAction<S>>] (+1 overload)
Returns a stateful value, and a function to update it.useState, function useEffect(effect: React.EffectCallback, deps?: React.DependencyList): void
Accepts a function that contains imperative, possibly effectful code.useEffect } from 'react';
import { import swapKitClient
swapKitClient } from Cannot find module './swapKitClient' or its corresponding type declarations.'./swapKitClient';
import { enum Chain
Chain, enum WalletOption
WalletOption } from '@swapkit/sdk';
function function App(): React.JSX.Element
App() {
const [const isConnected: boolean
isConnected, const setIsConnected: React.Dispatch<React.SetStateAction<boolean>>
setIsConnected] = useState<boolean>(initialState: boolean | (() => boolean)): [boolean, React.Dispatch<React.SetStateAction<boolean>>] (+1 overload)
Returns a stateful value, and a function to update it.useState(false);
const [const address: string
address, const setAddress: React.Dispatch<React.SetStateAction<string>>
setAddress] = useState<string>(initialState: string | (() => string)): [string, React.Dispatch<React.SetStateAction<string>>] (+1 overload)
Returns a stateful value, and a function to update it.useState<string>('');
const const connectWallet: () => Promise<void>
connectWallet = async () => {
try {
await import swapKitClient
swapKitClient.connectEVMWallet([enum Chain
Chain.function (enum member) Chain.Ethereum = "ETH"
Ethereum], enum WalletOption
WalletOption.function (enum member) WalletOption.METAMASK = "METAMASK"
METAMASK);
const setIsConnected: (value: React.SetStateAction<boolean>) => void
setIsConnected(true);
const const ethAddress: any
ethAddress = await import swapKitClient
swapKitClient.getAddress(enum Chain
Chain.function (enum member) Chain.Ethereum = "ETH"
Ethereum);
const setAddress: (value: React.SetStateAction<string>) => void
setAddress(const ethAddress: any
ethAddress);
} catch (error) {
console.Console.error(message?: any, ...optionalParams: any[]): void (+3 overloads)
Prints to `stderr` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)).
```js
const code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
```
If formatting elements (e.g. `%d`) are not found in the first string then
[`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) is called on each argument and the
resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)
for more information.error('Failed to connect wallet:', error);
}
};
const const disconnectWallet: () => void
disconnectWallet = () => {
import swapKitClient
swapKitClient.disconnectWallet(enum Chain
Chain.function (enum member) Chain.Ethereum = "ETH"
Ethereum);
const setIsConnected: (value: React.SetStateAction<boolean>) => void
setIsConnected(false);
const setAddress: (value: React.SetStateAction<string>) => void
setAddress('');
};
return (
<'React' refers to a UMD global, but the current file is a module. Consider adding an import instead.div>
<'React' refers to a UMD global, but the current file is a module. Consider adding an import instead.h1>SwapKit + Vite</h1>
{!const isConnected: boolean
isConnected ? (
<'React' refers to a UMD global, but the current file is a module. Consider adding an import instead.button onClick={const connectWallet: () => Promise<void>
connectWallet}>Connect Wallet</button>
) : (
<'React' refers to a UMD global, but the current file is a module. Consider adding an import instead.div>
<'React' refers to a UMD global, but the current file is a module. Consider adding an import instead.p>Connected: {const address: string
address}</p>
<'React' refers to a UMD global, but the current file is a module. Consider adding an import instead.button onClick={const disconnectWallet: () => void
disconnectWallet}>Disconnect</button>
</div>
)}
</div>
);
}
export default function App(): React.JSX.Element
App;
Environment Variables
Section titled “Environment Variables”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:
import { function createSwapKit(config?: Parameters<typeof SwapKit>[0]): {
chainflip: {
supportedSwapkitProviders: ProviderName[];
} & {
swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
};
... 5 more ...;
near: {
...;
} & {
...;
};
} & {
...;
} & {
...;
}
createSwapKit, const SKConfig: {
getState: () => SwapKitConfigStore;
get: <T extends "wallets" | "apiKeys" | "apis" | "chains" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations">(key: T) => SwapKitConfigStore[T];
... 6 more ...;
setIntegrationConfig: <T extends keyof SKConfigIntegrations>(integration: T, config: SKConfigIntegrations[T]) => void;
}
SKConfig } from '@swapkit/sdk';
// Configure API keys
const SKConfig: {
getState: () => SwapKitConfigStore;
get: <T extends "wallets" | "apiKeys" | "apis" | "chains" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations">(key: T) => SwapKitConfigStore[T];
... 6 more ...;
setIntegrationConfig: <T extends keyof SKConfigIntegrations>(integration: T, config: SKConfigIntegrations[T]) => void;
}
SKConfig.setApiKey: <"swapKit">(key: "swapKit", apiKey: string) => void
setApiKey('swapKit', Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.import.meta.env.VITE_SWAPKIT_API_KEY);
const SKConfig: {
getState: () => SwapKitConfigStore;
get: <T extends "wallets" | "apiKeys" | "apis" | "chains" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations">(key: T) => SwapKitConfigStore[T];
... 6 more ...;
setIntegrationConfig: <T extends keyof SKConfigIntegrations>(integration: T, config: SKConfigIntegrations[T]) => void;
}
SKConfig.setApiKey: <"walletConnectProjectId">(key: "walletConnectProjectId", apiKey: string) => void
setApiKey('walletConnectProjectId', Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.import.meta.env.VITE_WALLETCONNECT_PROJECT_ID);
export const const swapKitClient: {
chainflip: {
supportedSwapkitProviders: ProviderName[];
} & {
swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
};
... 5 more ...;
near: {
...;
} & {
...;
};
} & {
...;
} & {
...;
}
swapKitClient = function createSwapKit(config?: Parameters<typeof SwapKit>[0]): {
chainflip: {
supportedSwapkitProviders: ProviderName[];
} & {
swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
};
... 5 more ...;
near: {
...;
} & {
...;
};
} & {
...;
} & {
...;
}
createSwapKit();
Common Issues
Section titled “Common Issues”WebAssembly Support
Section titled “WebAssembly Support”If you encounter WebAssembly-related errors, ensure you have the required plugins installed:
bun add -D vite-plugin-wasm vite-plugin-top-level-await
pnpm add -D vite-plugin-wasm vite-plugin-top-level-await
npm install -D vite-plugin-wasm vite-plugin-top-level-await
yarn add -D vite-plugin-wasm vite-plugin-top-level-await
Example Repository
Section titled “Example Repository”For a complete working example, check out the Vite playground in the SwapKit repository.