3⃣
sponsoredCallERC2771
SDK Method 2️⃣
WARNING: If you are using the deprecated method
relayWithSponsoredUserAuthCall,
please read the migration guide.After reading this page:
- You'll know how to use the
sponsoredCallERC2771
SDK method. This will give your user's a gasless UX requiring a user signature. This uses the 1Balance payment method, allowing you to sponsor some/all of your user's gas costs. - You'll see some code which will help you send a relay request within minutes.
sponsoredCallERC2771
utilises authentication both via sponsor api key and a user's signature (e.g. from MetaMask) to sponsor your user's gasless transaction securely. The payment method is Gelato 1Balance.const sponsoredCallERC2771 = async (
request: SponsoredCallERC2771Request,
provider: ethers.providers.Web3Provider,
sponsorApiKey: string,
options?: RelayRequestOptions
): Promise<RelayResponse>
provider
: a valid provider connected to RPC.sponsorApiKey
: an API key used to authenticate your sponsorship.options?
:RelayRequestOptions
is an optional request object
type RelayResponse = {
taskId: string;
};
const request = {
chainId: BigNumberish;
target: string;
data: BytesLike;
user: string;
userNonce?: BigNumberish;
userDeadline?: BigNumberish;
};
chainId
: the chain ID of the chain where thetarget
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 requiredtarget
address.user
: the address of the user's EOA.userNonce
: optional, this is a nonce similar to Ethereum nonces, stored in a local mapping on the relay contracts. It is used to enforce nonce ordering of relay calls, if the user requires it. Otherwise, this is an optional parameter and if not passed, the relay-SDK will automatically query on-chain for the current value.userDeadline
: optional, the amount of time in seconds that a user is willing for the relay call to be active in the relay backend before it is dismissed.- This way the user knows that if the transaction is not sent within a certain timeframe, it will expire. Without this, an adversary could pick up the transaction in the mempool and send it later. This could transfer money, or change state at a point in time which would be highly undesirable to the user.
For your testing, Gelato has deployed a simple contract which implements logic to increment a counter with ERC2771 support.
CounterERC2771.sol
: deployed at address0x30d97B13e29B0cd42e6ebd48dbD9063465bF1997
on these networks.
CounterERC2771.sol
's counter is special because it implements ERC-2771's _msgSender
authentication to allow for secure whitelisting based on the identity of the original off-chain relay request originator, which has been verified using a user signature. Furthermore, to set your trusted forwarder, you need the address for GelatoRelayERC2771:
GelatoRelayERC2771.sol
: deployed at address0xBf175FCC7086b4f9bd59d5EAE8eA67b8f940DE0d
on these networks.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import {
ERC2771Context
} from "@gelatonetwork/relay-context/contracts/vendor/ERC2771Context.sol";
// Importing ERC2771Context gives access to:
// 1. An immutable trusted forwarder address
// for Gelato Relay ERC2771, this is 0xBf175FCC7086b4f9bd59d5EAE8eA67b8f940DE0d
// 2. function isTrustedForwarder
// to verify an input address matches the trustedForwarder address
// 3. function _msgSender()
// which decodes the user's address from the calldata
// _msgSender() can now be used to refer to user safely
// instead of msg.sender (which is Gelato Relay in this case).
// 4. function _msgData()
// which decodes the function signature from the calldata
contract CounterERC2771 is ERC2771Context {
// Here we have a mapping that maps a counter to an address
mapping(address => uint256) public contextCounter;
event IncrementContextCounter(address _msgSender);
// A modifier that only allows the trustedForwarder to call
// the required target function: `incrementContext`
modifier onlyTrustedForwarder() {
require(
isTrustedForwarder(msg.sender),
"Only callable by Trusted Forwarder"
);
_;
}
// ERC2771Context: setting the immutable trustedForwarder variable
constructor(address trustedForwarder) ERC2771Context(trustedForwarder) {}
// `incrementContext` is the target function to call
// This function increments a counter variable which is
// mapped to every _msgSender(), the address of the user.
// This way each user off-chain has their own counter
// variable on-chain.
function incrementContext() external onlyTrustedForwarder {
// Remember that with the context shift of relaying,
// where we would use `msg.sender` before,
// this now refers to Gelato Relay's address,
// and to find the address of the user,
// which has been verified using a signature,
// please use _msgSender()!
// Incrementing the counter mapped to the _msgSender!
contextCounter[_msgSender()]++;
// Emitting an event for testing purposes
emit IncrementContextCounter(_msgSender);
}
}
1
import { GelatoRelay, SponsoredCallERC2771Request } from "@gelatonetwork/relay-sdk";
2
const relay = new GelatoRelay();
// Set up on-chain variables, such as target address
const counter = "0xEEeBe2F778AA186e88dCf2FEb8f8231565769C27";
const abi = ["function incrementContext()"];
const provider = new ethers.providers.Web3Provider(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.populateTransaction.incrementContext();
// Populate a relay request
const request: SponsoredCallERC2771Request = {
chainId: provider.network.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);
It is important to mention that in the current implementation, the
userNonce
abstraction does not allow for multiple calls or call concurrency:- For example, if a user sends three relay calls in a row, and one of them is reverted, the
userNonce
mapping is still incremented, exactly as in the EVM. - In this case, the next two transactions, which may have relied on the previous one modifying some state, will still match the user’s specific
userNonce
, and this could cause the next two transactions to fail. - To implement multi-calls, this would have to be handled by the
target
smart contract via encoding into_call.data.
Last modified 1d ago