I like learning things when building. So, tutorials, blog posts and then books are my go-to tools when picking up a new paradigm or tool. With the same mindset, after some tinkering with DApps, I realized an important detail that might be helpful to any beginner.
When building your first web3 application by following up on tutorials, you may not notice the difference between send
and call
methods immediately.
Let me try to explain the difference below.
Call
Contract methods that do not modify the state of the contract and have no logic other than returning a value can be invoked with call
methods.
- they don't cost any gas or transaction fees - it is free to call them
- used for view and pure functions (read-only), so it's faster to execute
- no need to sign them with MetaMask or with another provider
- safer to use them because they don't forward gas and publish anything
an example call to contract
web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1")
.then(console.log);
> "1000000000000"
Send
Contract methods that modify the state of the contract uses send
method to add this modification to the blockchain.
- they cost gas and transaction fees - it is not free to invoke those functions
- it needs a
from
as the sender address - it needs to be signed through MetaMask or with another provider
- it is published in the form of transaction and can publicly be seen on the blockchain
an example send to contract
web3.eth.sendTransaction({
from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe',
value: '1000000000000000'
})
.on('transactionHash', function(hash){
...
})
.on('receipt', function(receipt){
...
})
.on('confirmation', function(confirmationNumber, receipt){ ... })
.on('error', console.error);
Notice, getBalance
will return a value while sendTransaction
method returns a callback which is expected to include a 32 bytes transaction hash.
This is an important detail to keep in mind when designing our interactions with the contract and user.
Happy coding!
Top comments (0)