How to use Web3 Functions to build serverless web3 apps

Gelato Team

Feb 21, 2023

We call our smart contracts 'smart' because they know exactly how to do what we ask them to. Having immutable code that executes as expected is powerful, but the challenge is they don’t know when to execute — and timing is crucial in financial systems.

Since inception, Gelato has enabled web3 developers to automate tasks based on on-chain conditions. Now, Gelato is going one step further with Web3 Functions — decentralized, serverless functions that can communicate both on-chain and off-chain, run any custom logic, and send transactions on-chain.

👉 Learn more in our Web3 Functions blog post.

Decentralized Serverless Functions

Think of Web3 Functions as decentralized versions of AWS Lambda or Google Cloud Functions — but for web3. They let you execute on-chain transactions based on arbitrary off-chain data (APIs, subgraphs, etc.) and computation. Functions are written in TypeScript, stored on IPFS, and run by Gelato Nodes. For details, visit the documentation.

Creating Web3 Functions

To build a decentralized Web3 Function, follow two stages:

  1. Write, test, and deploy the function itself

  2. Create a task that executes the Web3 Function

Writing, Testing & Deploying a Web3 Function

1. Clone the template repo:

git clone https://github.com/gelatodigital/web3-functions-template
cd web3-functions-template
yarn

2. Configure environment variables:

cp .env.example .env

Edit .env with your provider RPC URL and optionally a private key:

PROVIDER_URL="https://eth-mainnet.alchemyapi.io/v2/YOUR_ALCHEMY_ID"
PRIVATE_KEY=""

3. Write your function:

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

Web3Function.onRun(async (context: Web3FunctionContext) => {
  // custom logic here
  return { canExec: true, callData: "YOUR_EXECUTION_PAYLOAD" };
});

When conditions aren’t met, return:

return { canExec: false, message: "Condition not met" };

4. Example: Random API + On-chain Check

let abi = [
  "function active() view returns (bool)",
  "function setMockString(string) external",
];
let contract = new ethers.Contract(contractAddress, abi, provider);

if (!(await contract.active())) {
  return { canExec: false, message: "Contract not active" };
}

let randomApiRes: any = await ky.get("http://www.randomnumberapi.com/api/v1.0/random?min=0&max=100&count=1").json();
let random = randomApiRes[0] as number;

if (random <= 75) {
  return { canExec: false, message: "Number ≤ 75" };
}

const { data } = await contract.populateTransaction.setMockString("random_string");
return { canExec: true, callData: data! };

5. Test your function locally:

npx w3f test src/web3Functions/display-string/index.ts

6. Deploy to IPFS:

npx w3f deploy src/web3Functions/display-string/index.ts

This returns a CID, which you’ll use to create a task.

Create a Task to Run Your Web3 Function

With your Web3 Function deployed to IPFS, you can now set up a task in the Gelato Web3 Functions UI (currently private beta).

  1. Input the CID, arguments, network, target smart contract, and method

  2. Check source code to verify

  3. Name your task and submit

Gelato Nodes will now handle execution based on your logic and triggers.

Demo App

We’ve built a demo integrating:

  • Web3 Functions (serverless logic)

  • Hardhat contracts and deployment scripts

  • A React frontend

The demo includes a contract with an active flag and a Web3 Function that calls an external API and executes a transaction when conditions are met. Try it out:

Resources

About Gelato

Gelato is a Web3 Cloud Platform powering automated, gasless, and off-chain-aware smart contracts across major Layer 2 chains. 400+ projects rely on Gelato for millions of DeFi, NFT, and gaming transactions.

👉 Subscribe to our newsletter and follow us on Twitter.
👉 Explore careers at Gelato to help build the future of Web3.

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.