Interacting with smart contracts
Tinkering with blocks and contracts
Overview
Smart Contracts are vague, so knowing how to interact with them is a beneficial especially if you like to tinker with it. Interacting with ethereum blockchain is either by reading blockchain data or sending transactions. JSON-RPC is a stateless, light-weight remote procedure call (RPC) protocol. It defines several data structures and the rules around their processing. So every Ethereum Client follows a JSON-RPC Specification so that there’s a uniform set of methods that can be rely on regardless of client and node implementation
There are lot of methods that can be use, and starting a JSON-RPC is kinda complicated because it depends on the client of your choice. Now there’s another one called ethers.js where it aims to be compact library for interacting Ethereum Blockchain and its ecosystem. It is often use in DeFi apps, notably wallets like Metamask.
The primary difference of ethers.js and JSON-RPC is you will write a lot of code that should have templated and generic HTTP library to receive and request responses whereas Ethers.js is a simpler library that allows you to make JSON-RPC requests in JavaScript where each request is a single function call.
There’s three important concepts:
- Provider - a node provider that grants read and write access to the blockchain.
- Signer - an Ethereum account that allows for transactions to be signed.
- Contract - an object that represents a specific deployed on-chain contract.
There’s also Viem which is very interesting since it featured anvil by Foundry and also a language that is closely aligned to the official Ethereum terminology.
How It Works:
- Connecting to Ethereum:
- Use a Provider for read-only access or MetaMask for authenticated write access.
- Custom RPC Backend:
- Utilize JSON Rpc Provider for running your Ethereum node or custom third-party services.
- User Interaction:
- Convert user inputs to integer units (wei) for Ethereum transactions.
- Interacting with Blockchain:
- Provider allows querying blockchain data; Signer is for sending transactions with private key access.
- Contracts:
- Defined by ABI, offering read-only (view and pure) and state-changing methods.
- ABI and Event Handling:
- ABI defines contract interaction; Events trigger actions based on state changes.
- Signing Messages:
- Private keys sign messages for authentication and authorization purposes.
- Transport:
- intermediary layer that is responsible for executing outgoing requests
Conclusion
If you want a direct and have specific controls learning JSON-RPC is worth but if you want something that works right out of the box then ethers.js or Viem is cool (after checking out viem’s documentation i favor this a lot).