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 { BigInt, ERC20Token, log, SwapBuilder, TokenAmount, USD } from '@mimicprotocol/lib-ts'

import { ERC20 } from './types/ERC20'
import { inputs } from './types'

export default function main(): void {
  if (inputs.slippage > 100) throw new Error('Slippage must be between 0 and 100')

  const tokenIn = ERC20Token.fromAddress(inputs.tokenIn, inputs.sourceChain)
  const tokenOut = ERC20Token.fromAddress(inputs.tokenOut, inputs.destinationChain)

  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)
  log.info('Recipient balance in USD: {}', [recipientBalanceUsd])

  if (recipientBalanceUsd.lt(thresholdUsd)) {
    // 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))
    log.info('Min amount out: {}', [minAmountOut])

    SwapBuilder.forChains(inputs.sourceChain, inputs.destinationChain)
      .addTokenInFromTokenAmount(tokenInAmountNeeded)
      .addTokenOutFromTokenAmount(minAmountOut, inputs.recipient)
      .build()
      .send()
  } else {
    log.info('Threshold not met')
  }
}

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