Skip to Content
Supra Layer 1SupraEVMGetting Started with Automation

Getting Started with Automation

This page registers an automation task on Devnet end to end with Foundry: a contract whose counter the chain increments on its own, in every block whose number is a multiple of 5. The task’s action runs in every block where its predicate holds. The task’s owner pays automation fees in WSUPRA and each run’s execution fee, its gas, in native SUPRA; step 3 gives both. For the model behind each step — cycles, fees, task states — see How Automation Works.

The steps are:

  1. Find the contracts
  2. Check that automation is available
  3. Prepare the account
  4. Deploy the example contract
  5. Register a user task
  6. Watch it run
  7. Cancel or stop a task
  8. Register a task from a contract

The commands assume a Foundry project set up as in Foundry: its foundry.toml targets osaka and names the Devnet endpoint supra_devnet, and the account’s key is imported into a keystore named deployer:

[profile.default] evm_version = "osaka" chain_id = 535600 [rpc_endpoints] supra_devnet = "https://rpc-devnet.supra.com/rpc/v1/eth/wallet_integration"

supra_devnet must name the wallet-integration endpoint: the scripts on this page fail against /rpc/v1/eth, as Which endpoint to use explains.

1. Find the contracts

Read the automation registry’s and Wrapped SUPRA’s addresses from the contract registry, under the keys AutomationRegistry and WrappedSupra. The resource omits leading zero digits, so each value is left-padded to 40 hex digits:

details=$(curl -s 'https://rpc-devnet.supra.com/rpc/v4/accounts/0x1/resources/0x1%3A%3Aevm_config%3A%3AEvmContractsDetails') evm_address() { local hex hex=$(jq -r --arg k "$1" '.data.details.data[] | select(.key == $k) | .value' <<< "$details") printf '0x%040s\n' "${hex#0x}" | tr ' ' 0 } export AUTOMATION_REGISTRY=$(evm_address AutomationRegistry) export WSUPRA=$(evm_address WrappedSupra)

2. Check that automation is available

Registration succeeds only while automation is enabled, registration is enabled, and the current cycle is STARTED:

cast call "$AUTOMATION_REGISTRY" "isAutomationReadyEnabled()(bool)" --rpc-url supra_devnet cast call "$AUTOMATION_REGISTRY" "isRegistrationEnabled()(bool)" --rpc-url supra_devnet # Cycle index, start time, duration in seconds, state (0 READY, 1 STARTED, 2 FINISHED, 3 SUSPENDED). cast call "$AUTOMATION_REGISTRY" "getCycleInfo()(uint64,uint64,uint64,uint8)" --rpc-url supra_devnet

Both calls must return true and the state must be 1. Otherwise registration reverts with AutomationNotEnabled, RegistrationDisabled or CycleTransitionInProgress; see Cycle states.

3. Prepare the account

A task’s owner pays two kinds of fees, from two balances:

FeeWhat it isPaid inWhen
Automation feeThe flat registration fee and a refundable deposit, then the cycle feeWSUPRAAt registration, then at each cycle transition while the task lives
Execution feeThe gas of the task’s action, and any native value the action sendsNative SUPRAIn each block where the predicate holds and the action runs

The registry draws the automation fees from the owner’s WSUPRA balance, under the owner’s approval. The chain debits the execution fees from the owner’s native balance. The predicate’s gas is not charged, but counts towards the task’s _maxGasAmount. The owner’s EVM account therefore needs native SUPRA, part of it wrapped into WSUPRA with the automation registry approved to spend it, and the rest kept native.

  1. Fund the EVM account. Devnet has no EVM faucet. Fund a Move account from the Move faucet and transfer to the EVM address from it, as described in Funding an account. Creating the Move account and the transfer with the Supra CLI are in From the Supra CLI.

  2. Wrap and approve. The PrepareFees script is in script/Automation.s.sol, listed in step 5; create that file before running it. The script deposits native SUPRA into WSUPRA and approves the registry for the same amount — 1 SUPRA unless FEE_BUDGET sets another amount in wei:

    forge script script/Automation.s.sol:PrepareFees \ --rpc-url supra_devnet --account deployer --broadcast

