Relay

The Defender Relay service allows you to send transactions via a regular HTTP API, and takes care of private key secure storage, transaction signing, nonce management, gas price estimation, and resubmissions. This way you don’t need to worry about securing your private keys in your backend scripts, or by monitoring your transactions to ensure they get mined.

Use cases

Use a Defender Relayer every time you find yourself using a hot wallet in your code. Whenever you need to send a transaction from a script or your backend, you can connect to a Relayer instead to simplify key management and transaction submissions.

  • Poking your contracts to trigger a state transition

  • Update an on-chain oracle with external data

  • Sending meta-transactions to build a gasless experience

  • React to sign-ups in your app by airdropping tokens to your new users

  • Sweeping funds from protocol contracts to secure wallets

  • Building bots for interacting with smart contract protocols

What’s in a Relayer?

Each Defender Relayer is an Ethereum account assigned exclusively to your team. Every time you create a new Relayer, Defender will create a new private key in a secure vault. Whenever you request Defender to send a transaction through that Relayer, the corresponding private key will be used for signing.

You can think of each Relayer as a queue for sending transactions, where all transactions sent through the same Relayer will be sent in order and from the same Ethereum account, controlled exclusively by your team. Skip ahead to the Under the hood section if you want more info on how Relayers work behind the scenes!

Relayers on the Goerli and Rinkeby networks will be automatically funded with test ETH upon creation, and will be topped up when they run low on funds. On other networks, you’ll need to fund each Relayer individually with ETH to ensure they have enough funds to pay for the gas of the transactions you send. In these cases, Defender will send you an email notification if a Relayer’s funds drop below 0.1 ETH.
Defender Relayers are implemented as Externally Owned Accounts. We are working to implement Smart Accounts in the future as well, to support batched transactions, gas tokens, and cold keys for on-chain management.

API Keys

Each Relayer has one or more API keys associated with it. In order to send a transaction through a Relayer, you will need to authenticate the request with one an API key/secret pair. You can create or delete API keys as you see fit, and this will not change the sending address or Relayer balance.

When creating a new API key, keep in mind that the API secret is only visible once during the creation — if you don’t write it down, it’s lost forever. Luckily, creating a new API key is as easy as clicking a button.

Pausing

You can pause a Relayer from the Defender website, to quickly respond to an emergency. This will cause the Relayer to reject any incoming requests to send a transaction, whether it is from an Autotask or via the API. However, keep in mind that any transactions already sent will not be cancelled. When you are ready to resume operations, just hit the Unpause button and your Relayer will go back to normal.

Sending transactions

The easiest way to send a transaction via a Relayer is using the defender-relay-client npm package. The client is initialized with an API key/secret and exposes a simple API for sending transactions through the corresponding Relayer.

import { Relayer } from 'defender-relay-client';
const relayer = new Relayer({apiKey: YOUR_API_KEY, apiSecret: YOUR_API_SECRET});

const tx = await relayer.sendTransaction({
  to, value, data, gasLimit, speed: 'fast'
});
You don’t need to enter a private key when initializing a Relayer client, since the private key is kept secure in the Defender vault.

Using ethers.js

The Relayer client also integrates with ethers.js via a custom signer. This allows you to switch to Defender Relayer for sending transactions with minimal changes in your codebase.

const { DefenderRelaySigner, DefenderRelayProvider } = require('defender-relay-client/lib/ethers');
const { ethers } = require('ethers');

const credentials = { apiKey: YOUR_API_KEY, apiSecret: YOUR_API_SECRET };
const provider = new DefenderRelayProvider(credentials);
const signer = new DefenderRelaySigner(credentials, provider, { speed: 'fast' });

const erc20 = new ethers.Contract(ERC20_ADDRESS, ERC20_ABI, signer);
const tx = await erc20.transfer(beneficiary, 1e18.toString());
const mined = await tx.wait();

In the example above, we are also using a DefenderRelayProvider for making calls to the network. The Defender signer can work with any provider, such as ethers.getDefaultProvider(), but you can rely on Defender as a network provider as well.

