Connect Smart Contracts to Web2 API with Gelato Web3 Functions

Gelato Team

Aug 4, 2023

Gelato Web3 Functions offer a powerful solution to connect on-chain smart contracts with off-chain data. The on-chain component is the smart contract you want to automate, while the off-chain element is the Web3 Function that fetches and processes external API or subgraph data.

By configuring a Web3 Function Task, you can seamlessly integrate both sides, enabling greater control and automation for decentralized applications. In this blog post, we demonstrate 5 ways to integrate Web2 APIs with smart contracts, complete with code examples.

1. Update Oracle Smart Contract using CoinGecko Price API

CoinGecko provides real-time price feeds and crypto market data. Using Web3 Functions, you can fetch the price of ETH from CoinGecko and update an oracle contract on-chain every 5 minutes.

Implementation

Example Web3 Function script to update an oracle with CoinGecko ETH price:

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

const ORACLE_ABI = [
  "function lastUpdated() external view returns(uint256)",
  "function updatePrice(uint256)",
];

Web3Function.onRun(async (context: Web3FunctionContext) => {
  const provider = context.multiChainProvider.default();
  const oracleAddress = "0x71b9b0f6c999cbbb0fef9c92b80d54e4973214da";
  const oracle = new Contract(oracleAddress, ORACLE_ABI, provider);

  const lastUpdated = parseInt(await oracle.lastUpdated());
  const nextUpdateTime = lastUpdated + 300; // 5 min interval
  const timestamp = (await provider.getBlock("latest")).timestamp;
  if (timestamp < nextUpdateTime) return { canExec: false, message: "Too early" };

  const priceData = await ky
    .get("https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd")
    .json();
  const price = Math.floor(priceData["ethereum"].usd);

  return {
    canExec: true,
    callData: [{
      to: oracleAddress,
      data: oracle.interface.encodeFunctionData("updatePrice", [price])
    }],
  };
});

2. Automated Trades with Web3 Functions

Automated trading strategies like Trailing Stop or Bounce Entry can be implemented by monitoring Uniswap prices via Web3 Functions.

Implementation

  • Trailing Stop: Exit a trade if the price drops below a dynamic threshold from the max recorded price.

  • Bounce Entry: Enter a trade if the price increases beyond a threshold from the min recorded price.

See the GitHub code for full strategy implementations.

3. Sports Betting Platform

A betting contract can use Web3 Functions to fetch match results from a sports API and trigger on-chain payouts automatically.

Implementation

Web3Function.onRun(async (context) => {
  const gameId = context.userArgs.gameId ?? "Argentina_vs_France";
  const res = await axios.get(`https://www.thesportsdb.com/api/v1/json/3/searchevents.php?e=${gameId}`);
  const gameEvent = res.data.event[0];

  if (gameEvent.strStatus !== "Match Finished") 
    return { canExec: false, message: "Match not finished yet" };

  const BETTING_CONTRACT_ABI = ["function updateGameScore(string, uint16, uint16)"];
  const bettingInterface = new utils.Interface(BETTING_CONTRACT_ABI);

  return {
    canExec: true,
    callData: [{
      to: targetContract,
      data: bettingInterface.encodeFunctionData("updateGameScore", [
        gameId,
        parseInt(gameEvent.intHomeScore),
        parseInt(gameEvent.intAwayScore),
      ])
    }],
  };
});

4. Automated Content Creation on Lens with ChatGPT

Combine AI and Web3 by using Web3 Functions to connect with the OpenAI ChatGPT API and post automated content on Lens Protocol.

Implementation

The LensGelatoGPT contract manages prompts, while the Web3 Function calls OpenAI, validates metadata, uploads it to IPFS, and triggers LensHub’s post function.

See the GitHub tutorial for complete code.

// Generate text with OpenAI
const openai = new OpenAIApi(new Configuration({ apiKey: SECRETS_OPEN_AI_API_KEY }));
const response = await openai.createCompletion({ model: "text-davinci-003", prompt });
const text = response.data.choices[0].text;

// Upload metadata to IPFS
const storage = new Web3Storage({ token: WEB3_STORAGE_API_KEY });
const file = new File([JSON.stringify({ content: text })], "publication.json");
const cid = await storage.put([file]);
const contentURI = `https://${cid}.ipfs.w3s.link/publication.json`;

// Prepare callData for LensHub
const iface = new utils.Interface(lensHubAbi);
callDatas.push({ to: lensHubAddress, data: iface.encodeFunctionData("post", [postData]) });

5. NFT Creation with Stable Diffusion API

Use Stable Diffusion to generate NFT artwork dynamically and assign images as metadata to unrevealed NFTs.

Implementation

// Check unrevealed NFTs
const nft = new Contract(nftAddress, NFT_ABI, provider);
const currentTokenId = (await nft.tokenIds()).toNumber();
if (currentTokenId === lastProcessedId) return { canExec: false };

// Generate image with Stable Diffusion API
const res = await fetch("https://stablediffusionapi.com/api/v3/text2img", {...});
const data = await res.json();
const imageUrl = data.output[0];

// Upload metadata to IPFS
const imageBlob = (await axios.get(imageUrl, { responseType: "blob" })).data;
const nftStorage = new NFTStorage({ token: nftStorageApiKey });
const metadata = await nftStorage.store({ image: new File([imageBlob], "nft.png") });

// Update contract
callDatas.push({
  to: nft.address,
  data: nft.interface.encodeFunctionData("revealNft", [tokenId, metadata.url]),
});

See the GitHub repo for full details.

About Gelato

Join our community on Discord.

Web3 Functions are available today in private beta. Explore the docs and our in-depth tutorial. Apply here to test Web3 Functions.

If you’re new to Gelato

Gelato is Web3’s decentralized backend powering automated, gasless, and off-chain aware smart contracts across Ethereum, Arbitrum, Polygon, Optimism, zkSync, and more. 400+ projects rely on Gelato for millions of transactions in DeFi, NFTs, and gaming.

Core Services:

  • Web3 Functions: Connect smart contracts to off-chain data & computation.

  • Automate: Execute transactions automatically with reliability.

  • Relay: Provide gasless transactions with a simple API.

  • Gasless Wallet: An SDK combining Gelato Relay + Safe’s Smart Wallet to enable Account Abstraction.

Subscribe to our newsletter and turn on Twitter notifications for updates.
Explore open positions and apply 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.