Skip to content

Instantly share code, notes, and snippets.

@ecoologic
Created November 7, 2025 00:45
Show Gist options
  • Save ecoologic/ca7044a988a1384d84f5dc639b20ea5d to your computer and use it in GitHub Desktop.
Save ecoologic/ca7044a988a1384d84f5dc639b20ea5d to your computer and use it in GitHub Desktop.
Alchemy blockchain connector
// index.js
process.loadEnvFile();
const { APP_ID, API_KEY, ALCHEMY_NETWORK = "eth-sepolia" } = process.env;
console.log(`Using APP_ID=${APP_ID}`);
class AlchemyConnector {
constructor({ apiKey, network }) {
this.httpUrl = `https://${network}.g.alchemy.com/v2/${apiKey}`;
this.id = 0;
}
async rpc(method, params = []) {
const body = { jsonrpc: "2.0", id: ++this.id, method, params };
const res = await fetch(this.httpUrl, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
let text;
try {
text = await res.text();
const data = JSON.parse(text);
if (data.error) throw new Error(data.error.message);
return data.result;
} catch (err) {
throw new Error(
`RPC error (${res.status}): ${err.message}\nBody: ${text?.slice(0, 200)}`
);
}
}
getBlockNumber() {
return this.rpc("eth_blockNumber");
}
getBalance(address, block = "latest") {
return this.rpc("eth_getBalance", [address, block]);
}
}
const alch = new AlchemyConnector({ apiKey: API_KEY, network: ALCHEMY_NETWORK });
(async () => {
try {
const blockHex = await alch.getBlockNumber();
console.log("Current block:", parseInt(blockHex, 16));
} catch (e) {
console.error(e.message);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment