To run this code:
-
Install Bun
-
Run the code:
bun --hot index.js
The
--hot
flag uses a watcher feature to restart the server when changes are made.
To run this code:
Install Bun
Run the code:
bun --hot index.js
The --hot
flag uses a watcher feature to restart the server when changes are made.
const PORT = 5555; | |
Bun.serve({ | |
port: PORT, | |
async fetch(request) { | |
// Parse the request URL to get the pathname | |
const urlObject = new URL(request.url); | |
const pathname = urlObject.pathname; | |
// Check if it's a GET request to the "/getBalance/" endpoint | |
if (request.method === "GET" && pathname.startsWith("/getBalance/")) { | |
try { | |
const CHAINSTACK_NODE_URL = Bun.env.CHAINSTACK_NODE_URL; | |
// Extract the address from the pathname | |
const address = pathname.split("/getBalance/")[1]; | |
// Validate Ethereum address format (basic validation) | |
if (!/^0x[a-fA-F0-9]{40}$/.test(address)) { | |
return new Response( | |
JSON.stringify({ | |
INVALID_ADDRESS_ERROR: "Invalid Ethereum address format", | |
}), | |
{ | |
status: 400, | |
headers: { "Content-Type": "application/json" }, | |
} | |
); | |
} | |
const response = await fetch(CHAINSTACK_NODE_URL, { | |
method: "POST", | |
headers: { | |
"accept": "application/json", | |
"content-type": "application/json", | |
}, | |
body: JSON.stringify({ | |
id: 1, | |
jsonrpc: "2.0", | |
method: "eth_getBalance", | |
params: [address, "latest"], | |
}), | |
}); | |
if (!response.ok) { | |
throw new Error("Error fetching balance"); | |
} | |
const data = await response.json(); | |
if (data.error) { | |
throw new Error( | |
data.error.message || "Error in Ethereum node response" | |
); | |
} | |
let decimalValue = parseInt(data.result.substring(2), 16); | |
let weiValue = BigInt(decimalValue); | |
let divisor = BigInt("1000000000000000000"); | |
let wholeEthers = weiValue / divisor; | |
let remainderWei = weiValue % divisor; | |
let remainderEther = remainderWei.toString().padStart(18, "0"); | |
let etherValueWithDecimals = `${wholeEthers}.${remainderEther}`; | |
return new Response( | |
JSON.stringify({ | |
address: address, | |
balance: etherValueWithDecimals, | |
unit: "Ether", | |
}), | |
{ | |
status: 200, | |
headers: { "Content-Type": "application/json" }, | |
} | |
); | |
} catch (error) { | |
return new Response(`Error: ${error.message}`, { status: 500 }); | |
} | |
} | |
// Default response for other requests | |
return new Response( | |
JSON.stringify({ | |
error: "Endpoint does not exist", | |
}), | |
{ | |
status: 404, // HTTP status code for "Not Found" | |
headers: { "Content-Type": "application/json" }, | |
} | |
); | |
}, | |
}); | |
console.log(`Bun server running on port ${PORT}...`); |