The WSUPRA budget pays the automation fees: the flat registration fee and the task’s deposit at registration, then the cycle fee at every cycle transition while the task runs. Keep both the WSUPRA balance and the allowance above each cycle’s fee: a task whose owner cannot be charged is removed, and its deposit is not refunded. At the fee settings Devnet’s genesis derives from its Move configuration, without congestion, registering the task below takes about 5.0 × 10¹⁷ wei (0.5 SUPRA) — the flat fee plus a refundable deposit of 2 × 10¹⁵ wei — and each 600-second cycle charges 10¹⁵ wei. The default budget of 10¹⁸ wei (1 SUPRA) covers registration and about 6 × 10¹⁵ wei of cycle fees over the task’s default one-hour lifetime, with about 0.49 SUPRA left over. The settings can change; read the current ones with getConfig(), and a task’s per-cycle fee with estimateAutomationFee, as in Values at genesis.

The execution fees are paid separately, from the owner’s native balance and not from WSUPRA. An action runs only while that balance covers its gas limit at the scheduled price plus any value it sends; otherwise it is discarded in that block and the task stays registered. The node logs a discarded action only at debug level, and the cycle fees keep being drawn from WSUPRA while the task lives.

The figures below assume one block per second; at R blocks per second, multiply the execution fees by R, and measure R by reading cast block-number twice. The task runs in every block whose number is a multiple of 5, so one 600-second cycle holds 120 runs. The first run of the task, which sets the counter’s storage slot, uses 45,183 gas, and each later run uses 28,083 gas. At the minimum gas price of 333,333,300,000 wei a later run costs about 9.4 × 10¹⁵ wei (0.0094 SUPRA), so a cycle costs about 1.12 SUPRA, and the default one-hour lifetime, at most six cycles once the task is active, about 6.7 SUPRA. The price paid is the lowest gas price included in the block, which is above the minimum when every transaction in the block offers more. Keep the native balance above FEE_BUDGET plus the runs’ gas for as long as the task is meant to run, and stop the task in step 7 before the balance runs out, because StopTask also needs native gas. To spend less, set TASK_LIFETIME_SECS to a shorter lifetime when registering, still later than the end of the current cycle.

4. Deploy the example contract

src/AutomationCounter.sol holds the task’s action and its predicate:

// SPDX-License-Identifier: MIT pragma solidity ^0.8.31; /// A target for an automation task: `increment` is the action, and `isBlockMultipleOf5` the /// predicate that gates it. contract AutomationCounter { uint256 public counter; event Incremented(uint256 blockNumber, uint256 newValue); /// The task's action. function increment() external { counter += 1; emit Incremented(block.number, counter); } /// The predicate: the action runs only in a block whose number is a multiple of 5. function isBlockMultipleOf5() external view returns (bool) { return block.number % 5 == 0; } }

The predicate is evaluated in the block the action would run in, so every Incremented log emitted by the task’s automated transactions carries a block number that is a multiple of 5. increment() has no access control, so a log from a transaction that any account sends to the contract can carry any block number.

forge create src/AutomationCounter.sol:AutomationCounter \ --rpc-url supra_devnet --account deployer --broadcast export COUNTER=<deployed address>

5. Register a user task

script/Automation.s.sol holds every script this page runs — PrepareFees, RegisterUserTask, and the CancelTask and StopTask scripts of step 7:

