Skip to content

Commit 7f639e7

Browse files
authored
Merge pull request #2324 from anirudhmakhana/main
[chore]: add gelato guide for relay and w3f
2 parents 89217d1 + 392ab63 commit 7f639e7

File tree

2 files changed

+249
-0
lines changed

2 files changed

+249
-0
lines changed
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
---
2+
description: >-
3+
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.
4+
---
5+
6+
# Contract Automation
7+
8+
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.
9+
10+
## Available automation services
11+
12+
### [Gelato](https://gelato.network/)
13+
14+
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.
15+
16+
#### **How Gelato Web3 functions work?**
17+
18+
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.
19+
20+
**Off-chain Data or Computation?**
21+
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.
22+
23+
**All Checks On-chain?**
24+
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
25+
26+
## Triggers
27+
28+
1. Time Interval
29+
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.
30+
2. Cron Expressions
31+
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.
32+
3. On-Chain Event
33+
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.
34+
4. Every Block
35+
This function operates with the rhythm of the blockchain itself, executing your chosen function each time a new block is created.
36+
37+
## What to Execute?
38+
39+
<!-- <Figure src={require('/docs/build/zkEVM/integrations/automation-off-chain/img/functions.png').default} width="100%" /> -->
40+
41+
### Typescript Functions
42+
43+
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.
44+
45+
### Solidity Functions
46+
47+
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.
48+
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.
49+
50+
### Automated Transaction
51+
52+
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.
53+
54+
#### **What is dedicatedMsgSender?**
55+
56+
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.
57+
58+
## Quick Start
59+
60+
### Writing & Deploying Typescript Functions
61+
62+
1. Clone the hardhat-template repo
63+
64+
```shell
65+
git clone web3-functions-hardhat-template
66+
```
67+
68+
2. CD into the folder and install
69+
70+
```shell
71+
cd web3-functions-hardhat-template && yarn install
72+
```
73+
74+
3. Update the `index.ts` in one of the examples
75+
76+
```typescript
77+
Web3Function.onRun(async (context: Web3FunctionContext) => {
78+
const { userArgs, multiChainProvider } = context;
79+
80+
const provider = multiChainProvider.default();
81+
// Retrieve Last oracle update time
82+
const oracleAddress =
83+
(userArgs.oracle as string) ?? "0x71B9B0F6C999CBbB0FeF9c92B80D54e4973214da";
84+
85+
// YOUR CUSTOM LOGIC
86+
.....
87+
88+
// Return if nothing has to be pushed on-chain
89+
return { canExec: false, message: `Coingecko call failed` };
90+
91+
// Return if tx has to be pushed on-chain
92+
return {
93+
canExec: true,
94+
callData: [
95+
{
96+
to: oracleAddress,
97+
data: oracle.interface.encodeFunctionData("updatePrice", [price]),
98+
},
99+
],
100+
};
101+
});
102+
```
103+
104+
4. Deploy the Web3 Function to IPFS and create the Task
105+
106+
```shell
107+
npx w3f deploy web3-functions/YOUR-FUNCTION/index.ts
108+
```
109+
110+
Result:
111+
112+
```shell
113+
$ npx w3f deploy web3-functions/YOUR-FUNCTION/index.ts
114+
✓ Web3Function deployed to ipfs.
115+
✓ CID: QmYMysfAhYYYrdhVytSTiE9phuoT49kMByktXSbVp1aRPx
116+
117+
To create a task that runs your Web3 Function every minute, visit:
118+
> https://beta.app.gelato.network/new-task?cid=QmYMysfAhYYYrdhVytSTiE9phuoT49kMByktXSbVp1aRPx
119+
✨ Done in 3.56s.
120+
```
121+
122+
Finally, go to the [Gelato App](https://app.gelato.network), create a new task, decide on the trigger, and input the CID.
123+
124+
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).
125+
126+
#### **Further Resources**
127+
128+
- [Gelato Web3 Functions Docs](https://docs.gelato.network/web3-services/web3-functions)
129+
- [What is 1Balance?](https://docs.gelato.network/web3-services/1balance)
130+
- [Github Repository](https://github.com/gelatodigital/how-tos-3-w3f-triggers)
131+
- [YouTube - How to write Event driven Web3 Functions](https://www.youtube.com/watch?v=7UpqGsANsBQ&ab_channel=JavierDonoso)

smart-contracts/advanced/relay.md

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
---
2+
description: >-
3+
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.
4+
---
5+
6+
# Relay
7+
8+
## Meta Transactions
9+
10+
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.
11+
12+
## Available relayers
13+
14+
There are several relayers available that support meta transactions on the Filecoin network. Builders can integrate these relayers into their applications today.
15+
16+
### [Gelato](https://gelato.network/)
17+
18+
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.
19+
20+
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.
21+
22+
### Use cases
23+
24+
- Highlight.xyz: Allows users to mint NFTs without incurring gas fees.
25+
- ZED RUN: Automates breeding processes for digital racehorses.
26+
- Reya: Enable gasless trading on the platform
27+
28+
#### Off-chain and on-chain payments
29+
30+
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.
31+
32+
##### Off-chain payments
33+
34+
- **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.
35+
36+
- **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.
37+
38+
##### On-chain payments
39+
40+
- **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.
41+
42+
- **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.
43+
44+
### Implementation
45+
46+
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.
47+
48+
#### Step 1: Inherit Context Contract
49+
50+
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.
51+
52+
```solidity
53+
import {
54+
ERC2771Context
55+
} from "@gelatonetwork/relay-context/contracts/vendor/ERC2771Context.sol";
56+
57+
contract CounterERC2771 is ERC2771Context {
58+
59+
// ERC2771Context: setting the immutable trustedForwarder variable
60+
constructor(address trustedForwarder) ERC2771Context(trustedForwarder) {}
61+
62+
function incrementContext() external {
63+
64+
// Incrementing the counter mapped to the _msgSender!
65+
contextCounter[_msgSender()]++;
66+
67+
// Emitting an event for testing purposes
68+
emit IncrementContextCounter(_msgSender());
69+
}
70+
}
71+
```
72+
73+
#### Step 2: Import the relay SDK
74+
75+
In your frontend/backend, you would need to import and instantiate the relay class.
76+
77+
```
78+
import { GelatoRelay, SponsoredCallERC2771Request } from "@gelatonetwork/relay-sdk";
79+
const relay = new GelatoRelay(API_KEY);
80+
```
81+
82+
#### Step 3: Send the payload to Gelato
83+
84+
This is an example using Gelato's CounterERC2771.sol, which is deployed on these networks.
85+
86+
```
87+
// Set up on-chain variables, such as target address
88+
const counter = "0x00172f67db60E5fA346e599cdE675f0ca213b47b";
89+
const abi = ["function incrementContext()"];
90+
const provider = new ethers.BrowserProvider(window.ethereum);
91+
const signer = provider.getSigner();
92+
const user = signer.getAddress();
93+
94+
// Generate the target payload
95+
const contract = new ethers.Contract(counter, abi, signer);
96+
const { data } = await contract.incrementContext.populateTransaction();
97+
98+
// Populate a relay request
99+
const request: CallWithERC2771Request = {
100+
chainId: (await provider.getNetwork()).chainId,
101+
target: counter;
102+
data: data;
103+
user: user;
104+
};
105+
106+
// Without a specific API key, the relay request will fail!
107+
// Go to https://relay.gelato.network to get a testnet API key with 1Balance.
108+
// Send a relay request using Gelato Relay!
109+
const relayResponse = await relay.sponsoredCallERC2771(request, provider, apiKey);
110+
```
111+
112+
#### Further Gelato resources
113+
114+
- [Gelato Relay Docs](https://docs.gelato.network/web3-services/relay)
115+
- [What is 1Balance?](https://docs.gelato.network/web3-services/1balance)
116+
- [YouTube - ERC2771](https://www.youtube.com/watch?v=P6LlzSzta1Q)
117+
- [YouTube - non-ERC2771](https://youtu.be/shqLPDerunY)
118+
- [GitHub Repository](https://github.com/gelatodigital/how-tos-5-6-7-8-relay-intro-methods)

0 commit comments

Comments
 (0)