A secure and easy-to-use Web3 Provider SDK for DApps connecting to imToken Web.
- 🔄 Dual Mode Support: Automatically switches between popup and iframe communication modes
- 🔒 Secure & Reliable: Built-in origin verification, message source validation, and multiple security mechanisms
- 📱 EIP-1193 Compatible: Fully implements the EIP-1193 standard for seamless integration with mainstream DApp frameworks
- 🔗 Multi-Chain Support: Built-in multi-chain configuration with chain switching support
- ⚡ Read-Only RPC Support: Direct RPC node calls for read-only methods (eth_call, eth_estimateGas, etc.) without wallet interaction
- 💾 State Management: Automatically caches account and chain state to localStorage
- 📡 Event System: Complete event system (connect, chainChanged, accountsChanged, etc.)
- 🎯 TypeScript: Full type definitions for an excellent development experience
pnpm add @consenlabs/imtoken-connectOr using other package managers:
npm install @consenlabs/imtoken-connect
# or
yarn add @consenlabs/imtoken-connectUse ImTokenWebProvider for automatic environment adaptation:
import { ImTokenWebProvider } from "@consenlabs/imtoken-connect";
// Create Provider instance
const provider = new ImTokenWebProvider();
// Request wallet connection
const accounts = await provider.request({
method: "eth_requestAccounts"
});
console.log("Connected accounts:", accounts);
// Listen to events
provider.on("accountsChanged", (accounts) => {
console.log("Accounts changed:", accounts);
});
provider.on("chainChanged", (chainId) => {
console.log("Chain changed:", chainId);
});Automatic Behavior:
- ✅ Automatically detects runtime environment (iframe or main window)
- ✅ iframe environment: Uses iframe communication
- ✅ Main window environment: Uses popup communication
- ✅ Built-in parent window origin validation (only allows official imToken Web domains)
If your DApp will only run in an iframe, you can use the lightweight ImTokenWebIframeProvider:
import { ImTokenWebIframeProvider } from "@consenlabs/imtoken-connect";
const provider = new ImTokenWebIframeProvider();Important Notes:
⚠️ Must run in an iframe environment, otherwise it will throw an error⚠️ Must run in a trusted parent window (official imToken Web domain)
| Method | Description | Handling |
|---|---|---|
eth_requestAccounts |
Request wallet connection | Handled by wallet |
eth_accounts |
Get connected accounts | Local cache |
eth_chainId |
Get current chain ID | Local cache |
eth_sendTransaction |
Send transaction | Handled by wallet |
eth_signTypedData_v4 |
Sign (EIP-712) | Handled by wallet |
personal_sign |
Personal signature | Handled by wallet |
wallet_switchEthereumChain |
Switch chain | Handled locally |
These methods are called directly via RPC nodes using viem, without requiring wallet interaction:
| Method | Description |
|---|---|
eth_call |
Execute a call without creating a transaction |
eth_estimateGas |
Estimate gas for a transaction |
eth_gasPrice |
Get current gas price |
eth_getBalance |
Get account balance |
eth_getBlockByNumber |
Get block by number |
eth_getBlockByHash |
Get block by hash |
eth_getTransactionByHash |
Get transaction by hash |
eth_getTransactionReceipt |
Get transaction receipt |
eth_getTransactionCount |
Get account nonce |
eth_getCode |
Get contract code |
eth_getLogs |
Get event logs |
eth_blockNumber |
Get latest block number |
eth_getStorageAt |
Get storage value |
net_version |
Get network version |
Note: Read-only methods can be called before connecting to the wallet (
eth_requestAccounts).
src/
├── communication/ # Communication layer
│ ├── base.ts # Communicator base class
│ ├── iframe.ts # iframe communication implementation
│ ├── popup.ts # popup communication implementation
│ └── index.ts # Communication layer exports
├── provider/ # Provider layer
│ ├── base.ts # Provider base class
│ ├── common.ts # Full-featured Provider
│ ├── iframe.ts # iframe-specific Provider
│ └── index.ts # Provider exports
├── storage/ # Storage layer
│ └── index.ts # localStorage/sessionStorage wrapper
├── types.ts # Type definitions
├── constants.ts # Constants configuration
└── index.ts # SDK entry point
┌─────────────────────────────────────┐
│ Provider Layer │ ← EIP-1193 Interface
│ (BaseProvider, ImTokenWebProvider) │
├─────────────────────────────────────┤
│ Communication Layer │ ← Message Communication
│ (IframeCommunicator, PopupComm.) │
├─────────────────────────────────────┤
│ RPC Layer (viem) │ ← Read-Only RPC Calls
│ (PublicClient for each chain) │
├─────────────────────────────────────┤
│ Storage Layer │ ← State Caching
│ (localStorage, sessionStorage) │
└─────────────────────────────────────┘
provider.request({ method, params })
│
▼
┌───────────────┐
│ Read-Only RPC │ ─── Yes ──→ viem PublicClient ──→ RPC Node
│ Method? │
└───────┬───────┘
│ No
▼
┌───────────────┐
│ Wallet Method │ ──→ Communicator ──→ Wallet (Popup/Parent)
└───────────────┘
DApp (Main Window) ←→ Popup Window (Wallet)
│ │
└────── postMessage ─────┘
- Opens popup window on user action
- Communicates via
window.postMessage - Suitable for non-embedded DApps
imToken Web (Parent Window)
└── iframe (DApp) ←→ Parent Window (Wallet)
│ │
└──── postMessage ──┘
- DApp is embedded in imToken Web
- Communicates via
parent.postMessage
All postMessage communications verify the message origin:
// Built-in allowed origins list
const ALLOWED_ORIGINS = [
"https://web.token.im",
// ... more official domains
];In addition to origin verification, validates that the message source window is the expected window to prevent same-origin attacks.
ImTokenWebIframeProvider validates the runtime environment:
- ✅ Must run in an iframe
- ✅ Parent window must be a trusted origin
- ❌ Throws error immediately if conditions are not met
All postMessage calls use specific targetOrigin, never uses wildcard *.
Each request carries a unique UUID, and responses must match the request ID.
pnpm buildpnpm clean- Use ImTokenWebProvider: Suitable for most scenarios, automatically adapts to environment
- Use ImTokenWebIframeProvider: When you're certain the DApp will only run in iframe (more lightweight)
This is because you're using ImTokenWebIframeProvider but not in an iframe environment. Please use ImTokenWebProvider instead.