// SPDX-License-Identifier: MIT pragma solidity ^0.8.31; import {Script, console} from "forge-std/Script.sol"; import {AutomationCounter} from "../src/AutomationCounter.sol"; /// The automation registry entry points these scripts call. interface IAutomationRegistry { function register( bytes memory payloadTx, bytes memory predicate, uint64 expiryTime, uint128 maxGasAmount, uint128 gasPriceCap, uint128 automationFeeCapForCycle, uint64 priority, bytes[] memory auxData ) external; function cancelTasks(uint64[] memory taskIndexes) external; function stopTasks(uint64[] memory taskIndexes) external; function getNextTaskIndex() external view returns (uint64); function estimateAutomationFee(uint128 taskOccupancy) external view returns (uint128); } interface IWrappedSupra { function deposit() external payable; function approve(address spender, uint256 amount) external returns (bool); } /// The registry's access-list entry, as encoded into a task's payload. struct AccessListEntry { address addr; bytes32[] storageKeys; } /// Stand-in for the transaction-hash precompile, which Forge's local EVM does not have. contract TxHashStandIn { fallback(bytes calldata) external returns (bytes memory) { return abi.encode(bytes32(0)); } } /// Stand-in for the EVM gas config precompile, serving the figures it is constructed with. contract GasConfigStandIn { uint64 internal immutable TX_GAS_LIMIT_CAP; uint256 internal immutable MIN_GAS_PRICE; constructor(uint64 txGasLimitCap_, uint256 minGasPrice_) { TX_GAS_LIMIT_CAP = txGasLimitCap_; MIN_GAS_PRICE = minGasPrice_; } function txGasLimitCap() external view returns (uint64) { return TX_GAS_LIMIT_CAP; } function minGasPrice() external view returns (uint256) { return MIN_GAS_PRICE; } } abstract contract AutomationScript is Script { address constant TX_HASH_PRECOMPILE = 0x0000000000000000000000000000000053555001; address constant GAS_CONFIG_PRECOMPILE = 0x0000000000000000000000000000000053555005; /// Gas ceiling for one execution, shared by the predicate and the action. uint128 constant MAX_GAS_AMOUNT = 100_000; /// Forge executes the script locally before broadcasting, and registration reads two Supra /// precompiles that Forge's EVM does not have. Install stand-ins for that local run; the /// broadcast transaction is executed by the chain against the real precompiles. function installPrecompileStandIns() internal { vm.etch(TX_HASH_PRECOMPILE, address(new TxHashStandIn()).code); GasConfigStandIn gasConfig = new GasConfigStandIn( uint64(vm.envUint("CHAIN_TX_GAS_LIMIT_CAP")), vm.envUint("CHAIN_MIN_GAS_PRICE") ); vm.etch(GAS_CONFIG_PRECOMPILE, address(gasConfig).code); } function encodePayload(address target, bytes memory callData) internal pure returns (bytes memory) { return abi.encode(uint128(0), target, callData, new AccessListEntry[](0)); } function encodePredicate(address target) internal pure returns (bytes memory) { return abi.encode(target, abi.encodeCall(AutomationCounter.isBlockMultipleOf5, ())); } function expiryTime() internal view returns (uint64) { return uint64(block.timestamp + vm.envOr("TASK_LIFETIME_SECS", uint256(3600))); } } /// Wraps native SUPRA into WSUPRA and approves the automation registry to spend it. contract PrepareFees is Script { function run() external { IWrappedSupra wsupra = IWrappedSupra(vm.envAddress("WSUPRA")); address registry = vm.envAddress("AUTOMATION_REGISTRY"); uint256 amount = vm.envOr("FEE_BUDGET", uint256(1 ether)); vm.startBroadcast(); wsupra.deposit{value: amount}(); wsupra.approve(registry, amount); vm.stopBroadcast(); } } /// Registers a user task (UST) that calls `increment` whenever the block number is a multiple of 5. contract RegisterUserTask is AutomationScript { function run() external { installPrecompileStandIns(); IAutomationRegistry registry = IAutomationRegistry(vm.envAddress("AUTOMATION_REGISTRY")); address counter = vm.envAddress("COUNTER"); // Pay up to twice the current per-cycle estimate, as headroom against congestion. uint128 feeCapForCycle = registry.estimateAutomationFee(MAX_GAS_AMOUNT) * 2; // Bid above the floor, so the task is not skipped in blocks priced above it. uint128 gasPriceCap = uint128(vm.envUint("CHAIN_MIN_GAS_PRICE") * 2); vm.startBroadcast(); uint64 taskIndex = registry.getNextTaskIndex(); registry.register( encodePayload(counter, abi.encodeCall(AutomationCounter.increment, ())), encodePredicate(counter), expiryTime(), MAX_GAS_AMOUNT, gasPriceCap, feeCapForCycle, 0, new bytes[](0) ); vm.stopBroadcast(); console.log("Submitted user task; expected task index", taskIndex); } } /// Selects the task named by TASK_INDEX. abstract contract TaskOwnerScript is Script { function taskIndexes() internal view returns (uint64[] memory indexes) { indexes = new uint64[](1); indexes[0] = uint64(vm.envUint("TASK_INDEX")); } } /// Cancels a task. A PENDING task is removed at once; an ACTIVE task keeps running until the /// current cycle ends and is removed at the cycle transition. contract CancelTask is TaskOwnerScript { function run() external { IAutomationRegistry registry = IAutomationRegistry(vm.envAddress("AUTOMATION_REGISTRY")); vm.startBroadcast(); registry.cancelTasks(taskIndexes()); vm.stopBroadcast(); } } /// Stops a task, removing it at once whatever its state. contract StopTask is TaskOwnerScript { function run() external { IAutomationRegistry registry = IAutomationRegistry(vm.envAddress("AUTOMATION_REGISTRY")); vm.startBroadcast(); registry.stopTasks(taskIndexes()); vm.stopBroadcast(); } }

