Automate smart contract transaction for hourly activity
Defender allows you to automate smart contract operational tasks with easy integration with the rest of Defender. This tutorial shows how to build an action that sends an on-chain transaction every hour that adds an object to a box and increases the number of objects inside.
1. Set up action
You will configure an action that sends an hourly transaction with the addObject()
function to the 0xC64f7ace6127bc7B0bAb23bD1871aC81e6AEC074
contract in Sepolia, which is an example of a Box contract deployed in the Deploy tutorial. To do so, follow these steps:
-
Run the following command in your terminal:
-
Open Defender Relayers in a web browser.
-
Click on Create Relayer with the name
Actions Relayer
and Sepolia network. -
Fund it with some Sepolia ETH. This relayer will send and pay for the automated transactions.
-
Open Defender Actions.
-
Click on Create Action.
-
Name the action
Hourly object add
. -
Select Schedule as trigger, and a Timespan of 1 hour as schedule.
-
Select the Actions Relayer as the connected relayer.
-
Paste the following code in the Code field:
const { Defender } = require('@openzeppelin/defender-sdk'); exports.handler = async function(credentials) { const client = new Defender(credentials); const txRes = await client.relaySigner.sendTransaction({ to: '0xC64f7ace6127bc7B0bAb23bD1871aC81e6AEC074', speed: 'fast', data: '0x62029d2a', gasLimit: '80000', }); console.log(txRes); return txRes.hash; }
The contract address is the target, which is
0xC64f7ace6127bc7B0bAb23bD1871aC81e6AEC074
, and data is0x62029d2a
, the encoded version of theaddObject()
function of the contract. -
Click on Save Action.
After saving, the Actions page should look like this:
Your action will now be running every hour! You can check the Defender Logs for more detailed information about the activity.
2. Verify activity
After the action has run for a while, you can verify that the transaction is being sent every hour. To do so, open the Etherscan contract page and look for transactions from the configured Relayer. An alternative is to search your Relayer in Etherscan and look for the transactions sent to the contract.
You will also receive alerts in case the action fails (for example, if the Relayer runs out of gas). They look like this:
Next steps
Congratulations! You can modify the action to automate other contracts and build more complex transactions. In case you are interested in advanced use cases, we are working on actions-related guides.
Alongisde actions, we recommend using Access Control to manage a contract’s permissions through Defender. Learn how to use Access Control with its tutorial here. |