How To Use Gelato Web3 Functions On BuildBear Sandbox

BuildBear Team
BuildBear Labs
Published in
7 min readMay 30, 2024

In this tutorial, we’ll walk through the process of deploying a Web3 function, creating an automated task, and executing automated actions on the BuildBear Sandbox. By the end of the tutorial, you will get a clear understanding of creating web3 functions and executing automated tasks.

Implementation Path For Creating Web3 Function

  • Choose Trigger Type: Select Trigger Type allows you to choose between time-based, event-based, or every block triggers. In this tutorial, we will be using time based trigger that executes every minute.
  • Select Task Type: This option lets you choose between TypeScript Function, Solidity Function, or Transaction types. Typescript Functions are suitable for tasks requiring off-chain data or computations. This tutorial contains a typescript-based function and we will see how to fetch data from API to execute the task.
  • Create Web3 Function Task: The task connects your Web3 function to a targeted smart contract for execution. Here every one minute is set in the task to trigger the web3 function.
  • Finalize and Monitor Tasks: To make ensure the completion of tasks, one can monitor their outcomes in the explorer. When a task is executed, it provides the IPFS CID of the deployed Web3Function making it available to anyone with CID.

Development Setup

To get started, we have set up the following repo with the required functions. Clone this repository using the commands shown below:

git clone https://github.com/BuildBearLabs/Gelato-Web3-Functions.git
cd Gelato-Web3-Functions
yarn install

Open a code editor like VS Code and explore the folder structure. It includes three main folders:

  • The script folder contains task execution scripts.
  • The test folder has functionalities for testing.
  • The web3-function folder contains all the web3 functions.

Create Your Private Sandbox and install the Gelato plugin

Visit BuildBear Home to create a new Sandbox. If you are new to BuildBear, refer to our comprehensive documentation to sign up and create your sandbox here.

Click on the Plugins option from the sandbox dashboard. From the All Plugins tab, select and install the Gelato plugin, once installed it will be visible under installed Plugins.

Configure your local environment by creating a .env file containing the private key and RPC URL in the format shown below;

## Example Private Key and RPC
PRIVATE_KEY=670e8f5f57a3bc4bd1869d473591ff10f6cf0d69a254257b61eca3f244ef188
PROVIDER_URLS= https://rpc.buildbear.io/sanam

Creating a Web3 Function

Now, we will look into how we can automate the execution of its function by creating a Web3 Function. Inside the web3-functions folder, there are multiple folders containing various Web3 functions. In this tutorial, we will see how to implement ‘advertising-board’ function. Inside a web3 function, the core functionality is defined over index.ts.

This script defines a Web3Function, which executes on-chain transactions based on off-chain data. Let’s break down the script:

Web3Function.onRun

  • This function is invoked when the Web3Function is triggered to run. It takes a callback function with a context parameter of type Web3FunctionContext.
  • Inside this callback function, the context object provides access to user arguments (userArgs), storage (storage), and a multi-chain provider (multiChainProvider).

Provider and Ad Board Contract Initialization

  • The default provider is obtained from the multi-chain provider.
  • The address of the Ad Board contract is retrieved from user arguments (userArgs.adBoard) or set to a default value.
  • The last post timestamp is retrieved from storage, and if it doesn’t exist, it defaults to 0.
  • An instance of the Ad Board contract is created using the address and ABI.

Post Message Logic

  • Calculates the next allowed post time by adding 1 hour to the last post timestamp.
  • Retrieves the current timestamp from the latest block using the provider.
  • If the current timestamp is less than the next post time, it returns an object indicating that execution is not allowed yet.
  • Attempts to fetch a random quote from the ZenQuotes API. It constructs a message string using the quote author and content if successful.
  • If the quote fetch fails, it returns an object indicating the failure.
  • Stores the current timestamp as the last post timestamp in storage.

Execution Result

  • If the execution is allowed (canExec: true), it constructs an array of call data objects.
  • Each call data object specifies the contract address (to) and the encoded function call data (data) for the postMessage function with the generated message as an argument.

