-
Notifications
You must be signed in to change notification settings - Fork 297
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #2324 from anirudhmakhana/main
[chore]: add gelato guide for relay and w3f
- Loading branch information
Showing
2 changed files
with
249 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
--- | ||
description: >- | ||
Smart contract automation enables decentralized applications (dapps) to interact with both on-chain and off-chain data in an automated and trustless manner. Automation tools allow developers to build smart contracts that execute predefined actions based on external triggers, eliminating the need for manual intervention while ensuring secure and reliable execution. | ||
--- | ||
|
||
# Contract Automation | ||
|
||
In the Filecoin network, smart contracts benefit from a secure, deterministic environment. While this ensures reliability, it also limits direct access to external data sources. However, developers can leverage automation services to seamlessly connect off-chain data with on-chain smart contracts. This unlocks advanced capabilities such as price feeds, data verification, and much more, empowering Filecoin dapps with dynamic, real-world functionality by integrating external data into on-chain logic. | ||
|
||
## Available automation services | ||
|
||
### [Gelato](https://gelato.network/) | ||
|
||
Gelato's Web3 Functions is a powerful automation system designed to streamline and enhance Web3 operations. Web3 Functions serve as a comprehensive tool, enabling developers to effortlessly set up, manage, and automate their smart contract tasks. | ||
|
||
#### **How Gelato Web3 functions work?** | ||
|
||
Web3 Functions can be triggered by various events and allow developers to write both off-chain logic (TypeScript) and on-chain logic (Solidity). Once deployed, they handle automated smart contract interactions, providing real-time monitoring and flexibility. | ||
|
||
**Off-chain Data or Computation?** | ||
Sometimes, automation tasks require data that isn't readily available on the blockchain, or they might need computations that are better performed off-chain. In such cases, Typescript Functions should be the choice. | ||
|
||
**All Checks On-chain?** | ||
If all the conditions necessary for your automation task can be directly verified on the blockchain, you have the option to select between Typescript Functions, Solidity Functions & Automated Transactions | ||
|
||
## Triggers | ||
|
||
1. Time Interval | ||
Use this trigger to execute tasks at regular intervals, e.g., every 10 minutes or once every 24 hours. It's like setting a straightforward, recurring alarm. | ||
2. Cron Expressions | ||
This offers a more refined control compared to the Time Interval. With cron expressions, you can set tasks to run at specific moments, such as "every Tuesday at 3 PM" or "on the 1st of every month". It gives you precision in task scheduling. | ||
3. On-Chain Event | ||
Ideal for those wanting their tasks to respond dynamically to blockchain activities. Whenever a specified event occurs on the blockchain, this trigger springs your task into action. It's like a vigilant watcher, always ready to act. | ||
4. Every Block | ||
This function operates with the rhythm of the blockchain itself, executing your chosen function each time a new block is created. | ||
|
||
## What to Execute? | ||
|
||
<!-- <Figure src={require('/docs/build/zkEVM/integrations/automation-off-chain/img/functions.png').default} width="100%" /> --> | ||
|
||
### Typescript Functions | ||
|
||
Typescript Functions are decentralized cloud functions that work similarly to AWS Lambda or Google Cloud, just for web3. They enable developers to execute on-chain transactions based on arbitrary off-chain data (APIs / subgraphs, etc) & computation. These functions are written in Typescript, stored on IPFS and run by Gelato. | ||
|
||
### Solidity Functions | ||
|
||
Solidity Functions are crucial for making on-chain tasks automatic and more efficient. They connect set conditions with specific actions in a smart contract, providing a straightforward method to turn user needs into automated processes. | ||
Consider them as a set of "if-then" rules: If certain conditions are met on the blockchain, then a specific function gets executed. This level of automation ensures that the decentralized application can operate with minimal manual intervention, providing a seamless user experience. | ||
|
||
### Automated Transaction | ||
|
||
Automated Transaction ensures that a specific function on the target smart contract gets reliably triggered. When you pre-define the inputs, it means that every time Gelato initiates the function call, it uses consistent, predetermined arguments. | ||
|
||
#### **What is dedicatedMsgSender?** | ||
|
||
For security reasons, during task creation, you will see an address that acts as the msg.sender for your task executions. This address is a proxy contract deployed by Gelato. It ensures that every task execution on behalf of your contract uses this dedicated msg.sender address, which is essential for validating the origin of the task. | ||
|
||
## Quick Start | ||
|
||
### Writing & Deploying Typescript Functions | ||
|
||
1. Clone the hardhat-template repo | ||
|
||
```shell | ||
git clone web3-functions-hardhat-template | ||
``` | ||
|
||
2. CD into the folder and install | ||
|
||
```shell | ||
cd web3-functions-hardhat-template && yarn install | ||
``` | ||
|
||
3. Update the `index.ts` in one of the examples | ||
|
||
```typescript | ||
Web3Function.onRun(async (context: Web3FunctionContext) => { | ||
const { userArgs, multiChainProvider } = context; | ||
|
||
const provider = multiChainProvider.default(); | ||
// Retrieve Last oracle update time | ||
const oracleAddress = | ||
(userArgs.oracle as string) ?? "0x71B9B0F6C999CBbB0FeF9c92B80D54e4973214da"; | ||
|
||
// YOUR CUSTOM LOGIC | ||
..... | ||
|
||
// Return if nothing has to be pushed on-chain | ||
return { canExec: false, message: `Coingecko call failed` }; | ||
|
||
// Return if tx has to be pushed on-chain | ||
return { | ||
canExec: true, | ||
callData: [ | ||
{ | ||
to: oracleAddress, | ||
data: oracle.interface.encodeFunctionData("updatePrice", [price]), | ||
}, | ||
], | ||
}; | ||
}); | ||
``` | ||
|
||
4. Deploy the Web3 Function to IPFS and create the Task | ||
|
||
```shell | ||
npx w3f deploy web3-functions/YOUR-FUNCTION/index.ts | ||
``` | ||
|
||
Result: | ||
|
||
```shell | ||
$ npx w3f deploy web3-functions/YOUR-FUNCTION/index.ts | ||
✓ Web3Function deployed to ipfs. | ||
✓ CID: QmYMysfAhYYYrdhVytSTiE9phuoT49kMByktXSbVp1aRPx | ||
|
||
To create a task that runs your Web3 Function every minute, visit: | ||
> https://beta.app.gelato.network/new-task?cid=QmYMysfAhYYYrdhVytSTiE9phuoT49kMByktXSbVp1aRPx | ||
✨ Done in 3.56s. | ||
``` | ||
|
||
Finally, go to the [Gelato App](https://app.gelato.network), create a new task, decide on the trigger, and input the CID. | ||
|
||
For a detailed guide on creating and deploying Web3 Functions, including setting up your development environment, triggers, and security configurations, refer to the full developer guide [here](https://docs.gelato.network/web3-services/web3-functions/quick-start/writing-typescript-functions). | ||
|
||
#### **Further Resources** | ||
|
||
- [Gelato Web3 Functions Docs](https://docs.gelato.network/web3-services/web3-functions) | ||
- [What is 1Balance?](https://docs.gelato.network/web3-services/1balance) | ||
- [Github Repository](https://github.com/gelatodigital/how-tos-3-w3f-triggers) | ||
- [YouTube - How to write Event driven Web3 Functions](https://www.youtube.com/watch?v=7UpqGsANsBQ&ab_channel=JavierDonoso) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
--- | ||
description: >- | ||
Relay is a service that allows users to interact with the Filecoin network using meta transactions. Users can submit transactions to the network without having to pay gas fees. Instead, a relayer pays the gas fees on behalf of the user. This enables users to interact with the network without having to hold FIL tokens or manage their own wallets. | ||
--- | ||
|
||
# Relay | ||
|
||
## Meta Transactions | ||
|
||
Meta transactions are a type of transaction that allows users to interact with the Filecoin network without having to pay for gas fees. Instead, a third party, known as a relayer, pays the gas fees on behalf of the user. This enables users to interact with the network without having to hold FIL tokens or manage their own wallets. | ||
|
||
## Available relayers | ||
|
||
There are several relayers available that support meta transactions on the Filecoin network. Builders can integrate these relayers into their applications today. | ||
|
||
### [Gelato](https://gelato.network/) | ||
|
||
Relay services, like Gelato Relay, act as intermediaries that handle the submission of meta-transactions to the blockchain. By integrating relay contracts (such as GelatoRelayContext or ERC2771Context) into a smart contract, developers can enable gasless transactions. This allows users to interact with decentralized applications without holding native tokens, while maintaining security through features like EIP-712 signature validation. | ||
|
||
The relayer ensures the transaction is executed securely and promptly, handling the gas fee payment either off-chain (via a sponsor) or on-chain (with the user’s funds). This system simplifies blockchain interactions, broadening accessibility and reducing friction for dapp users. | ||
|
||
### Use cases | ||
|
||
- Highlight.xyz: Allows users to mint NFTs without incurring gas fees. | ||
- ZED RUN: Automates breeding processes for digital racehorses. | ||
- Reya: Enable gasless trading on the platform | ||
|
||
#### Off-chain and on-chain payments | ||
|
||
Transactions can be paid for in two primary ways: off-chain payments and on-chain payments. Each method offers flexibility depending on how developers wish to handle transaction fees for their users. | ||
|
||
##### Off-chain payments | ||
|
||
- **SponsoredCallERC2771**: In this method, Gelato uses the ERC-2771 meta-transaction standard to allow gasless transactions. The user signs a message, and the relay service covers the gas fees. ERC-2771Context ensures that the user’s identity is verified off-chain, by encoding the user’s address in the last 20 bytes of the transaction. This provides a secure, gasless experience where Gelato, using its 1Balance, sponsors the transaction fee. | ||
|
||
- **SponsoredCall**: When there is no need for ERC-2771's off-chain signature verification, this more flexible method can be used. The transaction fees are still covered by the sponsor using 1balance, but the responsibility for managing security measures such as signature validation and replay protection lies with the project. This option is ideal for use cases that already have built-in security mechanisms. | ||
|
||
##### On-chain payments | ||
|
||
- **callWithSyncFeeERC2771**: This method combines ERC-2771 meta-transaction functionality with Gelato’s SyncFee model. The user’s gas fee is calculated and paid directly from the smart contract during the transaction execution. Gelato’s Fee Oracle estimates the fee in real-time, and the GelatoRelayContext contract automatically handles the fee transfer. This is ideal for developers who want to maintain user signature verification while ensuring users cover their transaction costs. | ||
|
||
- **callWithSyncFee**: This method is similar to callWithSyncFeeERC2771 but without the need for ERC-2771’s off-chain signature verification. The user’s gas fee is calculated and paid directly from the target smart contract during the transaction execution. This approach is useful for applications where users are expected to pay for their own gas without requiring meta-transaction features. | ||
|
||
### Implementation | ||
|
||
We will require three simple steps to implement Gelato Relay. Here, we are going to showcase the three steps required to implement the method `sponsoredCallERC2771`, which is the most used one. | ||
|
||
#### Step 1: Inherit Context Contract | ||
|
||
Depending on the method, you must inherit different contracts as they will provide other methods. In this case, we will have to inherit the `ERC2771Context`. The `ERC2771Context` provide us with the methods `_msgSender()` and `_msgData()` that will allow us to recover the original user sending the transaction. | ||
|
||
```solidity | ||
import { | ||
ERC2771Context | ||
} from "@gelatonetwork/relay-context/contracts/vendor/ERC2771Context.sol"; | ||
contract CounterERC2771 is ERC2771Context { | ||
// ERC2771Context: setting the immutable trustedForwarder variable | ||
constructor(address trustedForwarder) ERC2771Context(trustedForwarder) {} | ||
function incrementContext() external { | ||
// Incrementing the counter mapped to the _msgSender! | ||
contextCounter[_msgSender()]++; | ||
// Emitting an event for testing purposes | ||
emit IncrementContextCounter(_msgSender()); | ||
} | ||
} | ||
``` | ||
|
||
#### Step 2: Import the relay SDK | ||
|
||
In your frontend/backend, you would need to import and instantiate the relay class. | ||
|
||
``` | ||
import { GelatoRelay, SponsoredCallERC2771Request } from "@gelatonetwork/relay-sdk"; | ||
const relay = new GelatoRelay(API_KEY); | ||
``` | ||
|
||
#### Step 3: Send the payload to Gelato | ||
|
||
This is an example using Gelato's CounterERC2771.sol, which is deployed on these networks. | ||
|
||
``` | ||
// Set up on-chain variables, such as target address | ||
const counter = "0x00172f67db60E5fA346e599cdE675f0ca213b47b"; | ||
const abi = ["function incrementContext()"]; | ||
const provider = new ethers.BrowserProvider(window.ethereum); | ||
const signer = provider.getSigner(); | ||
const user = signer.getAddress(); | ||
// Generate the target payload | ||
const contract = new ethers.Contract(counter, abi, signer); | ||
const { data } = await contract.incrementContext.populateTransaction(); | ||
// Populate a relay request | ||
const request: CallWithERC2771Request = { | ||
chainId: (await provider.getNetwork()).chainId, | ||
target: counter; | ||
data: data; | ||
user: user; | ||
}; | ||
// Without a specific API key, the relay request will fail! | ||
// Go to https://relay.gelato.network to get a testnet API key with 1Balance. | ||
// Send a relay request using Gelato Relay! | ||
const relayResponse = await relay.sponsoredCallERC2771(request, provider, apiKey); | ||
``` | ||
|
||
#### Further Gelato resources | ||
|
||
- [Gelato Relay Docs](https://docs.gelato.network/web3-services/relay) | ||
- [What is 1Balance?](https://docs.gelato.network/web3-services/1balance) | ||
- [YouTube - ERC2771](https://www.youtube.com/watch?v=P6LlzSzta1Q) | ||
- [YouTube - non-ERC2771](https://youtu.be/shqLPDerunY) | ||
- [GitHub Repository](https://github.com/gelatodigital/how-tos-5-6-7-8-relay-intro-methods) |