Speed

Instead of the usual gasPrice, the Relayer accepts a speed parameter, which can be safeLow, average, fast, or fastest. These values are mapped to actual gas prices when the transaction is sent or resubmitted and vary depending on the state of the network.

Mainnet gas prices are calculated based on the values reported by EthGasStation, EtherChain, GasNow, BlockNative, and Etherscan. Testnet gas prices are obtained from a call to eth_gasPrice to the network.

Gas Price

Alternatively, you may specify a fixed gas price for a transaction, by setting the gasPrice parameter. Transactions with a fixed gas price are either mined with the specified gasPrice or replaced with a NOOP transaction if they couldn’t be mined before validUntil time.

Keep in mind that you have to provide either speed or gasPrice but not both in a send transaction request.

Valid Until

Every transaction in Defender Relay is valid for submission to the Ethereum network until validUntil time. After validUntil time the transaction is replaced by a NOOP transaction in order to prevent relayer from getting stuck at the transaction’s nonce. A NOOP transaction does nothing except advancing the relayer’s nonce.

validUntil defaults to 8 hours after the transaction creation. Note that you can combine validUntil with a fixed gas price to achieve extremely fast mining times and beating other transactions on gasPrice.

If you’re using ethers.js, you may set a validForSeconds option instead of validUntil. In the example below, we configure a DefenderRelaySigner to issue a transaction which will be valid for 120 seconds after its creation.

const signer = new DefenderRelaySigner(credentials, provider, { validForSeconds: 120 });
validUntil is a UTC timestamp. Make sure to use a UTC timezone and not a local one.

Transaction IDs

Since the Relayer may resubmit a transaction with an updated gas price if it does not get mined in the expected time frame, the hash of a given transaction may change over time. To track the status of a given transaction, the Relayer API returns a transactionId identifier you can use to query it.

const latestTx = await relayer.query(tx.transactionId);
The query endpoint will return the latest view of the transaction from the Defender service, which gets updated every few minutes.

Signing

In addition to sending transactions, the Relayer can also sign arbitrary messages using its private key. You can access this feature via the sign method of the client or the equivalent ethers.js method.

const signResponse = await relayer.sign({ message });

Relayer Info

A relayer’s address can be retrieved using the getAddress method of the DefenderRelaySigner class.

const address = await signer.getAddress();

If you need more info about a relayer then checkout the getRelayer method of the client. It returns the following data:

const info = await relayer.getRelayer();
console.log('Relayer info', info);

export interface RelayerModel {
  relayerId: string;
  name: string;
  address: string;
  network: string;
  paused: boolean;
  createdAt: string;
  pendingTxCost: string;
}

Network calls

Defender also provides an easy way to make arbitrary JSON RPC calls to the network. You can use the low-level relayer.call method to send any JSON RPC HTTP request:

const balance = await relayer.call('eth_getBalance', ['0x6b175474e89094c44da98b954eedeac495271d0f', 'latest']);

If you are using ethers.js, this is supported via a custom DefenderRelayProvider provider object:

const provider = new DefenderRelayProvider(credentials);
const balance = await provider.getBalance('0x6b175474e89094c44da98b954eedeac495271d0f');

Autotasks integration

A Relayer can be attached to an Autotask. When doing so, the Autotask code will have direct access to the attached Relayer methods without requiring you to specify an API key. Instead, Defender will inject short-lived credentials for your Relayer in your Autotask handler function.

const { Relayer } = require('defender-relay-client');

// The credentials object is injected by the Defender Autotasks engine
exports.handler = async function(credentials) {
  const relayer = new Relayer(credentials);
  // ... use relayer as usual
}

Meta-transactions

Defender Relayers are general-purpose relayers, in the sense that you can use them to send any transaction you want to your contracts. In particular, they can also be used for relaying meta-transactions on behalf of your users. A simple setup for this requires setting up a server-side function that decides whether or not to relay a given meta-transaction, and then calls the Defender Relayer for effectively sending it.