forge script executes a script locally before it broadcasts, and registration reads two Supra precompiles that Forge’s local EVM does not have: the transaction-hash precompile at 0x…53555001 and the EVM gas config precompile at 0x…53555005. installPrecompileStandIns installs stand-ins for that local run only. The broadcast transaction is executed by the chain against the real precompiles. Because the local run differs from the chain, pass --skip-simulation, which stops Forge from replaying the transactions without the stand-ins.

The gas-config stand-in serves the figures passed in CHAIN_TX_GAS_LIMIT_CAP and CHAIN_MIN_GAS_PRICE. Read them from the chain, so the local run accepts what the chain will:

export CHAIN_TX_GAS_LIMIT_CAP=$(cast call 0x0000000000000000000000000000000053555005 "txGasLimitCap()" --rpc-url supra_devnet) export CHAIN_MIN_GAS_PRICE=$(cast call 0x0000000000000000000000000000000053555005 "minGasPrice()" --rpc-url supra_devnet) forge script script/Automation.s.sol:RegisterUserTask \ --rpc-url supra_devnet --account deployer --broadcast --skip-simulation

RegisterUserTask calls register with:

ArgumentValue
_payloadTxA call to increment() on COUNTER, sending no value
_predicateA call to isBlockMultipleOf5() on COUNTER
_expiryTimeOne hour from now, or TASK_LIFETIME_SECS seconds. It must be later than the end of the current cycle
_maxGasAmount100,000, shared by the predicate and the action
_gasPriceCapTwice the chain’s minimum gas price, so the task is not skipped in blocks priced above the minimum
_automationFeeCapForCycleTwice the registry’s current per-cycle fee estimate, as headroom if congestion raises the fee before the next cycle
_priority0. A user task’s priority is always its task index
_auxDataEmpty

The encodings follow Encoding the call. If registration reverts, the error names the check that failed; see When calls fail.

6. Watch it run

A newly registered task is PENDING until the current cycle ends; it becomes ACTIVE at the transition and runs from then on. Find the task and wait for the cycle to turn:

OWNER=$(cast wallet address --account deployer) cast call "$AUTOMATION_REGISTRY" "getTasksByAddress(address)(uint256[])" "$OWNER" --rpc-url supra_devnet export TASK_INDEX=<task index> # Repeat until the cycle index has advanced past the one registration happened in. cast call "$AUTOMATION_REGISTRY" "getCycleInfo()(uint64,uint64,uint64,uint8)" --rpc-url supra_devnet cast call "$AUTOMATION_REGISTRY" "hasActiveUserTask(address,uint64)(bool)" "$OWNER" "$TASK_INDEX" \ --rpc-url supra_devnet

