Gelato
  • Introduction
    • Gelato, The Web3 Cloud Platform
  • Smart Wallets
    • Introduction
      • Understanding EIP-7702
      • Understanding ERC-4337
      • ERC-4337 vs EIP-7702
    • Templates & Examples
    • How-To Guides
      • Create a Sponsor API Key
      • Sponsor gas for your users
      • Allow users to pay gas with erc20
      • Allow users to pay gas with native
      • Create Dynamic's Environment Id
      • Use Dynamic/Privy signers with React SDK
      • Estimate Gas for your transactions
    • React SDK
    • Demo
    • Supported Networks
  • Rollup As A Service
    • Introduction
    • Rollup Stacks
      • Arbitrum Orbit
        • Run a Full Orbit Node
      • OP Stack
        • Run OP Node
    • Deploy your Rollup
    • Customization
      • Data Availability
        • Celestia
        • Avail
        • Eigen DA
      • Custom Gas Token
      • Marketplace
        • Gelato Services
        • Data Indexers
        • Block Explorers
        • Oracles
        • Bridges
        • Account Abstraction
        • On & Off-ramp
        • Community
        • Identity & KYC
        • Others
      • Verifier Node Package
    • Public Testnet
  • RPC Nodes
    • Introduction
    • Compute Units
    • Using RPC Nodes
    • Supported Networks
    • Pricing and Plans
    • FAQ
  • Web3 Services
    • Web3 Functions
      • Understanding Web3 Functions
        • Trigger Types
        • Typescript Function
        • Solidity Function
        • Automated Transactions
      • Security Considerations
      • Template & Use Cases
      • Quick Start
        • Writing Typescript Functions
          • Event Trigger
          • Private Typescript Functions
          • Callbacks
        • Test, Deploy & Run Typescript functions
        • Writing Solidity Functions
        • Test, Deploy & Run Solidity Functions
        • Initiate an Automated Transaction
      • Create a Web3 Function Task
        • Using the UI
        • Using the Safe App
        • Using a Smart Contract
        • Using the Automate SDK
      • Analytics & Monitoring
      • Supported Networks
      • Subscription & Payments
      • Legacy Automate Migration Guide
    • Relay
      • What is Relaying?
      • Security Considerations
        • ERC-2771 Delegatecall Vulnerability
      • Templates
      • Quick Start
        • Sponsored Calls
        • Non-Sponsored Calls
      • ERC-2771 (recommended)
        • SponsoredCallERC2771
        • CallWithSyncFeeERC2771
          • Relay Context Contracts ERC2771
      • Non-ERC-2771
        • SponsoredCall
        • CallWithSyncFee
          • Relay Context Contracts
      • Relay API
      • Gelato's Fee Oracle
      • Tracking your Relay Request
      • Supported Networks
      • Subscriptions and Payments
        • 1Balance & Relay
        • SyncFee Payment Tokens
        • Relay Pricing
      • ERC2771 Migration Guide
    • VRF
      • Understanding VRF
      • How does Gelato VRF Work?
      • Security Considerations
      • Template
      • Quick Start
      • Create a VRF Task
        • Create a Fallback VRF
        • Migrating from Chainlink VRF
      • Supported Networks
      • Pricing & Rate Limits
    • Oracles
      • Understanding Gelato Oracles
      • Quick Start
      • Data Providers
        • Stork
        • Choas Labs
      • Migrating from Chainlink Oracles
      • Available Price Feeds
      • Supported Networks
      • Pricing & Rate Limits
    • Account Abstraction
      • Understanding ERC-4337
      • Introduction to Gelato Bundler
      • Templates & Examples
      • Quick Start
      • Supported Networks
      • Bundler API Endpoints
        • eth_sendUserOperation
        • eth_estimateUserOperationGas
        • eth_getUserOperationByHash
        • eth_getUserOperationReceipt
        • eth_supportedEntryPoints
        • eth_maxPriorityFeePerGas
        • eth_chainId
    • 1Balance
      • 1Balance Alerts
      • Subscription Plans
      • Subscription Notifications
      • USDC Addresses
    • AI Agents
    • Teams
  • GELATO DAO
    • DAO & Token (GEL)
    • GEL Token Contracts
    • Governance Process
  • Social Media
Powered by GitBook
On this page
  • Overview
  • Paying for Transactions
  • Setting maxFee for Your Transaction
  • SDK method: callWithSyncFee
  • Sending a Request
  • Request Body
  • Example Code GelatoRelayContext
  • 1. Deploy a GelatoRelayContext compatible contract
  • 2. Import GelatoRelaySDK into your front-end .js project
  • 3. Send the payload to Gelato
  1. Web3 Services
  2. Relay
  3. Non-ERC-2771

CallWithSyncFee

