Created
August 12, 2024 06:45
-
-
Save ardislu/7c1af0b0dd252bb915705cefe8bd2a66 to your computer and use it in GitHub Desktop.
Example of making a batch JSON-RPC request and concisely destructuring the response by (ab)using the JSON-RPC id as the variable name.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const rpc = 'https://ethereum.publicnode.com'; | |
const to = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48'; | |
const requests = { | |
name: '0x06fdde03', | |
symbol: '0x95d89b41', | |
decimals: '0x313ce567', | |
totalSupply: '0x18160ddd' | |
} | |
const payload = []; | |
for (const [id, data] of Object.entries(requests)) { | |
payload.push({ | |
jsonrpc: '2.0', | |
id, | |
method: 'eth_call', | |
params: [{ to, data }, 'safe'] | |
}); | |
} | |
const response = await fetch(rpc, { | |
method: 'POST', | |
headers: { 'Content-Type': 'application/json' }, | |
body: JSON.stringify(payload) | |
}).then(r => r.json()); | |
// These values still must be ABI decoded | |
const { name, symbol, decimals, totalSupply } = response.reduce((a, c) => ({ ...a, [c.id]: c.result }), {}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment