Skip to content

Instantly share code, notes, and snippets.

@rollendxavier
Created November 13, 2024 11:16
Show Gist options
  • Save rollendxavier/2f4cb6d18e8fd615fe4efa962a1f24b5 to your computer and use it in GitHub Desktop.
Save rollendxavier/2f4cb6d18e8fd615fe4efa962a1f24b5 to your computer and use it in GitHub Desktop.
Node.js program integrating Web3.js, the CoinGecko API
const https = require('https');
const Web3 = require('web3');
const axios = require('axios');
require('dotenv').config();
const fs = require('fs');
const express = require('express');
// Load environment variables
const COINGECKO_API_KEY = process.env.COINGECKO_API_KEY;
// Web3 setup using Ganache
const ganacheUrl = 'http://127.0.0.1:8545'; // Default Ganache CLI URL
const web3 = new Web3(new Web3.providers.HttpProvider(ganacheUrl));
async function getEthBalance(userAddress) {
return new Promise((resolve, reject) => {
web3.eth.getBalance(userAddress, (err, balance) => {
if (err) {
reject(err);
} else {
resolve(web3.utils.fromWei(balance, 'ether'));
}
});
});
}
// Load ERC20 ABI and your Smart Contract ABI
const erc20Abi = [
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
}
],
"name": "balanceOf",
"outputs": [
{
"name": "balance",
"type": "uint256"
}
],
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_to",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"name": "success",
"type": "bool"
}
],
"type": "function"
}
];
const myTokenAbi = JSON.parse(fs.readFileSync('./MyToken_abi.json'));
const myTokenAddress = '0x33e4D0517Ff8C174b90FEd77E413fE1aFC6207a8'; // Replace with your actual token contract address
const app = express();
app.use(express.json());
// Functions
async function newAccount() {
const account = web3.eth.accounts.create();
return {
privateKey: account.privateKey,
address: account.address,
};
}
async function getErc20Balance(contractAddress, userAddress) {
const checksumAddress = web3.utils.toChecksumAddress(userAddress);
console.log(`Checksum Address: ${checksumAddress}`);
const contract = new web3.eth.Contract(erc20Abi, contractAddress);
const balance = await contract.methods.balanceOf(checksumAddress).call();
return balance;
}
// Fetch market chart data from CoinGecko API
async function getMarketChart(days) {
const url = `https://api.coingecko.com/api/v3/coins/ethereum/market_chart?vs_currency=usd&days=${days}`;
const response = await axios.get(url, {
headers: {
Authorization: `Bearer ${COINGECKO_API_KEY}`,
}
});
if (response.status === 200) {
return response.data;
} else {
throw new Error('Failed to fetch market chart data from CoinGecko');
}
}
async function sendTransaction({ to, amount, privateKey }) {
const account = web3.eth.accounts.privateKeyToAccount(privateKey);
const nonce = await web3.eth.getTransactionCount(account.address);
const tx = {
to,
value: web3.utils.toWei(amount, 'ether'),
gas: 2000000,
gasPrice: web3.utils.toWei('20', 'gwei'), // Adjust gas price as needed
nonce,
chainId: 1337 // Ganache's default chain ID
};
const signedTx = await account.signTransaction(tx);
const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
return receipt.transactionHash;
}
async function interactWithSmartContract(userAddress) {
const contract = new web3.eth.Contract(myTokenAbi, myTokenAddress);
// Example interaction with the smart contract
const result = await contract.methods.totalSupply().call({ from: userAddress }); // Replace totalSupply with actual method
return result;
}
// Express routes
app.get('/balance/:contract_address', async (req, res) => {
try {
const contractAddress = req.params.contract_address;
const account = await newAccount();
const balance = await getErc20Balance(contractAddress, account.address);
res.json({ balance });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/eth_balance/:user_address', async (req, res) => {
try {
const userAddress = req.params.user_address;
const balance = await getEthBalance(userAddress);
res.json({ balance });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/market_chart/:days', async (req, res) => {
try {
const { days } = req.params;
const marketChart = await getMarketChart(days);
res.json(marketChart);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
// Self-invoking function for initial actions
(async () => {
try {
// Create a new account
const account = await newAccount();
console.log('New Account:', account);
// Get balance of an ERC20 token (example usage)
const erc20Address = myTokenAddress; // Use your deployed token address
const balance = await getErc20Balance(erc20Address, account.address);
console.log('ERC20 Token Balance:', balance);
// Get ETH balance
const ethBalance = await getEthBalance(account.address);
console.log('ETH Balance:', ethBalance);
// Get market chart data
const marketChart = await getMarketChart(30); // last 30 days
console.log('Market Chart Data:', marketChart);
// Interact with your smart contract
const contractResult = await interactWithSmartContract(account.address);
console.log('Smart Contract Result:', contractResult);
} catch (error) {
console.error('Error:', error);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment