Automate Contract Balance Top-up
Some smart contract applications require you to maintain a certain Ethereum balance to ensure optimal operation. You can automate this process using Chainlink Automation. Use these smart contracts to monitor and top-up native token balances on your smart contracts.
View the EthBalanceMonitor.sol contract on GitHub.
Objective
This Automation contract monitors and funds Ethereum addresses that developers might need to top up frequently based on a configurable threshold. You will deploy this example monitor contract and use the automation.chain.link interface to register an upkeep and run the contract. To learn the basics about Chainlink Automation, read the Chainlink Automation Introduction.
For this example, use the Polygon Mumbai testnet to simplify access to testnet funds. You will top up an address with a specific amount of testnet MATIC. Later, you can use another EVM-compatible network of your choice.
Before you begin
Before you start this tutorial, complete the following items:
- If you are new to smart contract development, learn how to Deploy Your First Smart Contract.
- Set up a cryptocurrency wallet such as MetaMask.
- Fund your wallet with the following testnet tokens:
- Get testnet MATIC from faucet.polygon.technology to pay for your on-chain transactions.
- Get at least 2 ERC-677 testnet LINK from faucets.chain.link/mumbai.
Setup steps
Setting up the example requires the following steps:
- Deploy the upkeep contract.
- Configure the address watch list.
- Register the upkeep.
Deploy the upkeep contract
-
Open the
EthBalanceMonitor.sol
example contract in Remix. -
Compile the contract in Remix.
-
On the Deploy & Run Transactions tab in Remix, set your Environment to Injected Provider and allow Remix to connect to MetaMask.
-
The constructor requires a
keeperRegistryAddress
value and aminWaitPeriodSeconds
value. Specify these in the Deploy fields in Remix. You can find these registry addresses on the Automation Supported Networks page. For this example using Polygon Mumbai, enter the following values:- keeperRegistryAddress:
0xE16Df59B887e3Caa439E0b29B42bA2e7976FD8b2
- minWaitPeriodSeconds:
60
- keeperRegistryAddress:
-
Click Transact to deploy the contract with the defined constructor settings and accept the transaction in MetaMask. After the contract is deployed, it will appear in your Deployed Contracts list with several functions available to configure.
-
Use metamask to Send 0.001 MATIC to your contract address. The funds are used to top-up other contracts with MATIC. See the Fund Your Contracts page to learn how to find your contract address and send funds to those contracts. For this example, 0.001 MATIC is sufficient for demonstration purposes. In a production environment, you might store a larger amount of funds in the contract so Chainlink Automation can automatically distribute them to several different addresses as they are needed over time.
Configure the address watch list
Before your contract will fund an address, you must set the watchList
address array with minBalancesWei
and topUpAmmountsWei
variables. For this example on Polygon Mumbai, you are using testnet MATIC instead of wei (ETH). For demonstration purposes, you configure your own wallet as the top-up address. This makes it easy to see the MATIC being sent as part of the automated top-up function. After you complete this tutorial, you can configure any wallet or contract address that you want to keep funded.
-
In the list of functions for your deployed contract, run the
setWatchList
function. This function requires anaddresses
array, aminBalancesWei
array that maps to the addresses, and atopUpAmountsWei
array that also maps to the addresses. In Remix, arrays require brackets and quotes around both addresses and integer values. For this example, set the following values:- addresses:
["YOUR_WALLET_ADDRESS_OR_CONTRACT_ADDRESS"]
- minBalancesWei:
["100000000000000000000"]
- topUpAmountsWei:
["000100000000000000"]
These values tell the top up contract to top up the specified address with 0.0001 MATIC if the address balance is less than 100 MATIC. These settings are intended to demonstrate the example using testnet faucet funds. For a production application, you might set more reasonable values that top up a smart contract with 10 MATIC if the balance is less than 1 MATIC.
- addresses:
-
After you configure the function values, click transact to run the function. MetaMask asks you to confirm the transaction.
-
In the functions list, click the
getWatchList
function to confirm your settings are correct.
Register the upkeep
Now that the contract is deployed, funded, and configured, register the upkeep and Chainlink Automation will automatically run the example code.
-
Go to the automation.chain.link registration UI.
-
Click Connect wallet in the top right of the UI to connect your wallet.
-
After the site recognizes your wallet, click Register new Upkeep. The registration interface opens.
-
Select the Custom logic trigger option.
-
Copy your contract address from Remix and paste it into the Target contract address field.
-
Click Next to go to the Upkeep details page.
-
Specify a name for your upkeep and set a Starting balance of 2 LINK. Leave the other settings at their default values.
-
Click Register Upkeep to complete the registration process.
Now that you've registered the upkeep, Chainlink Automation handles the rest of the process.
Check your upkeeps
The upkeep runs the checkUpkeep
function in your contract, which checks the balances of all addresses in the watchList
against their defined limits. If any of the addresses are below their specified minimum balances, the upkeep runs the topUp
function for that specific address, which distributes the MATIC in your contract to that address. Unless your wallet happens to have more than 100 testnet MATIC, you will receive MATIC in your wallet every 60 seconds as defined by minWaitPeriodSeconds
in your contract. Check to make sure the example is running correctly:
-
Go to automation.chain.link, view your new upkeep, and confirm that it is performing upkeeps in the History list.
-
View your contract address and your wallet address at mumbai.polygonscan.com to see the transactions happening between your contract and your wallet address.
The example continues to run until your upkeep runs out of LINK, your contract runs out of MATIC, or until you manually pause or cancel the upkeep.
Clean up
After you are done with this example, you can run the withdraw
function on your contract to withdraw any remaining testnet MATIC so you can use it later. Also, you can cancel your upkeep in the Automation UI and withdraw any remaining unspent LINK.
Examine the example code
The EthBalanceMonitor
contract is ownable, pauseable, and compatible with the AutomationCompatibleInterface
contract:
- Ownable: The contract has an owner address, and provides basic authorization control functions. This simplifies the implementation of user permissions and allows for transfer of ownership.
- Pauseable: This feature allows the contract to implement a pause and unpause mechanism that the contract owner can trigger.
- Compatible: The
AutomationCompatibleInterface
is necessary to create contracts that are compatible with the Chainlink Automation Network. To learn more about theAutomationCompatibleInterface
and its uses and functions, read the Making Compatible Contracts guide.
Contract functions
Functions with an asterisk (*
) denote features that only the owner can change. Click on each function to learn more about its parameters and design patterns:
Function Name | Description |
---|---|
setWatchList * | Addresses to watch minimum balance and how much to top it up. |
setKeeperRegistryAddress * | Updates the KeeperRegistry address. |
setMinWaitPeriodSeconds * | Updates the global minimum period between top ups. |
topUp | Used by performUpkeep . This function will only trigger top up if conditions are met. |
Below are the feed functions in EthBalanceMonitor
:
Read Function Name | Description |
---|---|
getUnderfundedAddresses | View function used in checkUpkeep to find underfunded balances. |
getKeeperRegistryAddress | Views the KeeperRegistry address. |
getMinWaitPeriodSeconds | Views the global minimum period between top ups. |
getWatchList | Views addresses to watch minimum balance and how much to top it up. |
getAccountInfo | Provides information about the specific target address, including the last time it was topped up. This function is external only. |
setWatchList
Function
Parameters
Name | Description | Suggested Setting |
---|---|---|
addresses | The list of addresses to watch | (not applicable) |
minBalancesWei | The minimum balances for each address | 5000000000000000000 (5 ETH) |
topUpAmountsWei | The amount to top up each address | 5000000000000000000 (5 ETH) |
Only the owner can setWatchList
. Each of the parameters should be set with distinct requirements for each address.
setKeeperRegistryAddress
Function
Parameters
Name | Description |
---|---|
keeperRegistryAddress | Address that requires updating in KeeperRegistry |
Only the keeperRegistryAddress
can performUpkeep
, which is a global setting. KeeperRegistry
addresses can be found on the Chainlink Automation app. However, only the owner can set a new KeeperRegistry
after deployment.
setMinWaitPeriodSeconds
Function
Parameters
Name | Description | Suggested Setting |
---|---|---|
period | Minimum wait period (in seconds) for addresses between funding | 3600 (1 hour) |
period
denotes the length of time between top ups for a specific address. This is a global setting that prevents draining of funds from the contract if the private key for an address is compromised or if a gas spike occurs. However, only the owner can set a different minimum wait period after deployment.
topUp
Function
Parameters
Name | Description |
---|---|
needsFunding | List of addresses to fund (addresses must be pre-approved) |
Any address can trigger the topUp
function. This is an intentional design pattern that shows how easy it is to make an existing contract compatible with Chainlink Automation while maintaining an open interface. All validations are performed before the funding is triggered. If the conditions are not met, any attempt to top up will revert.