If you would like to use Autotasks to host the server-side function to decide whether to pay for a meta-transaction request, let us know! We are working on a webhooks integration that can be used for this purpose.

EIP2771 GSNv2-compatible meta-transactions

We have created a demo application for Defender-powered meta-txs here. This application relies on an EIP-2771 Forwarder contract. This contract’s sole responsibility is to receive a signed meta-tx request, verify its signature, and forward the request to a recipient contract by appending the signer address to the call.

This setup is compatible with GSNv2, meaning that you can use a Defender Relayer for sending your meta-transactions, and at any point in the future, you can switch to the decentralized network of GSN relayers without any changes to your contracts.

You can explore the key parts of the code for the application here.

More meta-transaction patterns

The pattern described above is just one variant among several meta-transaction flavors available. Given that Defender Relayers are general-purpose, you can also use them for any other type of meta-transactions, such as relaying gasless ERC20 transfers using EIP2612 or EIP3009.

In particular, you can leverage Defender xDai Relayers for sending transactions on behalf of your users in xDai, given the low cost of transactions in that sidechain. This way, you can offer a full gasless experience in your dapp. Let us know if you have any other network you’d like to see supported in Defender.

Manual operation

You can also manually send transactions through a Relayer or withdraw funds from it directly from the Defender site. To do so, go to the Relayer page, open the cog menu, and choose the option you want.

Sending transactions

You can manually send a transaction to a contract from your Relayer by choosing Send transaction in your relay cog menu:

Defender Relay Cog Menu

At the Send transaction screen, enter the address of the contract you want to interact with, select a function to execute, and enter its arguments.

At the time of writing, Defender only supports sending transactions to source verified contracts, so make sure the target contract has been verified either on Etherscan or Sourcify.
Defender Relay Send Transaction

When you click on Confirm transaction, the transaction will be sent through the relayer. We suggest that you wait for the transaction to be confirmed before leaving this screen, or to monitor it on your block explorer of choice, to ensure that it is confirmed and there is no further action required from you.

Defender sets speed to Fast for relayer transactions created through the UI.

Withdrawing funds

You can withdraw funds from a relayer by clicking on Withdraw funds in the Relayer page.

Defender Relay Withdraw Funds

At the Withdraw funds screen, you can choose to send funds in ETH or pick from a built-in list of ERC20 tokens.

Defender Relay Withdraw Funds Screen

Under the hood

Each Relayer is associated to a private key. When a request to send a transaction is received, the Relayer validates the request, atomically assigns it a nonce, reserves balance for paying for its gas fees, resolves its speed to a gas price, signs it with its private key, and enqueues it for submission to the blockchain. The response is sent back to the client only after this process has finished. Then, the transaction is broadcasted through both Infura and Alchemy for redundancy and retried up to three times in case both APIs are down.

Every five minutes, all in-flight transactions are checked by the system. If they have not been mined and more than a certain time has passed (which depends on the transaction speed), they are resubmitted with a 10% increase in their gas price (or the latest gas price for their speed, if it’s greater), which could be up to a 150% of the reported gas price for their speed. This process causes the transaction hash to change, but their ID is preserved. On the other hand, if the transaction has been mined, it is still monitored for several blocks until we consider it to be confirmed.

Security considerations

All private keys are stored in the AWS Key Management Service. Keys are generated within the KMS and never leave it, i.e., all sign operations are executed within the KMS. Furthermore, we rely on dynamically generated AWS Identity and Access Management policies to isolate access to the private keys among tenants.

As for API secrets, these are only kept in memory during creation when they are sent to the client. After that, they are hashed and stored securely in AWS Cognito, which is used behind the scenes for authenticating Relayer requests. This makes API keys easy to rotate while preserving the same private key on the KMS.

Coming up…​

We are working on new features, such as fixed gas prices, time-to-live for transactions, and policies to restrict maximum expenditure. Stay tuned, and let us know if you have any requests!