BLOG — Updates

89 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` };
  }

  // Publish final score on-chain
  const BETTING_CONTRACT_ABI = ["function updateGameScore(string, uint16, uint16)"];
  const bettingInterface = new utils.Interface(BETTING_CONTRACT_ABI);
  return { 
    canExec: true,
    callData: bettingInterface.encodeFunctionData("updateGameScore",[
      gameId,
      parseInt(gameEvent.intHomeScore),
      parseInt(gameEvent.intAwayScore),
       ]) 
    };
 });

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

Gelato’s mission is to enable developers to augment their smart contracts by building and running their entire web3 backend in a serverless, decentralized, secure, and scalable manner. This new service finally expands Gelato to serve more use cases, including projects that need access to off-chain data. Web3 Functions serve as the missing piece of the puzzle to bridge Gelato’s web3 infrastructure services across the off-chain and on-chain worlds, accelerating the adoption of web3 by making use cases more applicable to everyday users.

Web3 Functions are available today in private beta on most major EVM networks like Ethereum, Polygon, Optimism, Arbitrum and more. For more information, please check out the Web3 Functions documentation.

Apply here to be one of the first to test Web3 Functions.