Combine multiple transactions and make them atomic
Introduction
With Blocto, you can combine multiple transactions into a single transaction for the following advantages:
Save gas fee
Make multiple transactions atomic, so they either all succeed or all fail
Usage
There are two ways to combine transactions:
A. EIP-1193 (Recommended)
import Web3 from'web3';// Use the Ethereum provider injected by Blocto appconsttxHash=awaitwindow.ethereum.request({ method:'wallet_sendMultiCallTransaction', params: [ [web3.eth.sendTransaction.request(SOME_REQUEST),web3.eth.sendTransaction.request(SOME_OTHER_REQUEST) ],true// revert flag, could be true or false ]});console.log(txHash); // ex: 0x12a45b...
B. Web3 Batch Request
import Web3 from'web3';// Use the Ethereum provider injected by Blocto appconstweb3=newWeb3(window.ethereum);constbatch=newweb3.BatchRequest();batch.add(web3.eth.sendTransaction.request(SOME_REQUEST));batch.add(web3.eth.sendTransaction.request(SOME_OTHER_REQUEST));constresponses=awaitbatch.execute();
Example
For example, if you are building a campaign for PoolTogether. You want to let user claim a DAI token from a smart contract, approve PoolTogether from spending user's DAI and deposit the DAI into PoolTogether, you can do something like:
A. EIP-1193
import Web3 from'web3';// approve DAIconstapproveDAIReq=web3.eth.sendTransaction.request({ from: address, to:'0x6b175474e89094c44da98b954eedeac495271d0f', data: '0x095ea7b300000000000000000000000029fe7d60ddf151e5b52e5fab4f1325da6b2bd9580000000000000000000000000000000000000000000845951614014849ffffff',
},'latest');// put in PoolTogetherconstputInPoolTogetherReq=web3.eth.sendTransaction.request({ from: address, to:'0x29fe7D60DdF151E5b52e5FAB4f1325da6b2bD958', data:'0x234409440000000000000000000000000000000000000000000000000de0b6b3a7640000',},'latest');// Use the Ethereum provider injected by Blocto appconsttxHash=awaitwindow.ethereum.request({ method:'wallet_sendMultiCallTransaction', params: [ [ approveDAIReq, putInPoolTogetherReq ],true ]});console.log(txHash) // ex: 0x12a45b...
B. Web3 Batch Request
import Web3 from'web3';// Use the Ethereum provider injected by Blocto appconstweb3=newWeb3(window.ethereum);constbatch=newweb3.BatchRequest();// claim DAI from some promotion smart contractbatch.add(web3.eth.sendTransaction.request({ from: address, to:'SOME_PROMOTION_CONTRACT', data:'SOME_METHOD_HASH',},'latest'));// approve DAIbatch.add(web3.eth.sendTransaction.request({ from: address, to:'0x6b175474e89094c44da98b954eedeac495271d0f', data: '0x095ea7b300000000000000000000000029fe7d60ddf151e5b52e5fab4f1325da6b2bd9580000000000000000000000000000000000000000000845951614014849ffffff',
},'latest'));// put in PoolTogetherbatch.add(web3.eth.sendTransaction.request({ from: address, to:'0x29fe7D60DdF151E5b52e5FAB4f1325da6b2bD958', data:'0x234409440000000000000000000000000000000000000000000000000de0b6b3a7640000',},'latest'));constresponses=awaitbatch.execute();