BLOG — Updates

659 days ago

Introducing Web3 Functions: Building Serverless Web3 Apps

Web3 Functions are a new paradigm enabling developers to build web3 apps that run entirely serverless, without creating a single point of failure or the need to trust a centralized party to run the correct computation.

They can be thought of as decentralized cloud functions that enable web3 developers to:

  • Connect their smart contracts to off-chain data
  • Ensure this data is accurate and is signed off by multiple parties
  • Run off-chain computation
  • Execute transactions on all major blockchains
  • Send notifications triggered by events or state changes
  • Index and store data such as events and transaction receipts

Our goal with Web3 Functions is to provide developers with a web3 native alternative to running their server side logic on centralized platforms like AWS or Google Cloud. Using Web3 Functions, developers are able to augment their smart contracts with a powerful, scalable and trust-minimized infrastructure that can power all of their off-chain server components, without sacrificing decentralization.

How Web3 Functions Work

Writing a Web3 Function is very similar to writing a traditional cloud function, just that the code is stored on IPFS instead of centralized servers and run by Gelato Nodes instead of a centralized cloud provider.

To create a Web3 Function, developers can use this template to write their logic in Typescript code (e.g. calling an arbitrary API and run computation on the result). Developers can run their Web3 Function locally and once tested, deploy them to IPFS and receive an IPFS ID. Gelato Nodes can then be instructed to run the Web3 Function, identifiable with the ID, on their behalf based on certain triggers. Web3 Functions can be triggered on a set time interval, when a certain on-chain event has been emitted or via a webhook.

Once a Web3 Function is invoked, for example every minute, Gelato Node Operators will run its logic and agree on the data that should be used to execute an on-chain transaction. The number of Gelato Nodes that have to sign off on data before executing a transaction can be defined by the Web3 Function creator. Some data, which is non-deterministic (e.g. price data), has to be aggregated and signed off differently than deterministic data (e.g. a certain Subgraph at block n).

Thus, Web3 Functions provide a more powerful and flexible approach to how Oracles are used today, expanding their use from simply pushing price feeds to enabling them to run the entire backend of web3 applications in a decentralized and scalable way.

Technical Features of Web3 Functions:

  • Full Typescript support with Deno runtime
  • RPC provider abstraction
  • Access to environment variables
  • Web3 Functions can be private or public (on IPFS)
  • Access to in-function state management
  • Flexible pay-per-usage pricing
  • High scalability
  • Spawn Web3 Functions using on-chain transactions

For a developer tutorial on creating Web3 Functions, check out our blog post here.

Examples of Web3 Functions in Action

Say you’re building a sports betting platform and you’d like to trigger an on-chain reaction if a certain team wins, so that everyone who placed a winning bet will get paid.

That information is not something you can access in smart contracts – you would need to call some APIs to retrieve that data, and based on the outcome, it would trigger the execution of transactions on any EVM chain. Web3 Functions allows you to connect your app to relevant, real-world data that enriches the user experience and gives developers the flexibility to create a whole new class of new web3 use cases.

import { Web3Function, Web3FunctionContext } from "@gelatonetwork/web3-functions-sdk";
import { utils } from "ethers";
import axios from "axios";

Web3Function.onRun(async (context: Web3FunctionContext) => {
  // Call SportsDB API to get game status & score
  const gameId = (context.userArgs.gameId as string) ?? "Argentina_vs_France";
  let gameEvent;
  try {
    const api = `https://www.thesportsdb.com/api/v1/json/3/searchevents.php?e=${gameId}`;
    const res = await axios.get(api);
    gameEvent = res.data.event[0];
  } catch (err) {
    return { canExec: false, message: `SportDb API call failed` };
  }

  // Wait for match to be finished
  console.log("Game details:", gameEvent);
  if (gameEvent.strStatus !== "Match Finished") {
    return { canExec: false, message: `Match not finished yet` };
  }

// Prepare the CallData to be executed  
  const BETTING_CONTRACT_ABI = ["function updateGameScore(string, uint16, uint16)"];
  const bettingInterface = new utils.Interface(BETTING_CONTRACT_ABI);

// Pushing the callData to the callData Array
  const callData = []
  callData.push({
    to: targetContract,
    data:bettingInterface.encodeFunctionData("updateGameScore",[
      gameId,
      parseInt(gameEvent.intHomeScore),
      parseInt(gameEvent.intAwayScore),
       ]) 
})
// Publish final score on-chain

  return { 
    canExec: true,
    callData: callData
    };
 });

Further Examples:

  • On-chain music royalty payments that are based on how often songs are played on streaming platforms like Spotify
  • Automated trading strategies that require access to DEX Aggreagtor endpoints (e.g. 1inch or Paraswap)
  • Resolving prediction market outcomes using real world data
  • Pushing custom-created price feeds such as NFT price floors
  • Liquidity management strategies that require complex AI algorithms and off-chain price related data
  • Liquidation systems that need to check a large number of debt positions for potential liquidations

About Gelato

Gelato is a Web3 Cloud Platform empowering developers to create automated, gasless, and off-chain-aware Layer 2 chains and smart contracts. Over 400 web3 projects rely on Gelato for years to facilitate millions of transactions in DeFi, NFTs, and gaming.

  • Gelato RaaS: Deploy your own tailor-made ZK or OP L2 chains in a single click with native Account Abstraction and all Gelato middleware baked in.

  • Web3 Functions: Connect your smart contracts to off-chain data & computation by running decentralized cloud functions.

  • Automate: Automate your smart contracts by executing transactions automatically in a reliable, developer-friendly & decentralized manner.

  • Relay: Give your users access to reliable, robust, and scalable gasless transactions via a simple-to-use API.

  • Account Abstraction SDK: Gelato has partnered with Safe, to build a fully-fledged Account Abstraction SDK, combining Gelato's industry's best gasless transaction capabilities, with the industry's most secure smart contract wallet.

Subscribe to our newsletter and turn on your Twitter notifications to get the most recent updates about the Gelato ecosystem! If you are interested in being part of the Gelato team and building the future of the Internet browse the open positions and apply here.