Permissionless transactions with on-chain payments

PreviousSponsoredCallNextRelay Context Contracts

Last updated 1 month ago

After reading this page:

  • You'll know how to use the callWithSyncFee SDK method, using the payment method.

  • You'll see some code which will help you send a relay request within minutes.

  • You'll learn how to pay for transactions using the provided values for fee, feeToken and feeCollector.

Please proceed to our page and read it thoroughly before advancing with your implementation. It is crucial to understand all potential security risks and measures to mitigate them.

Overview

The callWithSyncFee method uses the payment method.

Paying for Transactions

When using callWithSyncFee relay method the target contract assumes responsibility for transferring the fee to Gelato's fee collector during transaction execution. For this, the target contract needs to know:

  • fee: the transfer amount

  • feeToken: the token to be transferred

  • feeCollector: the destination address for the fee

Fortunately, Gelato provides some useful tools within the :

  1. By inheriting the contract in your target contract, you have the ability to transfer the fee through one of two straightforward methods: _transferRelayFee() or _transferRelayFeeCapped(uint256 maxFee). In either case, the inherited contract takes care of decoding the fee, feeToken, and feeCollector behind the scenes. The Gelato Relay backend simplifies the process by automatically calculating the fee for you, using Gelato's Fee Oracle to perform the calculations in the background.

  2. Alternatively, you may choose to inherit the contract. With this approach, Gelato only decodes the feeCollector. You must provide the fee and feeToken on-chain, either by hardcoding them (which is not recommended) or embedding them within the payload to be executed. The suggested way to handle this is to calculate the fee with .

Setting maxFee for Your Transaction

SDK method: callWithSyncFee

const callWithSyncFee = async (
  request: CallWithSyncFeeRequest,
  options?: RelayRequestOptions,
  apiKey?: string
): Promise<RelayResponse>

Arguments:

  • options: RelayRequestOptions is an optional object.

Return Object: RelayResponse

type RelayResponse = {
  taskId: string;
};

Optional Parameters

type RelayRequestOptions = {
  gasLimit?: BigNumberish;
  retries?: number;
};
  • gasLimit: the gas limit of the relay call. This effectively sets an upper price limit for the relay call.

    • If you are using your own custom gas limit, please add a 150k gas buffer on top of the expected gas usage for the transaction. This is for the Gelato Relay execution overhead, and adding this buffer reduces your chance of the task cancelling before it is executed on-chain.

    • If your contract has any hardcoded requirements about gas usage, please always explicitly pass the gasLimit to the SDK/API, as Gelato will not know what hardcoded gas expectations your contract has. Otherwise, your relay requests might not be executable.

  • retries: the number of retries that Gelato should attempt before discarding this relay call. This can be useful if the state of the target contract is not fully known and such reverts can not be definitively avoided.

Sending a Request

Request Body

const request = {
  chainId: BigNumberish;
  target: string;
  data: BytesLike;
  isRelayContext?: boolean;
  feeToken: string;
};
  • chainId: the chain ID of the chain where the target smart contract is deployed.

  • target: the address of the target smart contract.

  • data: encoded payload data (usually a function selector plus the required arguments) used to call the required target address.

  • isRelayContext: an optional boolean (default: true) denoting what data you would prefer appended to the end of the calldata.

Example Code GelatoRelayContext

1. Deploy a GelatoRelayContext compatible contract

// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;

import {
    GelatoRelayContext
} from "@gelatonetwork/relay-context/contracts/GelatoRelayContext.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";

// Inheriting GelatoRelayContext gives access to:
// 1. _getFeeCollector(): returns the address of Gelato's feeCollector
// 2. _getFeeToken(): returns the address of the fee token
// 3. _getFee(): returns the fee to pay
// 4. _transferRelayFee(): transfers the required fee to Gelato's feeCollector.abi
// 5. _transferRelayFeeCapped(uint256 maxFee): transfers the fee to Gelato
//    only if fee < maxFee
// 6. _getMsgData(): returns the original msg.data without appended information
// 7. onlyGelatoRelay modifier: allows only Gelato Relay's smart contract
//    to call the function
contract CounterRelayContext is GelatoRelayContext {
    using Address for address payable;

    uint256 public counter;

    event IncrementCounter(uint256 newCounterValue);

    // `increment` is the target function to call.
    // This function increments a counter variable by 1
    // IMPORTANT: with `callWithSyncFee` you need to implement 
    // your own smart contract security measures, as this 
    // function can be called by any third party and not only by 
    // Gelato Relay. If not done properly, funds kept in this
    // smart contract can be stolen.
    function increment() external onlyGelatoRelay {
        // Remember to autheticate your call since you are not using ERC-2771
        // _yourAuthenticationLogic()

        // Payment to Gelato
        // NOTE: be very careful here!
        // if you do not use the onlyGelatoRelay modifier,
        // anyone could encode themselves as the fee collector
        // in the low-level data and drain tokens from this contract.
        _transferRelayFee();

        counter++;

        emit IncrementCounter(counter);
    }

    // `incrementFeeCapped` is the target function to call.
    // This function uses `_transferRelayFeeCapped` method to ensure 
    // better control of gas fees. If gas fees are above the maxFee value 
    // the transaction will not be executed.
    // This function increments a counter variable by 1
    // IMPORTANT: with `callWithSyncFee` you need to implement 
    // your own smart contract security measures, as this 
    // function can be called by any third party and not only by 
    // Gelato Relay. If not done properly, funds kept in this
    // smart contract can be stolen.
    function incrementFeeCapped(uint256 maxFee) external onlyGelatoRelay {
        // Remember to autheticate your call since you are not using ERC-2771
        // _yourAuthenticationLogic()

        // Payment to Gelato
        // NOTE: be very careful here!
        // if you do not use the onlyGelatoRelay modifier,
        // anyone could encode themselves as the fee collector
        // in the low-level data and drain tokens from this contract.
       
          _transferRelayFeeCapped(maxFee);

        counter++;

        emit IncrementCounter(counter);
    }
}

