Files
internship_node/day7/services/Web3Service.js
T
2025-07-15 16:18:19 +01:00

38 lines
1010 B
JavaScript

// services/Web3Service.js
const { Web3 } = require("web3");
const web3 = new Web3(process.env.ALCHEMY_API_URL);
module.exports = {
web3,
createWallet: () => {
return web3.eth.accounts.create();
},
signMessage: (privateKey, message) => {
return web3.eth.accounts.sign(message, privateKey);
},
getBalance: async (address) => {
const balanceWei = await web3.eth.getBalance(address);
return web3.utils.fromWei(balanceWei, "ether");
},
transfer: async (privateKey, to, amount) => {
const account = web3.eth.accounts.privateKeyToAccount(privateKey);
const from = account.address;
const nonce = await web3.eth.getTransactionCount(from, "latest");
const gasPrice = await web3.eth.getGasPrice();
const tx = {
from,
to,
value: web3.utils.toWei(amount, "ether"),
gas: 21000,
gasPrice,
nonce,
};
const signed = await account.signTransaction(tx);
return web3.eth.sendSignedTransaction(signed.rawTransaction);
},
};