Account refilling
The goal of this task is to bridge assets from L1 to L2 every time the account balance on L2 gets under some threshold.
Task
import { Address, BigInt, environment, SwapBuilder, Token, TokenAmount, USD } from '@mimicprotocol/lib-ts'
import { inputs } from './types'
import { ERC20 } from './types/ERC20'
export default function main(): void {
if (inputs.slippage > 100) throw new Error('Slippage must be between 0 and 100')
const tokenIn = Token.fromAddress(inputs.tokenIn, inputs.sourceChain)
const tokenOut = Token.fromAddress(inputs.tokenOut, inputs.destinationChain)
const underlyingTokenAddress = aTokenContract.UNDERLYING_ASSET_ADDRESS()
const underlyingToken = Token.fromAddress(underlyingTokenAddress, aToken.chainId)
const me = environment.getContext().user
const tokenOutContract = new ERC20(tokenOut.address, tokenOut.chainId)
const recipientBalance = tokenOutContract.balanceOf(inputs.recipient)
const recipientBalanceAmount = TokenAmount.fromBigInt(tokenOut, recipientBalance)
const recipientBalanceUsd = recipientBalanceAmount.toUsd()
const thresholdUsd = USD.fromI32(inputs.thresholdUSD)
console.log('Recipient balance in USD: ' + recipientBalanceUsd.toString())
if (recipientBalanceUsd.lt(thresholdUsd)) console.log('Threshold not met')
else {
// Compute amount of token in needed to reach threshold
const usdToTopUp = thresholdUsd.minus(recipientBalanceUsd)
const amountOutNeeded = usdToTopUp.toTokenAmount(tokenOut)
const tokenInAmountNeeded = amountOutNeeded.toTokenAmount(tokenIn)
// Apply slippage tolerance for minAmountOut
const slippagePct = BigInt.fromI32(100).minus(BigInt.fromI32(inputs.slippage))
const minAmountOut = amountOutNeeded.times(slippagePct).div(BigInt.fromI32(100))
console.log('Min amount out: ' + minAmountOut.toString())
SwapBuilder.forChains(inputs.sourceChain, inputs.destinationChain)
.addTokenInFromTokenAmount(tokenInAmountNeeded)
.addTokenOutFromTokenAmount(minAmountOut, inputs.recipient)
.build()
.send()
}
}
Manifest
version: 1.0.0
name: Account Refill Task
description: Fund account bridging tokens from another chain when its balance is bellow certain threshold
inputs:
- sourceChain: uint32
- tokenIn: address
- destinationChain: uint32
- tokenOut: address
- recipient: address
- slippage: uint32
- thresholdUSD: uint32
Last updated