JavaScript Ethereum विकास के लिए कई शक्तिशाली लाइब्रेरीज़ प्रदान करता है, जिनमें web3.js और ethers.js सबसे लोकप्रिय विकल्प हैं।
मूल और सबसे व्यापक रूप से उपयोग किया जाने वाला Ethereum JavaScript API।
import Web3 from 'web3';
const web3 = new Web3('YOUR_ETHEREUM_NODE_URL');
// बैलेंस प्राप्त करें
const getBalance = async (address) => {
const balance = await web3.eth.getBalance(address);
const balanceInEth = web3.utils.fromWei(balance, 'ether');
return balanceInEth;
};
// लेनदेन भेजें
const sendTransaction = async (from, to, value) => {
const tx = {
from,
to,
value: web3.utils.toWei(value, 'ether'),
};
return await web3.eth.sendTransaction(tx);
};
आधुनिक, पूर्ण और संक्षिप्त लाइब्रेरी।
import { ethers } from 'ethers';
const provider = new ethers.JsonRpcProvider('YOUR_ETHEREUM_NODE_URL');
// बैलेंस प्राप्त करें
const getBalance = async (address) => {
const balance = await provider.getBalance(address);
return ethers.formatEther(balance);
};
// लेनदेन भेजें
const sendTransaction = async (wallet, to, value) => {
const tx = await wallet.sendTransaction({
to,
value: ethers.parseEther(value),
});
return await tx.wait();
};
दोनों लाइब्रेरीज़ उत्कृष्ट TypeScript समर्थन प्रदान करती हैं। TypeScript का उपयोग करते समय, आपको मिलता है:
import { BigNumber } from 'ethers';
interface TransactionData {
to: string;
value: BigNumber;
gasLimit?: BigNumber;
}
const createTransaction = async (data: TransactionData) => {
// आपका कार्यान्वयन
};
दोनों लाइब्रेरीज़ Node.js वातावरण में निर्बाध रूप से काम करती हैं:
// Node.js में Web3.js
const Web3 = require('web3');
const web3 = new Web3('YOUR_ETHEREUM_NODE_URL');
// Node.js में Ethers.js
const { ethers } = require('ethers');
const provider = new ethers.JsonRpcProvider('YOUR_ETHEREUM_NODE_URL');
ब्राउज़र वातावरण के लिए, आप webpack या vite जैसे बंडलर्स के साथ किसी भी लाइब्रेरी का उपयोग कर सकते हैं:
// ES मॉड्यूल का उपयोग करना
import { Web3 } from 'web3';
// या
import { ethers } from 'ethers';
// window.ethereum (MetaMask) का उपयोग करना
const provider = new ethers.BrowserProvider(window.ethereum);