yasar-connect-wallet-sdk
v1.5.0
Published
Universal crypto wallet connection library for Ethereum-based dApps
Maintainers
Readme
🔐 Yasar Connect Wallet SDK
A universal, easy-to-integrate cryptocurrency wallet connection library for Ethereum-based dApps. Works seamlessly across React, Vue, Angular, Vanilla JavaScript, Node.js, Laravel, and HTML.
✨ Features
- ✅ Auto Wallet Detection - Automatically detects installed wallets (MetaMask, Coinbase, Trust Wallet, etc.)
- ✅ Download Links - Shows download links for unavailable wallets
- ✅ Multi-Wallet Support - Connect to any Ethereum-compatible wallet
- ✅ Send Transactions - Send ETH with ease
- ✅ Token Transfers - Send ERC20 tokens
- ✅ Smart Contract Calls - Interact with any smart contract
- ✅ Balance Checking - Get wallet balance anytime
- ✅ Network Switching - Switch between different blockchain networks
- ✅ Event Listeners - React to wallet events (connect, disconnect, error)
- ✅ Mobile Friendly - Works on mobile devices with mobile wallets
- ✅ Zero Configuration - Works out of the box
- ✅ TypeScript Support - Full type definitions included
📦 Installation
npm install yasar-connect-wallet-sdk ethersOr with yarn:
yarn add yasar-connect-wallet-sdk ethers🚀 Quick Start
Vanilla JavaScript
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ethers/6.7.1/ethers.min.js"></script>
<script src="node_modules/yasar-connect-wallet-sdk/dist/index.umd.js"></script>
</head>
<body>
<button onclick="connectWallet()">Connect Wallet</button>
<script>
const wallet = new CryptoWallet();
async function connectWallet() {
const connected = await wallet.connectWallet('metamask');
console.log('Connected:', connected.address);
}
</script>
</body>
</html>React
import { useState, useEffect } from 'react';
import CryptoWallet from 'yasar-connect-wallet-sdk';
export function WalletConnector() {
const [wallet, setWallet] = useState(null);
const [wallets, setWallets] = useState([]);
const cryptoWallet = new CryptoWallet();
useEffect(() => {
detectWallets();
}, []);
const detectWallets = async () => {
const detected = await cryptoWallet.detectAvailableWallets();
setWallets(detected);
};
const handleConnect = async (walletType) => {
try {
const connected = await cryptoWallet.connectWallet(walletType);
setWallet(connected);
} catch (error) {
console.error('Connection failed:', error);
}
};
return (
<div>
{!wallet ? (
<div>
{wallets.map(w => (
<button key={w.id} onClick={() => handleConnect(w.id)}>
Connect {w.name}
</button>
))}
</div>
) : (
<div>
<p>Connected: {wallet.address}</p>
<button onClick={() => cryptoWallet.disconnectWallet()}>
Disconnect
</button>
</div>
)}
</div>
);
}Vue.js
<template>
<div class="wallet-container">
<button v-for="w in availableWallets" :key="w.id"
@click="connect(w.id)">
Connect {{ w.name }}
</button>
<div v-if="connected">
<p>Connected: {{ connected.address }}</p>
<button @click="sendTransaction">Send Transaction</button>
</div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import CryptoWallet from 'yasar-connect-wallet-sdk';
const wallet = new CryptoWallet();
const availableWallets = ref([]);
const connected = ref(null);
onMounted(async () => {
const detected = await wallet.detectAvailableWallets();
availableWallets.value = detected;
});
const connect = async (walletType) => {
const conn = await wallet.connectWallet(walletType);
connected.value = conn;
};
const sendTransaction = async () => {
const tx = await wallet.sendTransaction(
'0x742d35Cc6634C0532925a3b844Bc3e5bFC5cF4e8',
'0.1'
);
console.log('TX:', tx.hash);
};
</script>📖 API Documentation
Initialize CryptoWallet
const wallet = new CryptoWallet({
chainId: 1, // Default: 1 (Ethereum Mainnet)
rpcUrl: 'https://eth.public.rpc.thirdweb.com' // Default RPC endpoint
});Detect Available Wallets
const available = await wallet.detectAvailableWallets();
// Returns: [{ id: 'metamask', name: 'MetaMask', available: true }, ...]Get Download Links
const links = wallet.getWalletDownloadLinks();
// Returns wallet download links for unavailable walletsConnect to Wallet
const connected = await wallet.connectWallet('metamask');
// Returns: { address, chainId, type, provider, signer }Supported Wallets:
metamask- MetaMaskcoinbase- Coinbase Wallettrustwallet- Trust Walletwalletconnect- WalletConnectphantom- Phantom
Get Connected Wallet Info
const info = wallet.getConnectedWallet();
// Returns: { address, chainId, type }Get Balance
const balance = await wallet.getBalance('0x742d35Cc6634C0532925a3b844Bc3e5bFC5cF4e8');
// Returns: "1.5" (in ETH)Send ETH Transaction
const tx = await wallet.sendTransaction(
'0x742d35Cc6634C0532925a3b844Bc3e5bFC5cF4e8', // recipient
'0.5' // amount in ETH
);
// Returns: { hash, from, to, value, status }Send ERC20 Token
const tx = await wallet.sendToken(
'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // token address (USDC)
'0x742d35Cc6634C0532925a3b844Bc3e5bFC5cF4e8', // recipient
'100' // amount
);
// Returns: { hash, from, to, tokenAddress, amount, status }Call Smart Contract
const abi = [
'function swap(uint256 amount) returns (bool)',
'function balanceOf(address) returns (uint256)'
];
const result = await wallet.callContract(
'0x1111111254fb6c44bac0bed2854e76f90643097d', // contract address
abi, // contract ABI
'swap', // function name
['1000000000000000000'] // function arguments
);
// Returns: { hash, status }Get Gas Price
const gasData = await wallet.getGasPrice();
// Returns: { gasPrice, maxFeePerGas, maxPriorityFeePerGas }Switch Network
await wallet.switchNetwork(137); // Switch to Polygon
// Supported chains: 1, 11155111, 80001, 137, 56Get Transaction Receipt
const receipt = await wallet.getTransactionReceipt('0x...');
// Returns transaction receiptSign Message
const signature = await wallet.signMessage('Hello, Web3!');
// Returns: signatureDisconnect Wallet
await wallet.disconnectWallet();🎯 Event Listeners
// Listen to wallet connection
wallet.on('walletConnected', (data) => {
console.log('Wallet connected:', data);
});
// Listen to wallet disconnection
wallet.on('walletDisconnected', () => {
console.log('Wallet disconnected');
});
// Listen to network changes
wallet.on('networkSwitched', (data) => {
console.log('Network switched to:', data.chainId);
});
// Listen to errors
wallet.on('error', (error) => {
console.error('Error:', error);
});
// Remove listener
wallet.off('walletConnected', callbackFunction);🌐 Supported Networks
| Network | Chain ID | Symbol | |---------|----------|--------| | Ethereum Mainnet | 1 | ETH | | Sepolia Testnet | 11155111 | SEP | | Polygon Mumbai | 80001 | MATIC | | Polygon | 137 | MATIC | | BSC | 56 | BNB |
📱 Mobile Support
The SDK automatically detects mobile devices and shows appropriate wallet options:
- iOS: Phantom, MetaMask Mobile
- Android: MetaMask Mobile, Trust Wallet, Phantom
- WalletConnect: QR code scanning for any wallet
🔧 Configuration
const wallet = new CryptoWallet({
chainId: 1, // Default chain
rpcUrl: 'https://eth.public.rpc.thirdweb.com', // RPC endpoint
supportedChains: [1, 11155111, 80001, 137, 56], // Supported networks
infuraId: 'YOUR_INFURA_ID' // For WalletConnect
});🛠️ Node.js / Backend Example
const CryptoWallet = require('yasar-connect-wallet-sdk');
app.post('/api/verify-transaction', async (req, res) => {
const wallet = new CryptoWallet();
try {
const receipt = await wallet.getTransactionReceipt(req.body.txHash);
res.json({
status: receipt.status === 1 ? 'success' : 'failed',
blockNumber: receipt.blockNumber
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});🏗️ Build Formats
The package is available in multiple formats:
- UMD (
dist/index.umd.js) - Browser & CommonJS - ESM (
dist/index.esm.js) - ES Modules - CommonJS (
dist/index.js) - Node.js
Choose based on your environment:
<!-- Browser -->
<script src="dist/index.umd.js"></script>
<!-- ES Modules -->
<script type="module">
import CryptoWallet from './dist/index.esm.js';
</script>🐛 Troubleshooting
"No Ethereum provider found"
- Install MetaMask or another wallet extension
- Check if you're on a supported network
"Wallet not connected"
- Call
connectWallet()before using other methods - Check console for connection errors
Transaction fails
- Ensure sufficient gas
- Check wallet has enough balance
- Verify correct recipient address
Mobile wallet not detected
- Use WalletConnect for broader mobile support
- Check if wallet app is installed
📚 Examples
Full examples available in the examples/ folder:
react-example.jsx- React integrationvue-example.vue- Vue.js integrationvanilla-example.html- Vanilla JavaScriptnode-example.js- Node.js backend
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🔗 Links
- NPM: https://www.npmjs.com/package/yasar-connect-wallet-sdk
- GitHub: https://github.com/yourusername/yasar-connect-wallet-sdk
- Documentation: https://github.com/yourusername/yasar-connect-wallet-sdk/wiki
- Issues: https://github.com/yourusername/yasar-connect-wallet-sdk/issues
💡 Tips
- Always handle errors - Wallet connections can fail
- Use event listeners - React to wallet state changes
- Check balances - Before sending transactions
- Use testnet first - Test on Sepolia or Mumbai before mainnet
- Sign messages - Verify user ownership without transaction costs
🙏 Acknowledgments
Built with ❤️ for the Web3 community using:
📧 Support
For issues, questions, or feature requests:
- Open an issue on GitHub
- Email: [email protected]
Made for Web3 Developers by Yasar 🚀