Once the task is active, query the logs its action emits over the last 1,000 blocks:

LATEST=$(cast block-number --rpc-url supra_devnet) cast logs --address "$COUNTER" "Incremented(uint256,uint256)" \ --from-block $((LATEST - 1000)) --to-block "$LATEST" --rpc-url supra_devnet cast call "$COUNTER" "counter()(uint256)" --rpc-url supra_devnet

A node refuses an eth_getLogs request whose block range or result set exceeds its bound with -32005; see Error codes. To read logs from an earlier period, query that period in ranges within the bound.

Each log the task emits comes from an automated transaction. Fetching that transaction by its hash shows "supraTxKind": "automated"; a log from another caller has no supraTxKind. See Automated Transactions over RPC.

The task runs until its expiry time unless it is cancelled or stopped first; see step 7. It is also removed when its owner cannot pay a cycle fee, when its cycle fee exceeds _automationFeeCapForCycle, when the node removes it for one of the reasons in Removal by the runtime, or when a new epoch’s gas config no longer admits it. A reverted, halted or discarded action does not remove it. The task runs with its owner as the transaction sender. The owner of this task is the account that ran RegisterUserTask; a task registered by a contract is owned by, and runs as, that contract, as in step 8. Its action pays gas from the owner’s native balance in every block it runs; see What an execution looks like.

7. Cancel or stop a task

A task’s owner ends it early with cancelTasks or stopTasks. The two differ in when the task stops running and in what is refunded:

CallTask stateRemovedRefund
CancelPENDINGAt onceHalf the deposit
CancelACTIVEAt the next cycle transition. Until then the task is CANCELLED and keeps executingThe whole deposit, at that transition
StopPENDINGAt onceHalf the deposit
StopACTIVE or CANCELLEDAt onceThe whole deposit, plus half the cycle fee for the rest of the cycle

The flat registration fee is not refunded in any case. Both calls work only while the cycle is STARTED with automation enabled. The rules are in Cancelling versus stopping and Task lifecycle.

CancelTask and StopTask act on the task given by TASK_INDEX. Neither reads a Supra precompile, so they need no stand-ins and no --skip-simulation:

export TASK_INDEX=<task index> forge script script/Automation.s.sol:CancelTask \ --rpc-url supra_devnet --account deployer --broadcast forge script script/Automation.s.sol:StopTask \ --rpc-url supra_devnet --account deployer --broadcast

An index that does not exist is skipped without an error, so check the result rather than relying on the transaction succeeding. The transaction’s logs show which indexes were acted on:

CallFor each task cancelled or stoppedFor an index with no task
cancelTasksOne entry in TasksCancelled: (taskIndex, taskType, txHash). A PENDING task is refunded in the same transaction, with TaskDepositFeeRefund(taskIndex, owner, amount). An ACTIVE task is refunded at the next cycle transition, whose RemovedTasks lists it and whose TaskDepositFeeRefund carries the whole depositNo entry
stopTasksOne entry in TasksStopped: (taskIndex, depositRefund, cycleFeeRefund, txHash), and a WSUPRA Transfer from the registry to the owner for the sum of the refundsNo entry

Each event lists only the indexes acted on, and a call none of whose indexes exists emits neither TasksCancelled nor TasksStopped. These calls emit no event for a skipped index. The owner is the indexed topic of both events, so they can also be found with cast logs by owner. Removal by the registry owner and by the runtime report skipped indexes with their own events; see Removal by the registry owner.

To check a cancel or stop, read its receipt and look for the event’s topic:

TX=<transaction hash of the cancel or stop> cast sig-event "TasksCancelled((uint64,uint8,bytes32)[],address)" cast sig-event "TasksStopped((uint64,uint128,uint128,bytes32)[],address)" cast receipt "$TX" logs --rpc-url supra_devnet

A log whose first topic is one of the two values above is the event, and its data holds the entries.

Checking the result

Whether the task is still registered, and whether it is still in the set the node schedules from:

