Callbacks can be used to manage the outcome of your transaction submission. This advanced feature enables your functions to adapt based on the execution status, whether successful or not, thus providing a robust way to handle different scenarios that may occur during task execution. Let’s explore the two types of callbacks available:
Callback Function Example:
import { Web3Function, Web3FunctionContext, Web3FunctionFailContext, Web3FunctionSuccessContext,} from"@gelatonetwork/web3-functions-sdk";import { Contract } from"@ethersproject/contracts";import ky from"ky"; // Using ky for HTTP requestsconstORACLE_ABI= ["function lastUpdated() external view returns(uint256)","function updatePrice(uint256)",];// Callback for successful executionWeb3Function.onSuccess(async (context:Web3FunctionSuccessContext) => {const { transactionHash } = context;//onSuccess Logic goes here});// Callback for handling failuresWeb3Function.onFail(async (context:Web3FunctionFailContext) => {const { reason,transactionHash,callData } = context;//onFail Logic goes here});// Main function logicWeb3Function.onRun(async (context:Web3FunctionContext) => {const { userArgs,multiChainProvider } = context;// Core logic goes here to prepare callDatareturn { canExec:false, message:"Nothing to execute yet" };});
Types of Callbacks
onSuccess Callback
This callback gets invoked after a successful on-chain execution. It’s especially useful for tracking successful transactions or for further processing after a task completes.
The Web3FunctionSuccessContext offers access to the transactionHash, allowing you to reference and track the successful transaction within your application.
onFail Callback
Triggered when an on-chain execution encounters issues such as
InsufficientFunds: When the account executing the function does not have enough balance to cover the transaction fees.
SimulationFailed: If the execution simulation (a pre-run of the transaction) fails, indicating that the actual transaction might also fail.
ExecutionReverted: When the actual transaction is executed on the blockchain but is reverted due to a condition in the smart contract code or because it runs out of gas.
This callback is crucial for handling errors and implementing fallback logic.
reason: This is a string indicating why the failure occurred.
transactionHash: Provided when the reason for failure is ExecutionReverted, this is the unique identifier of the reverted transaction.
callData: Available when the reason is SimulationFailed, this is the data that was used during the function run, which can be useful for debugging the failure.
Testing Your Callbacks
You can test your callbacks locally using specific flags during the test execution. This helps in ensuring that your callbacks function as intended before deployment.