ByAUJay
Creating API for Web3 Dapps: REST, GraphQL, and JSON-RPC Compared
Concise summary: When diving into modern Web3 products, it's unlikely that you'll stick with just one API pattern. The best approach is to mix things up a bit: use JSON-RPC for your write operations and low-level reads, go with GraphQL for those complex query joins and time-travel reads, and rely on REST from indexers to pull in cross-chain, user-centric data. And hey, don't forget to keep an eye on the upcoming protocol changes for 2024-2025, like Dencun (EIP-4844) and partial history expiry (EIP-4444). Check out more details here: (eips.ethereum.org)
Why this matters now
Two Protocol Shifts That Changed API Design for Dapps
There are two major shifts in protocols that have significantly changed the way decentralized apps (dapps) need to approach their API design:
- Get ready, because the Ethereum Dencun upgrade is set to hit the mainnet on March 13, 2024! This upgrade is bringing some exciting features like blob-carrying transactions, thanks to EIP-4844. You'll see new fields pop up in the block header, such as blob_gas_used and excess_blob_gas, plus a brand-new fee market just for “blob gas.” The best part? You can still use the same node APIs you already know to interact with these new fields. Just make sure you know where to find them. For more details, dive in here.
- So, let's chat about partial history expiry under EIP‑4444. This is expected to kick in across clients in 2025. What it means is that many nodes will stop keeping older block bodies and receipts. This shift is going to affect how we do long-range log scans and historic analytics, which could lead more teams to rely on indexers and subgraphs to get the data they need. For more details, check it out here.
Decision-makers should think of API selection as more of an architectural choice instead of just picking libraries.
TL;DR recommendations
- If you're looking to capture that classic node vibe, definitely opt for JSON‑RPC. It’s perfect for handling writes, mempool subscriptions, or anything specific to a chain--like Arbitrum's arbtrace_* methods. You can dive deeper here.
- Go with GraphQL if you want to easily stitch together block, transaction, receipt, and log data. It's also perfect for those time-travel queries on specific blocks--pretty cool, right? Check out more details here.
- If you're looking for sleek, cross-chain endpoints that zero in on wallets--think balances, NFTs, and prices--stick with REST from indexers. You'll appreciate the service level agreements (SLAs) and the reduced number of queries to pull everything together. For more info, check it out here.
Get everything unified under a single backend that handles authentication, caching, replay protection, and rate limits for you.
JSON-RPC: the canonical node interface
JSON-RPC, as described in EIP-1474, serves as the go-to communication protocol for Ethereum and EVM Layer 2 nodes. It supports various transport options like HTTP, WebSocket, and IPC, allowing for seamless interaction. Plus, it comes packed with super useful read/write methods such as eth_call, eth_sendRawTransaction, eth_getLogs, eth_feeHistory, and a whole lot more. If you're interested in digging into this further, feel free to explore it here.
What’s New and Important in 2024-2025
Check out these major trends and shifts we can expect to see in the next couple of years:
Economic Outlook
- Global Economic Growth: There's quite a bit of excitement surrounding the anticipated growth in emerging markets. Countries such as India and Brazil are gearing up to make some significant strides.
- Interest Rates: It's important to stay tuned to interest rates. Central banks are expected to tweak them, which will have a ripple effect on everything from mortgages to business loans.
Technology Trends
- AI Advancements: We’re really getting into the nitty-gritty of artificial intelligence. Get ready for AI to become a bigger part of our everyday lives -- think smart assistants and exciting breakthroughs in healthcare.
- Cybersecurity: As technology keeps moving forward, cyber threats are stepping up their game, too. We can expect a stronger emphasis on cybersecurity strategies for both businesses and individuals.
Environmental Initiatives
- Sustainability Efforts: More and more companies are getting on board with sustainability, striving for greener practices and working to cut down their carbon footprints.
- Renewable Energy: We’re likely to see a boost in investments for solar, wind, and other renewable energy sources. This change could really shake up the energy game.
Social Changes
- Workplace Dynamics: Remote and hybrid work models are definitely sticking around, but companies are trying to find the best ways to keep their teams engaged and feeling connected.
- Mental Health Awareness: There’s a lot more chatter about mental health these days, and businesses are stepping up to offer better support for their staff.
Healthcare Advances
- Telemedicine: The trend of remote healthcare is here to stay, giving patients the convenience of accessing care right from their homes.
- Personalized Medicine: Thanks to breakthroughs in genetic research, we're looking at treatments that are more customized to fit individual needs, potentially leading to better health outcomes.
Political Landscape
- Policy Changes: Stay tuned for any shifts in political policies that could impact different sectors, whether it's climate change initiatives or healthcare reforms.
- International Relations: Global politics will keep playing a big role in trade and economics, so make sure to keep your finger on the pulse of key international events.
Here are a few highlights of what we can expect in 2024-2025. It looks like it's going to be an exciting time, with a lot going on across different areas!
- Dencun’s EIP‑4844 brings some neat updates to block headers with
blob_gas_usedandexcess_blob_gas. You can easily check these out using your usual block retrieval methods. And hey, if you're diving into rollups, don't forget to keep an eye on those blob fee dynamics! More about it here: (eips.ethereum.org). - Many providers put the brakes on eth_getLogs range for each request, so it's a good idea to assume you'll need to paginate. For example, Alchemy sets different limits based on your plan and the size of the response, and they recommend using filters and chunking to make things easier. Chainstack has a similar tip, suggesting you stick to conservative ranges depending on the network. So, plan your log scanners accordingly! Learn more at (alchemy.com).
- Some clients and providers back eth_getBlockReceipts, which lets you grab all receipts in a block super efficiently--definitely a cheaper alternative than calling N× eth_getTransactionReceipt. Just a friendly reminder to check if it’s available for your client; Geth ≥1.13 and Erigon do offer it. Get the full scoop here: (docs.chainstack.com).
- If you’re looking for live updates, WebSocket subscriptions like eth_subscribe (newHeads, logs, newPendingTransactions) are the way to go! Just keep in mind these are WS-only, so be prepared to handle reorgs and any dropped connections. Find out more at (besu.hyperledger.org).
- The tags "safe" and "finalized" are becoming pretty well-known for default block parameters. Use these when you're dealing with consistency-sensitive reads (like balances and nonces) to avoid any reorg surprises. Just a little tip: some chains, like Base, don’t support these tags. Check it out: (ethereum.org).
- With access lists (EIP‑2930) and eth_createAccessList, you can cut down on gas costs and make estimates way more reliable for those tricky transactions. Want to learn more? Check it out here: (eips.ethereum.org).
Security and Hygiene:
Key Points for Keeping Things Safe and Clean
When it comes to keeping your space safe and tidy, here are some essential points you’ll want to keep in mind:
- Personal Hygiene: Make it a habit to wash your hands often, especially before meals and after using the bathroom. It's a straightforward but super effective way to keep yourself healthy!
- Workspace Cleanliness: Keep your space neat and tidy! Grab some disinfectant wipes and give your surfaces a quick wipe-down to fend off those pesky germs. And remember to declutter now and then--it's amazing how much a clean workspace can boost your mood!
- Data Security: Your online safety really matters! Make sure you’re using strong, unique passwords for all your accounts and switch them up every once in a while. Whenever you can, turn on two-factor authentication--it's a great way to boost your protection.
- Food Safety: When you're getting ready to whip up a meal, make sure all your utensils and surfaces are nice and clean. Don’t forget to pop those perishable items into the fridge right away to keep them fresh and prevent spoilage!
- Emergency Procedures: Stay alert to your surroundings and familiarize yourself with the safety protocols, whether you’re at work or out in public. Being prepared is always a smart move!
With these tips in mind, you can make your surroundings safer and healthier for yourself and everyone else nearby.
- Make sure to keep those
debug_*andtrace_*endpoints away from public networks. It's super important to lock them down with IP allowlists or mTLS. Some L2s provide their own trace namespaces specific to their chains (like Arbitrum’sarbtrace_*). Consider these as if they’re admin APIs. (chainnodes.org) - Steer clear of sending node credentials to browsers. If you need public access, it's best to use wallet providers like EIP‑1193 or just set up a straightforward proxy that keeps your secrets safe. For anything involving writing data or accessing sensitive information, rely on server-side solutions that use API secrets, JWTs, and allowlists. Check out more about it on (eips.ethereum.org).
Performance Tactics:
When you're looking to level up your game, having the right strategies is key. Here’s a quick rundown of some solid performance tactics you might want to try out:
1. Set Clear Goals
Setting clear and attainable goals can really help you find your way. Just remember to make them SMART - that means they should be Specific, Measurable, Achievable, Relevant, and Time-bound.
2. Monitor Your Progress
Tracking your progress is super important! Try using tools or apps that let you measure your performance over time. This way, you can easily spot what’s working and what might need a little adjustment.
3. Stay Focused
Distractions are all around us, but if you tackle them head-on, you can really boost your productivity. Consider finding a quiet spot to work or giving the Pomodoro Technique a shot. It’s a great way to amp up your focus!
4. Practice Regularly
Regular practice isn’t just for musicians; it’s for everyone! Going over things repeatedly really helps to nail down skills and boosts your confidence, too. So, make it a point to carve out some time to practice what you've picked up.
5. Seek Feedback
Feedback is like a treasure chest just waiting to be unlocked for improvement. So, don’t hold back--reach out to your peers or mentors for some constructive criticism. It’s a fantastic way to gain new perspectives on how to boost your performance.
Resources to Check Out
6. Stay Healthy
Your performance isn't just about how skilled you are; your physical and mental health are super important too! So, don’t forget to eat well, stay hydrated, and catch enough Z's. Keeping a balanced diet and getting a solid night’s sleep can really change the game for you.
7. Visualize Success
Take a moment to really picture what success means to you. Using visualization techniques can be a game-changer, helping you get mentally ready and boosting your confidence when you're about to face tough situations.
Conclusion
Using these performance tactics can seriously boost your skills. Just keep in mind that it takes time and consistent effort, so there’s no need to hurry through it. Stick with it, and you’ll see yourself getting better!
- If you're juggling a bunch of reads, it's a smart move to use batch JSON-RPC calls for N independent reads. Just keep an eye on your batch size and payload--aim for around 20 to 25 calls and try to stay under 1 MB. This way, you can avoid those pesky DOS issues and stay within the limits set by your provider. Oh, and don’t forget to use HTTP/2 along with keep-alive to keep things running smoothly. (json-rpc.dev)
- When you’re diving into historic reads that are more than a year old, don’t just assume the node will have all the receipts or bodies--thanks to EIP-4444, you might find yourself out of luck. Instead, think about using an archive or an indexer, or even a subgraph to grab what you need. (blog.ethereum.org)
Example: Read Blob Fee Context with EIP‑4844
To really get a grip on blob fee context with EIP‑4844, it helps to know a bit about its structure. EIP‑4844 rolls out the idea of "blobs," which are sizable bits of data designed to boost scalability in Ethereum. When you're diving into the blob fee context, what you're doing is tapping into these blobs to pull up the fee information.
How to Read Blob Fee Context
- Get the Blob Data
You can grab the blob data using the various Ethereum APIs. Just make a request to pull up the blob info that’s tied to your transaction.{ "blobID": "your_blob_id" } - Check the Fee Structure
After you’ve got the blob data, it’s time to dive into the fee structure. Keep in mind that blob fees can change depending on things like the size of the blob and the current state of the network. - Assess the Impact
Once you have the blob fee info, think about how it affects your choices. Are the fees fair? Do you need to tweak your transaction to make it more cost-effective?
Key Takeaways
- EIP‑4844 focuses on boosting scalability using blobs.
- Grasping how blob fees work can really help you take control of your transactions.
- Don't forget to stay updated on network conditions, since fees can change often.
Next time you’re handling blobs in Ethereum, don’t forget to keep an eye on those fees! They’re super important for making everything run without a hitch.
- Pick a block and take a look at the
blob_gas_usedandexcess_blob_gasusingeth_getBlockByNumber. Use this information to tweak your L2 posting cost model. You can find more details about these fields in the spec, and they’ll pop up in the client responses. If you need more info, check out EIP-4844.
GraphQL: precise, composable reads (two flavors)
In the Web3 world, you'll encounter two main flavors of GraphQL:
- Client GraphQL (EIP‑1767): Both Geth and Besu have read-only GraphQL endpoints that can really help reduce overfetching for common queries - like asking for a block and all its receipts. Just a quick note, though - Besu’s GraphQL is HTTP-only, so if you want to use subscriptions, you’ll have to go with JSON-RPC. The specific flags you can turn on will vary depending on which client you're using. For more details, check it out here: (eips.ethereum.org)
2) The Graph Subgraphs
So, The Graph subgraphs are like an upgraded version of GraphQL. They let you handle indexed data that you can set up yourself. You’ll find some pretty neat features here, like filtering, ordering, pagination, and even time-travel queries--yep, you can pull data based on a specific block number or hash! This makes it perfect for analytics, app feeds, and exploring historical data. Want to know more? Check it out here.
What’s New/Important:
- Feature Updates: We’ve introduced some awesome new features to make your experience even better. Take a look and share your thoughts with us!
- Bug Fixes: Our awesome team has been hard at work squashing those annoying bugs to make sure everything runs like a well-oiled machine. We really appreciate your feedback--it helps us keep everything in top-notch condition!
- Upcoming Events: Hey there! You definitely don’t want to miss our upcoming events! We’ve got some really exciting sessions coming up that you’ll love. Be sure to mark your calendars!
- Community Spotlight: A big shoutout to our awesome community members! We love highlighting your work, so if you’ve got something cool to share, don’t hesitate to get in touch!
For all the latest updates and more info, check out our blog and don’t forget to follow us on our social media channels. We’re always here to keep you informed!
- Thanks to Substreams-powered subgraphs, indexing and backfills just got a major upgrade. Teams can now sync datasets that used to take weeks in just a couple of hours. The Graph is seeing some jaw-dropping speed improvements--like 70× or even more for complex subgraphs (like Uniswap v3!). They've really hit the mark with production-grade streaming using Firehose. (thegraph.com)
- Have you ever wished you could easily query a specific state at block N across different chains? Time-travel GraphQL queries are here to help! They come with clear documentation on reorg semantics, so just remember to focus on finalized or older blocks to get the most reliable results. (thegraph.com)
When to Pick GraphQL:
Picking the right tech for your project can be tough. Here’s when it makes sense to go with GraphQL:
1. Complex Data Requirements
If your app has to gather data from different sources or deals with a complicated data structure, GraphQL is a game-changer for querying exactly what you need. Say goodbye to juggling multiple endpoints!
2. Flexible Queries
With GraphQL, clients get to choose exactly what data they need. This level of flexibility is ideal for apps that need to evolve or shift frequently. You won’t be stuck waiting around for backend updates to access new data.
3. Rapid Development
If you're navigating a fast-paced development scene, GraphQL can really give you a boost. With the power to pull all the data you need in one go, your frontend and backend teams can operate more independently and efficiently.
4. Bandwidth Constraints
GraphQL is a great way to cut down on the data traveling over the network. Clients can just grab the data they actually need, which is super handy for mobile apps or places where connectivity isn't so reliable.
5. Versioning Challenges
When it comes to handling API versions, things can get a bit complicated. That’s where GraphQL shines--it provides a more flexible option. Rather than having to roll out new versions of your API, you can simply add new fields or types. This approach allows your API to grow and change over time while keeping your existing clients happy and intact.
6. Strong Typing
If your team really values type safety, you’re in for a treat! GraphQL comes equipped with a robust type system that helps you catch errors early on in development.
7. Schema Documentation
Thanks to its introspective nature, GraphQL APIs pretty much document themselves. This means developers can easily figure out what data they can access and how to use it. It's a real game-changer for bringing new team members up to speed!
8. Tooling and Community
GraphQL boasts a strong ecosystem and a friendly community. Thanks to a variety of tools, libraries, and resources out there, jumping in and tackling common issues has never been simpler.
Conclusion
If any of these points hit home for your project, it could be the perfect time to try out GraphQL! It’s a robust technology that can simplify your development process and really enhance your users’ experience.
- You’re looking to link various blocks, transactions, logs, and accounts without drowning in a sea of RPC calls.
- Reliable historical snapshots are a must (like block-scoped reads), plus you want some cool features for filtering and sorting.
- You need an API contract that frontend teams can collaborate on and build upon as they go.
Limitations:
- Data Accuracy: We aim to keep our data as accurate as possible, but just a heads up--it might not always be completely up-to-date or free of errors.
- Scope of Information: The info we provide might not touch on every single scenario, so it’s smart to do a little extra digging if you need to.
- Context Dependency: Some insights may hit differently depending on your specific context or situation.
- User Interpretation: People can interpret the same information in different ways, which can lead to a variety of conclusions or actions.
Don’t hesitate to dive in and explore further! And if you’ve got any questions, just ask!
- The Node GraphQL is read-only, so you can't send mutations (like transactions) through it--those still use JSON-RPC. Just a little heads up, Besu only supports HTTP for its implementation. If you want to dive deeper, check it out here.
Example: “give us a ring, and we’ll pull all the paperwork”
- Using Node GraphQL, you can grab all the transaction receipts for a block with a single query. This is way easier than having to make several JSON-RPC calls, especially if you can't use eth_getBlockReceipts. (eips.ethereum.org)
REST from indexers: product‑level, cross‑chain data fast
Indexers like Moralis, SimpleHash, and a handful of others offer REST APIs that give you access to a ton of data--think wallet balances, NFT portfolios, token prices, holder info, transfers, approvals, and so much more. They also typically support over 30 different chains! It’s honestly the easiest way to get user-friendly features up and running, saving you the trouble of building your own indexer from scratch. For all the details, take a look here: docs.moralis.com.
Concrete Capabilities:
Concrete is hands down one of the most popular construction materials out there, and it’s got some pretty amazing qualities that make it a top pick for builders and engineers. Let’s dive into what makes concrete such a standout choice:
- Durability: Concrete structures are built to last--seriously, they can handle all sorts of weather and still look good years down the line. It’s a solid investment for the future.
- Versatility: Whether you’re designing a towering skyscraper, a robust bridge, or just a simple driveway, concrete has this amazing ability to take on all kinds of shapes and forms.
- Fire Resistance: One major perk of concrete? It doesn’t burn like wood does, which makes it a safer option in case of a fire.
- Energy Efficiency: Concrete can actually help keep buildings at a comfortable temperature, meaning you might save some bucks on energy bills down the road.
- Low Maintenance: Once you’ve got your concrete in place, it pretty much takes care of itself. This is a big win for anyone looking to stick to a budget.
- Sustainability: With the right methods, concrete can be produced in an eco-friendly way, and guess what? It can often be recycled after its first life is over.
These features really show why concrete is such a popular pick in the construction world. Whether you're tackling a big project or just sprucing up your home, concrete often proves to be the go-to option.
- Looking to check your wallet balances, including both native and ERC‑20 tokens? You can score prices and even see historical snapshots by block all at once. Take a peek here.
- Need to break down NFT ownership for token-gates? No worries! You can find all the info you need here.
- Want to amp up your activity feeds? You can pull transfers, spice up your labels, and decode method signatures, all in one spot. Check it out here for the scoop!
Tradeoffs:
When you're faced with decisions, it often feels like you're juggling a bunch of different options. Here are some important trade-offs to keep in mind:
Cost vs. Quality
- Cost: Sure, going for the cheaper option can help you save some cash right away.
- Quality: Just keep in mind that if you choose something that's lower quality, you might find yourself shelling out more later when things break or don’t quite do the job.
Time vs. Effort
- Time: Sure, speeding through a task can help you check things off your list in a flash.
- Effort: But when you invest a little more effort, you often end up with much better results, even if it takes a tad longer.
Short-term vs. Long-term
- Short-term: It's super tempting to chase quick wins.
- Long-term: But putting your money into something with future potential could really pay off later on.
Flexibility vs. Structure
- Flexibility: Staying flexible lets you roll with the punches and change things up as needed.
- Structure: On the other hand, a good structure keeps everything organized and on track.
Individual vs. Team Goals
- Individual: There are times when you might focus on your own goals and achievements.
- Team: However, teams usually accomplish much more when everyone joins forces and works towards shared objectives.
It's really about discovering the sweet spot that suits you best!
- You're cool with vendor limits and pagination models.
- Just a quick note: you might overlook some specific details or the newest opcodes until the provider pushes out updates.
- If you need things to be super consistent or want to keep tabs for audits, feel free to use your nodes or subgraphs whenever you need!
Emerging patterns we deploy for clients
At 7Block Labs, we're raising the bar for dapps that are geared up for 2025:
- Writes and low-level reads via JSON-RPC:
- When you're sending out signed transactions, remember to apply the EIP-1559 fee structure! It’s a good idea to check
eth_feeHistoryandeth_maxPriorityFeePerGasfor setting up your envelopes. If your transactions are a bit more complicated, don’t forget to precompute access lists usingeth_createAccessList. (eips.ethereum.org) - To keep in the loop, use WebSockets to subscribe for new heads and logs. Make sure you've got some reconnection and reorganization handling covered--like buffering the last 12 blocks and sorting things out during reorgs. (besu.hyperledger.org)
- For those log backfills, break up those queries based on the ranges your provider suggests and watch the response size like a hawk; don’t forget to deduplicate using (blockHash, logIndex). (docs.chainstack.com)
- When you're sending out signed transactions, remember to apply the EIP-1559 fee structure! It’s a good idea to check
- Read models using GraphQL:
- Set up subgraphs for your domain entities and take advantage of time-travel reads with (block: { number }) to keep those UIs and backtests running smoothly. If you’re dealing with bulky protocols, consider diving into Substreams to trim down sync times from days to just a few hours. Check it out here: (thegraph.com)
- User-centric features through REST indexers:
- Make a single call to pull in wallet portfolios, approvals, entities/labels, and net worth all at once; plus, be sure to cache like a pro at the edge. (moralis.com)
1) Safe JSON-RPC Log Backfill
When you’re working on JSON-RPC log backfill, keeping things safe is a big deal. Here are some important tips to remember:
- Data Integrity: It's super important to ensure that the data you're backfilling stays consistent. You definitely don’t want any mismatches between the old and new logs.
- Error Handling: Make sure to set up strong error handling so you can catch any hiccups that might come your way. This’ll help you tackle problems before they blow up.
- Batch Processing: Think about handling your logs in batches. This approach can lighten the strain on your system and make things a lot easier to keep track of.
- Backup: Make sure to keep a backup of your original logs before diving into any backfilling. If things go awry, you'll be glad you did!
- Testing: Before you officially launch, make sure to test your backfill process in a safe, controlled setting. It’s a great way to spot any hiccups before they become issues.
If you keep these tips in mind, you can really simplify and secure your JSON-RPC log backfill process!
- If your chain has “safe” block tags, go ahead and use them for consistency. If it doesn’t, try to lag your toBlock by about 2 blocks to keep things in check.
- Don’t forget about the page logs per provider limits--these usually range from 2,000 to 10,000 blocks. To keep your payloads easy to handle, make sure to filter by topics and addresses. For more info, check out (ethereum.org).
2) Read Blob Gas Context Post-Dencun
Blob Gas Context After Dencun
Hey there! Let’s jump into the blob gas situation after Dencun. It's been buzzing in conversations lately, and honestly, it’s a pretty interesting topic.
What’s Blob Gas?
Blob gas is basically a unique kind of gas that’s perfect for keeping data that doesn’t really slot into the typical structures. Picture it as a storage area for all those fuzzy bits of data that don’t have a specific place to go.
Why It Matters
Since Dencun, there's been a noticeable change in how we talk about blob gas. It's now a key player when it comes to dealing with huge amounts of unstructured data. With data generation booming on so many platforms, companies are realizing they have to change gears and discover smarter ways to handle their information.
Key Changes Post-Dencun
Here are a few key things to remember:
- Improved Efficiency: Ever since the Dencun update, we've seen a solid improvement in how blob gas handles data. It’s faster and more efficient now, which is a game changer for developers when it comes to storing and fetching information.
- Seamless Integration: The latest updates really enhance how blob gas fits with current platforms. This means teams can now smoothly add it to their workflows without a ton of fuss.
- Cost-Effectiveness: One of the major benefits is that blob gas has become more budget-friendly. Companies are discovering they can cut costs while still handling large datasets effectively.
Conclusion
To wrap things up, blob gas is really making waves after Dencun. It's become more efficient, easier to integrate, and more cost-effective, so it's definitely something to watch. If you're curious and want to dive deeper, you can find all the details in the documentation here.
- Check out a recent block:
- Use
eth_getBlockByNumberto take a look atblob_gas_usedandexcess_blob_gasfor your analytics and rollup cost dashboards. If you find thatexcess_blob_gasis regularly on the higher side, consider setting up an alert--this could mean that blob base fees are creeping up. (eips.ethereum.org)
- Use
3) Get All Receipts in a Block Efficiently
If you're looking to snag all the receipts from a block without breaking a sweat, here's how you can do it smoothly.
First, you’ll want to use the getBlockReceipts method. This handy function helps you fetch receipts all at once, making the process super efficient. Here’s a quick breakdown of how it works:
Basic Steps:
- Identify the Block: You’ll need the block number or hash. It's like the key to the treasure chest!
- Call the Method: Use the method to get the receipts. Here’s a sample code snippet to show you how it’s done:
const blockNumber = '0x1b4'; // Example block number const receipts = await getBlockReceipts(blockNumber); - Work with the Receipts: Once you have them, you can loop through the receipts and do some cool stuff, like analyze transactions or confirm events.
Why This Matters:
- Efficiency: Instead of fetching each receipt one by one, which can be a drag, getting them in a batch saves you time and resources.
- Simplicity: It streamlines your code and makes it easier to manage the data you’re working with.
Check out the documentation for more details and examples to get the most out of this method! Happy coding!
- If your client or provider supports this feature:
- Go ahead and use
eth_getBlockReceipts "0x…block"and loop through the received receipts to spot any contract deployments (wherereceipt.contractAddressisn’t null). You can dive deeper into the details in the Chainstack docs.
- Go ahead and use
4) Node GraphQL: Block with Nested Receipts (One Round-Trip)
In this section, we’re going to explore how to use Node.js with GraphQL to manage blocks that have nested receipts, all in a single round-trip. This method not only simplifies your queries but also boosts the efficiency of data retrieval.
Setting Up
Alright, let’s get your environment set up! Here’s what you’ll need:
- Make sure you've got Node.js up and running on your machine.
- You'll need a package manager, like npm or yarn.
- It's also good to have a GraphQL server ready to go, maybe with something like Apollo Server.
npm install apollo-server graphql
Writing the Schema
Setting Up Our GraphQL Schema
Alright, let's dive into setting up our GraphQL schema! This is where we can create the structure for our queries and outline how blocks and receipts relate to each other. Here's a straightforward example:
type Receipt {
id: ID!
amount: Float!
date: String!
}
type Block {
id: ID!
receipts: [Receipt]!
}
type Query {
block(id: ID!): Block
}
Using this schema, we can grab a block and all its nested receipts.
Implementing the Resolver
Next up, we’re going to set up a resolver to take care of our block queries. This is where the fun begins:
const { ApolloServer, gql } = require('apollo-server');
// Sample data
const blocks = [
{
id: '1',
receipts: [
{ id: '1', amount: 100.0, date: '2023-01-01' },
{ id: '2', amount: 150.0, date: '2023-01-02' },
]
}
];
const typeDefs = gql`
type Receipt {
id: ID!
amount: Float!
date: String!
}
type Block {
id: ID!
receipts: [Receipt]!
}
type Query {
block(id: ID!): Block
}
`;
const resolvers = {
Query: {
block: (_, { id }) => blocks.find(block => block.id === id),
},
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
Making a Query
To grab a block along with its related receipts, you can run a query like this:
query {
block(id: "1") {
id
receipts {
id
amount
date
}
}
}
Running this query will fetch the block and its nested receipts all in one go, which is pretty efficient!
Conclusion
And that’s a wrap! With just a handful of code, you’ve built a GraphQL API that smoothly fetches blocks along with their nested receipts. This one-round-trip method isn’t just about saving time; it also makes your data fetching game way easier. Enjoy coding!
- Want to save on disk reads? You can query a specific block and grab only the fields you really need instead of firing off multiple RPC calls. This handy feature is compatible with both Geth and Besu. Take a look here: (eips.ethereum.org)
5) Subgraph Time-Travel Read
When you start exploring subgraphs, one of the coolest features you'll come across is the time-travel reading ability. This lets you pull up historical data from your subgraph, which is really useful for checking out how things have evolved over time.
How It Works
With time-travel reads, you can dive into the past state of your subgraph by simply using a specific block number or timestamp. This lets you grab data just like it was back then, giving you a cool snapshot of what was happening on the blockchain at that moment.
Here’s a quick guide on how to add this to your queries:
{
myEntity(block: { number: YOUR_BLOCK_NUMBER }) {
id
value
}
}
In the example above, simply swap out YOUR_BLOCK_NUMBER with the block number you're curious about, and you'll see what the state of myEntity was like at that time.
Why It’s Useful
- Data Analysis: When it comes to spotting trends or shifts over time, this feature is a total game changer. You can quickly line up past data with what's happening now to see how things stack up.
- Debugging: Running into a snag? Those time-travel reads can show you what the data looked like at specific moments, which is super helpful for figuring out where things went off track.
- Historical Insights: Curious about how certain transactions or events have changed over time? This tool provides you with a detailed historical backdrop to help you make sense of it all.
Final Thoughts
Time-travel reads really boost the power and flexibility of subgraphs. As you dive into different applications, be sure to leverage this feature to gain deeper insights and enhance your data analysis!
- You can easily query your subgraph using a particular block number or hash to get the “state as of” without getting distracted by any reorgs. This is super useful for things like historical portfolio pages. Take a look here: (thegraph.com)
6) REST: Wallet Portfolio in One Call
When you want to get the full scoop on your wallet all at once, the REST API has got your back. You can pull your entire portfolio with just one request, giving you a fast look at how your wallet is doing without the hassle of searching through everything.
How it Works:
Just check out the endpoint for your wallet's portfolio, and bam! You’ll have all the info you need at your fingertips--like your balances, transaction history, and even a few insights about your investments--all neatly organized in one spot.
Example:
Here’s a quick look at what your request could resemble:
GET /api/wallet/portfolio
Authorization: Bearer your-access-token
When you send out this request, you'll likely receive a response that might look something like this:
{
"wallet": {
"id": "12345",
"balances": [
{
"currency": "BTC",
"amount": 0.5
},
{
"currency": "ETH",
"amount": 2.0
}
],
"transactions": [
{
"id": "67890",
"type": "deposit",
"amount": 0.5,
"currency": "BTC",
"date": "2023-10-01"
}
]
}
}
This gives you a straightforward peek into your wallet and keeps you in control of your finances! Just think about all the amazing possibilities that come with this one simple call--total convenience right at your fingertips!
- Check out your indexer’s “wallet tokens” endpoint to snag those ERC‑20 balances and prices. Don't forget to cache that info for around 30-60 seconds, and then kick it up a notch by adding on‑chain deltas through mempool subscriptions. (docs.moralis.com)
Security checklist you can enforce this sprint
- Browser integration:
- Don’t forget to tap into the wallet provider API (EIP‑1193) and ask for accounts using eth_requestAccounts (EIP‑1102). Oh, and here’s a little heads-up: never put your node secrets in the frontend code! (eips.ethereum.org)
- Backend to providers:
- Make sure to set up IP/domain allowlists and use API secrets/JWTs whenever possible. Just a quick tip--try not to expose secrets to browser origins; this can cause CORS issues and could lead to leaks. Check out this helpful article for more info!
- Webhooks/streams:
- It’s super important to check HMAC signatures on webhook payloads that you get from your provider. Take Alchemy, for example--they use X‑Alchemy‑Signature with HMAC‑SHA256 for this. You can check it out here.
- Node hardening:
- Remember to turn off debug/trace on all public interfaces. Make sure your admin port is separate from the public JSON‑RPC. It's also smart to secure your WebSocket connections with authentication and set a limit on how many subscriptions can be made. (besu.hyperledger.org)
Handling vendor limits and reorgs (operational playbook)
- Rate limits and response caps:
- Keep in mind that there are payload limits (around 150 MB) and certain block-range restrictions for the chain. To handle those annoying 429 errors or timeouts, it’s really helpful to set up automatic range splitting and exponential backoff. You can find more info on this here.
- Reorg safety:
- When it comes to your live subscriptions, keep a rolling buffer of the last N blocks. If a reorg takes place, you’ll want to reconcile using the block hash and send the differences to your downstream consumers. Plus, it’s super important to make it clear what your UI should expect--like explaining the distinction between “pending” and “finalized” states.
- History expiry:
- If you’ve got over a year’s worth of history, it's a smart move to send that data to archive nodes or subgraphs. With clients now pruning based on EIP‑4444, depending on random nodes for access to older history isn't the best approach anymore. For more details, take a look at this link.
Chain- and stack‑specific nuances
- L2-specific RPCs:
- So, with Arbitrum, there are these arbtrace_* methods that switch over to debug_trace* after you hit a certain block height. Just a friendly reminder to check out the docs when you're diving into debuggers or analytics! (quicknode.com)
- Fee estimation:
- For getting the best fee estimates, try using
eth_feeHistorytogether witheth_maxPriorityFeePerGas. If that doesn’t do the trick, you can always turn to the gas suggestion APIs specific to the network when necessary. (eips.ethereum.org)
- For getting the best fee estimates, try using
Decision guide
Pick the main API for each workload first, and then add in the others as necessary:
- Latency-sensitive UX (swaps, mints, live positions)
- We’re leveraging JSON-RPC WebSocket subscriptions for heads and logs, using JSON-RPC for writing, and if you're interested, there's also the option of REST overlays to pull portfolio snapshots.
- Analytics and Backtests
- We’ve got a solid strategy that uses subgraphs for those handy time-travel reads, Substreams to manage high-volume protocols, and JSON-RPC for solid validation. Take a look at the details here: (thegraph.com)
- Wallets/enterprise dashboards
- When it comes to our dashboard needs, we lean on REST for managing portfolios, labels, and prices. JSON-RPC is super handy for grabbing accurate balances at safe or finalized tags, and for those complex joins, we turn to GraphQL. You can dive deeper into this over at (ethereum.org).
Implementation blueprint (reference architecture)
- Frontend:
- We’re leveraging the EIP‑1193 provider, which allows us to request accounts using
eth_requestAccountsand manage chain switching withwallet_switchEthereumChain. You can dive into the specifics here.
- We’re leveraging the EIP‑1193 provider, which allows us to request accounts using
- API Gateway (Your Backend):
- This is your go-to spot for handling REST, GraphQL, and JSON-RPC proxying all in one place.
- We’ve got a retry policy set up for every method, so if something goes awry, it’ll give it another shot. Plus, there's a batcher for read operations and circuit breakers for those endpoints that tend to get overloaded.
- When it comes to caching, we’ve put together a few layers: in-memory storage for frequently accessed keys like balances and a short-time-to-live edge cache for our REST indexer responses.
- To keep everything in check, we tag every call with details like method, chainId, p95 latency, error code, and payload bytes, giving you full visibility on what's happening.
- Data layer:
- We’re teaming up with a bunch of node providers across different regions to manage JSON‑RPC, and we’ve also got a WebSocket channel pool for handling subscriptions.
- We’ve rolled out subgraph deployments for our domain entities and set up Substreams for the heavier protocols.
- And don’t forget about the indexer REST that powers all the awesome cross‑chain user features!
What to pilot in Q1-Q2 2026
- Let's ditch those heavy backfills from raw
eth_getLogsand opt for:- Subgraphs (or even Substreams-powered subgraphs) for a more customized look at protocols, or
- Provider-indexed log endpoints with solid filters and block chunking. Check it out over at (thegraph.com).
- We should definitely add “safe/finalized” read paths for balances and positions. This will really help keep the UI running smoothly. More details can be found here: (ethereum.org).
- It’s time to swap those N×
eth_getTransactionReceiptcalls witheth_getBlockReceiptswhere we can. Let’s make sure we’re set by detecting features at startup. For more info, swing by (docs.chainstack.com). - Update the fee estimator by mixing
eth_feeHistorywith some chain-specific tips for when fees get crazy; plus, let’s precompute access lists for those tricky transactions. You can grab the details here: (eips.ethereum.org).
In-depth: what Dencun (EIP‑4844) changes for APIs
- Check it out! You can now find new fields like
blob_gas_usedandexcess_blob_gasin every block when you use the standard JSON-RPC “get block” calls. It’s smart to keep tabs on these if you’re managing L1 DA fees from an L2. (eips.ethereum.org) - Just a quick note: blob data doesn't hang around for too long--around 18 days, to be exact--and it gets shared via blob sidecars. Keep in mind that your execution-layer RPC won't give you access to the blob contents, so it's a good idea to concentrate your observability on costs rather than just blob bytes. (blog.ethereum.org)
In-depth: history expiry (EIP‑4444) and your data strategy
- Execution clients can actually trim away old receipts and bodies, so don’t expect nodes to just pull up logs from 2019 like it’s nothing. If you need that kind of deep history, you’ll want to check out archive specialists, subgraphs, or community history networks. For more info, take a look here: (blog.ethereum.org).
- Geth and Nethermind have done a great job of explaining their pruning modes and Era1 sources. Just be sure to keep your ops runbooks in sync with their client documentation, and don’t forget to set up your pruning windows! You can check out more details here: (geth.ethereum.org).
Final take
For serious Web3 products, it’s a smart move to intentionally adopt a hybrid approach when it comes to your API surface:
- JSON-RPC: Awesome for dealing with writes, setting up live subscriptions, and really getting into the nitty-gritty of chain semantics.
- GraphQL: Just the ticket for clients or subgraphs that want super efficient, composable reads while still enjoying historical determinism.
- REST Indexers: Perfect for cross-chain, user-centric features that come through at lightning speed.
Design your gateway to support all three languages, then fine-tune the settings (like chunking, time-travel, and finalized tags) as the protocol landscape evolves.
Sources and further reading
- Be sure to check out the EIP‑1474 JSON‑RPC spec and the EIP‑1193 provider API; these are your best bets for understanding how wallets, dapps, and nodes communicate with each other. (eips.ethereum.org)
- Don't skip the EIP‑1767 GraphQL info, and definitely take a look at the Geth/Besu GraphQL documentation (just so you know, it’s HTTP-only on Besu). (eips.ethereum.org)
- Dive into Dencun / EIP‑4844 for the lowdown on headers, fees, and how blob behavior functions. (eips.ethereum.org)
- If you’ve got a bit of curiosity about EIP‑4444, it’s all about partial history expiry and client pruning--definitely worth your time! (blog.ethereum.org)
- And don’t forget to keep an eye on the provider constraints for eth_getLogs; checking out the subscription guidance will also make your life a whole lot easier. (alchemy.com)
If you want 7Block Labs to give your existing API setup a thorough pressure test, we've got your back! We'll evaluate your workloads based on the blueprint above and provide you with a list of low-risk, high-impact changes in under two weeks.
Like what you're reading? Let's build together.
Get a free 30-minute consultation with our engineering team.
Related Posts
ByAUJay
Building a Donation-Based Crowdfunding Platform That Gives Tax Receipts
**Summary:** Donation-based crowdfunding that includes tax receipts has become quite the complex puzzle across different regions. You've got to navigate IRS Pub 1771/526 rules, UK Gift Aid declarations, Canada’s CRA receipting, and the new eIDAS/OpenID4VCI wallets--all while keeping everything running smoothly.
ByAUJay
Why 'Full-Lifecycle Advisory' Beats Just Coding
**Summary:** Engineering teams that focus solely on “writing Solidity” often find themselves caught off guard by shifts in protocols, the need for composable security, and the procurement hurdles that are now impacting real ROI. Our full-lifecycle advisory service bridges the gap by connecting EIP-7702 smart accounts, modular decentralized applications (DA), and ZK-based compliance solutions.
ByAUJay
Why Your Project Could Really Use a 'Protocol Economist
Summary: A lot of Web3 teams are missing a crucial player: the “protocol economist.” And you can really see the impact--value slips away through MEV routing, token incentives that are all out of whack, and those sneaky changes to wallets after Pectra that end up messing with the unit economics. In this playbook, we’ll explore what a protocol economist can do to tackle these issues head-on.