cast call "$AUTOMATION_REGISTRY" "ifTaskExists(uint64)(bool)" "$TASK_INDEX" --rpc-url supra_devnet cast call "$AUTOMATION_REGISTRY" "getActiveTaskIds()(uint64[])" --rpc-url supra_devnet

A registered task’s state is the twelfth field of getTaskDetails: 0 PENDING, 1 ACTIVE, 2 CANCELLED. The call reverts with TaskDoesNotExist once the task is removed:

cast call "$AUTOMATION_REGISTRY" \ "getTaskDetails(uint64)((uint128,uint128,uint128,uint128,bytes32,uint64,uint64,uint64,uint64,address,uint8,uint8,bytes,bytes,bytes[]))" \ "$TASK_INDEX" --rpc-url supra_devnet

The refund is paid in WSUPRA:

cast call "$WSUPRA" "balanceOf(address)(uint256)" "$OWNER" --rpc-url supra_devnet

Cancelling versus stopping an active task

With the example task active, the difference shows in its logs:

  • After cancelling, ifTaskExists stays true, the state reads 2, the task stays in getActiveTaskIds, and Incremented logs keep appearing until the current cycle ends — getCycleInfo() gives its start time and duration. hasActiveUserTask also stays true, since it reports any task that is not PENDING. At the next cycle transition the task is removed and its whole deposit is refunded.
  • After stopping, ifTaskExists is false at once, the task leaves getActiveTaskIds, and no Incremented log appears from the next block on. The refund arrives in the same transaction.

Query a range within the node’s bound that starts shortly before the block of the cancel or stop and ends once the chain has passed it:

cast logs --address "$COUNTER" "Incremented(uint256,uint256)" \ --from-block $((CHANGE_BLOCK - 500)) --to-block $((CHANGE_BLOCK + 500)) \ --rpc-url supra_devnet

CHANGE_BLOCK is the block of the cancel or stop transaction.

8. Register a task from a contract

A task can also be registered by a contract, which then owns it: the task’s predicate and action are calls from the contract, so from, msg.sender and tx.origin are the contract, and the contract pays the task’s fees and gas. This step registers the same counter task from a contract.

What the contract needs before it registers

The registry and the chain require the owning contract to:

  1. Declare IAutomationTaskOwner through ERC-165. The registry asks a caller with code for supportsInterface, and accepts it only if it returns true for 0x01ffc9a7 (IERC165) and for bytes4(keccak256("IAutomationTaskOwner")), and false for 0xffffffff, each within 30,000 gas. Otherwise register reverts with UnsupportedTaskOwner(owner). An account with an EIP-7702 delegation needs no declaration.
  2. Hold WSUPRA for the automation fees and approve the registry. register draws the flat fee and the deposit from the calling contract with transferFrom, and each cycle transition draws the cycle fee the same way. Keep both the contract’s WSUPRA balance and its allowance above each cycle’s fee, as in step 3.
  3. Hold native SUPRA for the execution fees. Each run’s gas, and any value in the payload, is paid from the contract’s native balance, so the contract must be able to receive it. The run costs of step 3 apply.
  4. Have its own functions to cancel and stop the task. Only the owner can call cancelTasks or stopTasks, so a contract without such functions cannot end its task; only the registry owner can then remove it, through a governance proposal. The refund from a stop is paid to the contract, so it also needs a way to withdraw.
  5. Restrict who can make it register. Every task the contract registers runs in its name, for as long as the task lives, and passes any check other contracts make on the contract’s address. The example below lets only the account that deployed it register, cancel, stop or withdraw.

The task’s predicate must not depend on msg.sender: registration calls it from the registry, and execution from the owner; see The predicate.

The NatSpec of IAutomationTaskOwner, in src/interfaces/IAutomationTaskOwner.sol of the revm fork, lists the same obligations. The fork also provides an optional abstract base, AutomationTaskOwnerBase in src/AutomationTaskOwnerBase.sol. It answers ERC-165 as the registry requires, accepts native SUPRA, and wraps the registry calls in internal functions, leaving the external functions and their access control to the contract that inherits it. Its only imports are src/interfaces/IAutomationTaskOwner.sol and src/interfaces/IERC165.sol. The example below declares the interface itself, so that it compiles on its own.

