Transaction and Balance Monitoring Tools
1.1 T&B Monitoring Overview
1.2 Code for Monitoring Balances and Transactions
1.2.1 Monitoring Wallet Balance
const Web3 = require('web3');
const web3 = new Web3('wss://mainnet.infura.io/ws/v3/YOUR_INFURA_PROJECT_ID');
// Define the user's wallet address
const walletAddress = '0xYourEthereumAddressHere';
// Function to retrieve the current balance
async function checkBalance() {
try {
const balance = await web3.eth.getBalance(walletAddress);
console.log(`Wallet Balance: ${web3.utils.fromWei(balance, 'ether')} ETH`);
} catch (error) {
console.error("Error fetching balance:", error);
}
}
// Check balance at regular intervals (e.g., every minute)
setInterval(checkBalance, 60000);
1.2.2 Real-Time Balance Monitoring with WebSocket
web3.eth.subscribe('newBlockHeaders', (error, block) => {
if (error) console.error("Subscription error:", error);
else checkBalance();
});
1.2.3 Transaction Monitoring
const monitoredAddress = walletAddress;
// Function to monitor new transactions in each block
web3.eth.subscribe('pendingTransactions', async (error, txHash) => {
if (error) return console.error("Error:", error);
// Get transaction details
const tx = await web3.eth.getTransaction(txHash);
if (tx && (tx.to === monitoredAddress || tx.from === monitoredAddress)) {
console.log("Transaction detected:");
console.log(`From: ${tx.from}`);
console.log(`To: ${tx.to}`);
console.log(`Amount: ${web3.utils.fromWei(tx.value, 'ether')} ETH`);
console.log(`Tx Hash: ${tx.hash}`);
}
});
1.2.4 Multi-Asset Balance Monitoring (ERC-20 Tokens)
const tokenContractAddress = '0xTokenContractAddressHere';
const tokenABI = [
// Minimal ABI to get balance
{
"constant": true,
"inputs": [{ "name": "_owner", "type": "address" }],
"name": "balanceOf",
"outputs": [{ "name": "balance", "type": "uint256" }],
"type": "function"
}
];
// Create contract instance
const tokenContract = new web3.eth.Contract(tokenABI, tokenContractAddress);
// Function to check token balance
async function checkTokenBalance() {
try {
const tokenBalance = await tokenContract.methods.balanceOf(walletAddress).call();
console.log(`Token Balance: ${web3.utils.fromWei(tokenBalance, 'ether')} Tokens`);
} catch (error) {
console.error("Error fetching token balance:", error);
}
}
// Check token balance periodically
setInterval(checkTokenBalance, 60000);
1.3 API Integration
1.3.1 GET /wallets/{wallet_id}/balance
curl -X GET "https://api.capsurelabs.com/wallets/0xYourWalletAddress/balance" \
-H "Authorization: Bearer <token>"
1.3.2 GET /wallets/{wallet_id}/transactions
curl -X GET "https://api.capsurelabs.com/wallets/0xYourWalletAddress/transactions" \
-H "Authorization: Bearer <token>"
1.3.3 WebSocket /wallets/subscribe
{
"type": "subscribe",
"walletId": "0xYourWalletAddress"
}
PreviousDecentralized Identity Manager: Access Control and ManagementNextGame Asset Tracker: Monitoring Game Assets
Last updated