2. Import GelatoRelaySDK into your front-end .js project

import { GelatoRelay, CallWithSyncFeeRequest } from "@gelatonetwork/relay-sdk";
const relay = new GelatoRelay();

3. Send the payload to Gelato

// set up target address and function signature abi
const counter = "<your counter contract address>"; 
const abi = ["function increment()"];

// generate payload using front-end provider such as MetaMask
const provider = new ethers.BrowserProvider(window.ethereum);
const signer = provider.getSigner();

// address of the token to pay fees
const feeToken = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";

// instantiate the target contract object
const contract = new ethers.Contract(counterAddress, abi, signer);

// example callig the increment() method
const { data } = await contract.populateTransaction.increment();

// populate the relay SDK request body
const request: CallWithSyncFeeRequest = {
  chainId: (await provider.getNetwork()).chainId,
  target: counter,
  data: data,
  feeToken: feeToken,
  isRelayContext: true,
};
  
// send relayRequest to Gelato Relay API
const relayResponse = await relay.callWithSyncFee(request);

// -----------------------------------------------------------------
// the following is an alternative example using Gelato Fee Oracle, 
// setting maxFee, and calling the incrementFeeCapped(maxFee) method

// retrieve the estimate fee from the Gelato 

const fee = await relay.getEstimatedFee(
  (await provider.getNetwork()).chainId,
  feeToken,
  gasLimit,
  false,
)

const maxFee = fee * 2 // you can use 2x or 3x to set your maxFee

// example calling the incrementFeeCapped(maxFee) method
const { dataMaxFee } = await contract.incrementFeeCapped.populateTransaction(maxFee);

// populate the relay SDK request body
const requestMaxFee: CallWithSyncFeeRequest = {
  chainId: (await provider.getNetwork()).chainId,
  target: counter,
  data: dataMaxFee,
  feeToken: feeToken,
  isRelayContext: true,
};
  
// send relayRequest to Gelato Relay API
const relayResponse = await relay.callWithSyncFee(requestMaxFee);

Setting a maximum fee, or maxFee, for your transactions is strongly advised. This practice enables you to ensure that transaction costs remain below a specific limit. The method _transferRelayFeeCapped(uint256 maxFee) in the contract provides a convenient way to set the maxFee easily.

If you are utilizing the contract, the recommended way to pass the maxFee is by calculating the fee with , which is accessible in the . The getEstimatedFee() method is provided to facilitate this calculation.

request: this is the used to send a request.

apiKey: this is an optional API key that links your request to your Gelato Relay account. As this pertains to the payment method, transaction costs won't be deducted from your 1Balance account. By using the API key, you can benefit from increased rate limits of your Gelato Relay account.

taskId: your unique relay task ID which can be used for .

If set to true (default), Gelato Relay will append the feeCollector address, the feeToken address, and the uint256 fee to the calldata. This requires the target contract to inherit the contract.

If set to false, Gelato Relay will only append the feeCollector address to the calldata. In this case the contract to be inherit by the target contract is the .

feeToken: the address of the token that is to be used for payment. Please visit for the full list of supported payment tokens per network.

tracking your request
SyncFee Payment Tokens
request body
GelatoRelayContext
Gelato's Fee Oracle
relay-sdk
GelatoRelayFeeCollector
GelatoRelayContext
GelatoRelayFeeCollector
Security Considerations
Relay Context Contracts
Gelato's Fee Oracle
GelatoRelayContext
GelatoRelayFeeCollector
syncFee
syncFee
syncFee