The owner contract

src/AutomationCounterOwner.sol, next to src/AutomationCounter.sol from step 4:

// SPDX-License-Identifier: MIT pragma solidity ^0.8.31; import {AutomationCounter} from "./AutomationCounter.sol"; /// The automation registry entry points the owner calls. interface IAutomationRegistry { function register( bytes memory payloadTx, bytes memory predicate, uint64 expiryTime, uint128 maxGasAmount, uint128 gasPriceCap, uint128 automationFeeCapForCycle, uint64 priority, bytes[] memory auxData ) external; function cancelTasks(uint64[] memory taskIndexes) external; function stopTasks(uint64[] memory taskIndexes) external; } interface IWrappedSupra { function deposit() external payable; function approve(address spender, uint256 amount) external returns (bool); function transfer(address to, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); } /// The registry's access-list entry, as encoded into a task's payload. struct AccessListEntry { address addr; bytes32[] storageKeys; } // ERC-165 identifier of `IAutomationTaskOwner`, which the registry requires a contract task // owner to declare. bytes4 constant AUTOMATION_TASK_OWNER_INTERFACE_ID = bytes4(keccak256("IAutomationTaskOwner")); /// A contract that owns an automation task calling `increment` on an `AutomationCounter`. Every /// task it registers runs with this contract as the sender, so only its admin can make it /// register, cancel, stop or withdraw. contract AutomationCounterOwner { /// Gas ceiling for one execution, shared by the predicate and the action. uint128 public constant MAX_GAS_AMOUNT = 100_000; IAutomationRegistry public immutable registry; IWrappedSupra public immutable wsupra; address public immutable admin; error NotAdmin(); error TransferFailed(); modifier onlyAdmin() { if (msg.sender != admin) revert NotAdmin(); _; } constructor(address registry_, address wsupra_) { registry = IAutomationRegistry(registry_); wsupra = IWrappedSupra(wsupra_); admin = msg.sender; } /// ERC-165: `IERC165` and `IAutomationTaskOwner`, and nothing else. function supportsInterface(bytes4 interfaceId) external pure returns (bool) { return interfaceId == 0x01ffc9a7 || interfaceId == AUTOMATION_TASK_OWNER_INTERFACE_ID; } /// Native SUPRA held here pays each run's gas. receive() external payable {} /// Wraps `feeBudget` of the attached value into WSUPRA for the task's fees and approves the /// registry to draw them; the rest stays native, for gas. function fund(uint256 feeBudget) external payable onlyAdmin { wsupra.deposit{value: feeBudget}(); if (!wsupra.approve(address(registry), type(uint256).max)) revert TransferFailed(); } /// Registers a task that calls `increment` on `counter` in every block whose number is a /// multiple of 5. This contract becomes the task's owner. function registerCounterTask(address counter, uint64 expiryTime, uint128 gasPriceCap, uint128 feeCapForCycle) external onlyAdmin { registry.register( abi.encode(uint128(0), counter, abi.encodeCall(AutomationCounter.increment, ()), new AccessListEntry[](0)), abi.encode(counter, abi.encodeCall(AutomationCounter.isBlockMultipleOf5, ())), expiryTime, MAX_GAS_AMOUNT, gasPriceCap, feeCapForCycle, 0, new bytes[](0) ); } function cancelTask(uint64 taskIndex) external onlyAdmin { registry.cancelTasks(single(taskIndex)); } function stopTask(uint64 taskIndex) external onlyAdmin { registry.stopTasks(single(taskIndex)); } /// Sends this contract's WSUPRA and native SUPRA to `to`, for example the refund after a stop. function withdraw(address payable to) external onlyAdmin { uint256 wrapped = wsupra.balanceOf(address(this)); if (wrapped > 0 && !wsupra.transfer(to, wrapped)) revert TransferFailed(); (bool sent,) = to.call{value: address(this).balance}(""); if (!sent) revert TransferFailed(); } function single(uint64 taskIndex) internal pure returns (uint64[] memory indexes) { indexes = new uint64[](1); indexes[0] = taskIndex; } }

