Enhance Developer Experience with Gelato Functions Callbacks

Gelato Team

Dec 14, 2023

Turbocharge your DevX by 1000x with Gelato Functions Callbacks!

With the NEW Gelato Functions update — Callbacks, enhance your developer experience with more feedback on the transaction lifecycle.

Gelato's Functions are serverless and event-driven tools designed for automating blockchain transactions using both off-chain and on-chain data.

What are Callbacks?

The introduction of Callbacks within Gelato Functions allows developers to efficiently manage transaction outcomes. This feature offers a robust framework to handle various scenarios in automated tasks, ultimately enhancing the functionality of decentralized applications (dApps).

Why are Callbacks Essential?

  • Enhanced Control: Callbacks let you respond to the success or failure of your transactions, offering greater control over your dApp's automated processes.

  • Error Handling: Implement comprehensive error handling to ensure robustness and reliability.

  • Custom Logic: Execute custom logic based on transaction outcomes, such as sending alerts, updating databases, or triggering additional transactions.

Types of Callbacks

Check out real-world implementations in our GitHub repository.

onSuccess Callback

Triggered after a successful on-chain execution. Ideal for tracking transactions and post-processing.

Web3Function.onSuccess(async (context: Web3FunctionSuccessContext) => {
  const { transactionHash } = context;
  console.log("onSuccess: txHash: ", transactionHash);
  // Additional onSuccess logic...
});

onFail Callback

Invoked when an execution encounters issues such as insufficient funds, failed simulations, or execution reverts. Crucial for error handling and fallback strategies.

Web3Function.onFail(async (context: Web3FunctionFailContext) => {
  const { reason, transactionHash, callData } = context;
  // Handle failure scenarios...
});

Example Use Case: Oracle Price Update

Scenario: An Oracle contract needs regular updates on cryptocurrency prices from an external API.

  • onRun: Prepares calldata for updating the Oracle with the latest price.

  • onSuccess: Logs the transaction hash, updates the database, fetches price, and updates storage.

  • onFail: Handles errors (API failures, reverts), constructs alerts, and sends Slack notifications.

onSuccess Example

// Web3 Function onSuccess callback
Web3Function.onSuccess(async (context: Web3FunctionSuccessContext) => {
  const { userArgs, transactionHash, storage } = context;
  console.log("userArgs: ", userArgs.canExec);
  console.log("onSuccess: txHash: ", transactionHash);

  const currency = (userArgs.currency as string) ?? "ethereum";
  let price = 0;

  try {
    price = await getCurrentPrice(currency);
    console.log(`Current Price: ${price}`);
    await storage.set("lastPrice", price.toString());
  } catch (err) {
    console.error("Failed to update price:", err);
  }

  await storage.set("lastPrice", price.toString());
});

onFail Example

// Web3 Function onFail callback
Web3Function.onFail(async (context: Web3FunctionFailContext) => {
  const { userArgs, reason } = context;

  let alertMessage = `Web3 Function Failed. Reason: ${reason}`;
  console.log("userArgs: ", userArgs.canExec);

  if (reason === "ExecutionReverted") {
    alertMessage += ` TxHash: ${context.transactionHash}`;
  } else if (reason === "SimulationFailed") {
    alertMessage += ` callData: ${JSON.stringify(context.callData)}`;
  }

  console.log(alertMessage);
  await sendSlackAlert(alertMessage);
});

Testing Your Callbacks

Gelato Functions provide a local testing environment for callbacks. Simulate both successful and failed executions with --onSuccess or --onFail flags.

# Test onFail Callback
yarn test src/web3-functions/callbacks/index.ts --logs --onFail

# Test onSuccess Callback
yarn test src/web3-functions/callbacks/index.ts --logs --onSuccess

Conclusion

Callbacks in Gelato Functions provide dynamic control of dApps. By responding to both success and failure, developers can fine-tune app behavior, add error handling, and implement custom logic for specific requirements.

About Gelato

Gelato is a Web3 Cloud Platform empowering developers to create automated, gasless, and off-chain-aware L2s and smart contracts. Over 400 projects rely on Gelato to process millions of transactions in DeFi, NFTs, and gaming.

  • Gelato RaaS: Deploy tailor-made ZK or OP L2s in a single click with Account Abstraction and Gelato middleware baked in.

  • VRF: On-chain verifiable randomness for blockchain apps.

  • Functions: Serverless, event-driven functions to automate transactions.

  • Relay: Reliable, scalable gasless transactions via a simple API.

  • Account Abstraction SDK: Built with Safe, combining gasless transactions with secure smart contract wallets.

Subscribe to our newsletter and turn on your Twitter notifications for updates. Interested in joining the Gelato team? Browse open positions here.

Ready to build?

Start with a testnet, launch your mainnet in days, and scale with industry-leading UX.

Ready to build?

Start with a testnet, launch your mainnet in days, and scale with industry-leading UX.

Ready to build?

Start with a testnet, launch your mainnet in days, and scale with industry-leading UX.

Ready to build?

Start with a testnet, launch your mainnet in days, and scale with industry-leading UX.