Return Value

  • The function returns an object with canExec indicating whether execution is allowed, and callData containing the transaction data for contract function calls. If execution is not allowed, it also includes a message field with an explanation.

This script essentially defines the logic for a Web3Function that posts a random quote message to an Ad Board smart contract at regular intervals, leveraging off-chain data and on-chain transactions.

Testing Web3 Function Using the Web3 Function command

A quick way to see the results of the Web3 Function, without setting the testing environment is by using the W3f command; you will need to pass the path to our Web3 Function, the chain-id, where we are testing, and the user arguments and storage if any.

npx w3f test web3-functions/advertising-board/index.ts --logs --chain-id=1

Creating and Executing Task

We have set the Web3 Function, now to execute the task we need to create scripts that are defined in the create-task-ad-board.ts file inside the scripts folder.

Note: if Web3 Functions take any arguments, then they should be passed under web3FunctionArgs. In this case, copy and paste the value from userArgs.json the file from advertising-board web3 function.

This script performs the following actions using the Automate SDK and other libraries:

Instantiate Provider & Signer:

  • Create a JSON-RPC provider using the specified provider URL.
  • Obtain the chain ID by querying the network using the provider.
  • Create a wallet instance using the specified private key and provider.
  • Instantiate the Automate SDK with the obtained chain ID and wallet.

Deploy Web3Function on IPFS:

  • Specify the path to the TypeScript file containing the Web3Function code (index.ts in the "web3-functions/simple" directory).
  • Deploy the Web3Function to IPFS using the Web3FunctionBuilder.deploy method.
  • Print the IPFS CID (Content ID) of the deployed Web3Function.

Create Automate Task:

  • Create an Automate task (batch execution task) using the automate.createBatchExecTask method.
  • Provide details such as task name, Web3Function hash (CID), Web3Function arguments, and trigger settings.
  • The trigger is set to execute the task at regular intervals (every 60 seconds in this case).
  • Wait for the transaction to be mined and print the task ID along with the transaction hash.
  • Provide a link to view the task on the Gelato Network beta application.

This script essentially deploys a Web3Function to IPFS and creates an Automate task that executes this function at specified intervals.

To execute scripts, make sure the account contains enough balance to perform transactions on the network. To fund your account, navigate to your sandbox dashboard and use the faucet to transfer tokens.

Run the scripts using the command below:

ts-node scripts/create-task-ad-board.ts

This command stores the Web3Function on IPFS and generates a task ID, as illustrated above.

Now, navigate to our Sandbox Explorer to inspect the transaction.

To cancel a task, create a new file inside the scripts folder named ‘cancel-task.ts’ and use the following script to cancel the task which is just executed by passing your TaskID as a string in cancelTask method.

To execute the above cancellation task, run the command below:

ts-node scripts/cancel-task.ts

Conclusion

Congratulations on completing this tutorial and exploring the power of automation in smart contracts using Gelato Web3 Functions on BuildBear Sandbox! Explore all other Web3 Functions in the template and experience the power of automation in smart contracts to enhance DApp capabilities. Leveraging Gelato Web3 Functions using Buildbear sandbox allows developers to automate tasks on DApps effectively and identify any potential issues or optimizations needed before deploying their applications to production.

Simplify DApp development and testing with BuildBear!

BuildBear empowers you with:

  • Instant Sandboxes with replication of mainnet states: Create instant custom sandbox replicating mainnet experience for thorough testing and simulation of real-world scenarios before deployment.
  • Dedicated Faucets: Never run out of test funds with built-in faucets for each sandbox.
  • Blazing Fast Transactions: Experience lightning-fast transaction speeds for smooth development and testing.
  • User-Friendly Explorer: Debug with ease using a clear and intuitive blockchain explorer.
  • Plus, many more features: Explore a comprehensive suite of tools and plugin functionalities to streamline your DApp development workflow.

Connect with us on Twitter | LinkedIn | Telegram | GitHub

--

--

BuildBear Team
BuildBear Labs

BuildBear Team, helping users test their dApps at Scale