fund approves the registry for an unlimited amount, so that the cycle fees keep being drawn for as long as the task runs. withdraw sends the contract’s WSUPRA and native SUPRA to the given address once the task has ended.

Deploy, fund and register

COUNTER is the counter from step 4, and the registry and WSUPRA addresses are those of step 1. Deploy the owner from the account that will administer it:

forge create src/AutomationCounterOwner.sol:AutomationCounterOwner \ --rpc-url supra_devnet --account deployer --broadcast \ --constructor-args "$AUTOMATION_REGISTRY" "$WSUPRA" export TASK_OWNER=<deployed address>

Check that the contract answers ERC-165 as the registry requires. The three calls must return true, true and false:

OWNER_INTERFACE_ID=$(cast keccak "IAutomationTaskOwner" | cut -c1-10) cast call "$TASK_OWNER" "supportsInterface(bytes4)(bool)" 0x01ffc9a7 --rpc-url supra_devnet cast call "$TASK_OWNER" "supportsInterface(bytes4)(bool)" "$OWNER_INTERFACE_ID" --rpc-url supra_devnet cast call "$TASK_OWNER" "supportsInterface(bytes4)(bool)" 0xffffffff --rpc-url supra_devnet

Fund the contract. fund(feeBudget) wraps feeBudget of the attached value into WSUPRA and approves the registry; the rest of the value stays native and pays the runs’ gas. Size both as in step 3. Here 1 SUPRA is wrapped for fees and 9 SUPRA stay native, which covers the about 6.7 SUPRA of execution fees of the default one-hour lifetime at one block per second; at a higher block rate, attach proportionally more or register a shorter lifetime. Once the contract’s native balance cannot cover a run, each action is discarded while the cycle fees keep being drawn, so stop the task before then:

cast send "$TASK_OWNER" "fund(uint256)" 1ether --value 10ether \ --rpc-url supra_devnet --account deployer

Register the task through the contract, with the same arguments RegisterUserTask uses. cast send estimates gas against the node, which has the Supra precompiles, so no stand-ins are needed:

MIN_GAS_PRICE=$(cast call 0x0000000000000000000000000000000053555005 "minGasPrice()(uint256)" \ --rpc-url supra_devnet | awk '{print $1}') FEE_ESTIMATE=$(cast call "$AUTOMATION_REGISTRY" "estimateAutomationFee(uint128)(uint128)" 100000 \ --rpc-url supra_devnet | awk '{print $1}') EXPIRY=$(( $(date +%s) + 3600 )) cast send "$TASK_OWNER" "registerCounterTask(address,uint64,uint128,uint128)" \ "$COUNTER" "$EXPIRY" "$(( MIN_GAS_PRICE * 2 ))" "$(( FEE_ESTIMATE * 2 ))" \ --rpc-url supra_devnet --account deployer

If the call reverts with UnsupportedTaskOwner, the contract’s ERC-165 answers are not the ones above. The other errors are those of When calls fail.

Watch, stop and withdraw

The task is listed under the contract’s address, not the deployer’s, and runs from the next cycle as in step 6. The automated transactions’ from is TASK_OWNER:

cast call "$AUTOMATION_REGISTRY" "getTasksByAddress(address)(uint256[])" "$TASK_OWNER" --rpc-url supra_devnet export TASK_INDEX=<task index>

The CancelTask and StopTask scripts of step 7 revert with UnauthorizedAccount for this task, because the deployer is not its owner. End it through the contract, then withdraw what the contract holds:

cast send "$TASK_OWNER" "stopTask(uint64)" "$TASK_INDEX" --rpc-url supra_devnet --account deployer cast send "$TASK_OWNER" "withdraw(address)" "$(cast wallet address --account deployer)" \ --rpc-url supra_devnet --account deployer

cancelTask is the contract’s counterpart of CancelTask, with the differences described in step 7.

Last updated on