[SETUP]
Connect to the network
Load the user account
Load the router contract
Load the token contracts
[DATA STRUCTURES]
Prepare a data structure for each token
[MAIN PROGRAM]
Get allowance and set approvals as needed
Set up loop
Fetch, store, and print swap rates
Print interesting results
Execute a single swap if our swap threshold is met
# [Set up]
import time
import datetime
import sys
from brownie import *
network.connect('avax-main')
user = accounts.load('test_account')
print("Loading Contracts:")
dai_contract = Contract.from_explorer(
'0xd586e7f844cea2f87f50152665bcbc2c279d8d70')
mim_contract = Contract.from_explorer(
'0x130966628846bfd36ff31a822705796e8cb8c18d')
wavax_contract = Contract.from_explorer(
'0xb31f66aa3c1e785363f0875a1b74e27b85fd66c7')
router_contract = Contract.from_explorer(
'0x60aE616a2155Ee3d9A68541Ba4544862310933d4')
# [[DATA STRUCTURES]
dai = {
"address": dai_contract.address,
"symbol": dai_contract.symbol(),
"decimals": dai_contract.decimals(),
"balance": dai_contract.balanceOf(user.address),
}
mim = {
"address": mim_contract.address,
"symbol": mim_contract.symbol(),
"decimals": mim_contract.decimals(),
"balance": mim_contract.balanceOf(user.address),
}
print(dai)
print(mim)
if mim["balance"] == 0:
sys.exit("MIM balance is zero, aborting...")
# [MAIN PROGRAM]
if mim_contract.allowance(user.address, router_contract.address) < mim["balance"]:
mim_contract.approve(
router_contract.address,
mim["balance"],
{'from': user.address},
)
last_ratio = 0.0
while True:
try:
qty_out = router_contract.getAmountsOut(
mim["balance"],
[
mim["address"],
wavax_contract.address,
dai["address"]
],
)[-1]
except:
print("Some error occurred, retrying...")
continue
ratio = round(qty_out / mim["balance"], 3)
if ratio != last_ratio:
print(
f"{datetime.datetime.now().strftime('[%I:%M:%S %p]')} MIM → DAI: ({ratio:.3f})"
)
last_ratio = ratio
if ratio >= 1.006:
print("*** EXECUTING SWAP ***")
try:
router_contract.swapExactTokensForTokens(
mim["balance"],
int(0.995 * qty_out),
[
mim["address"],
wavax_contract.address,
dai["address"]
],
user.address,
1000 * int(time.time() + 60),
{"from": user},
)
print("Swap success!")
except:
print("Swap failed, better luck next time!")
finally:
break
time.sleep(0.5)
먼저 router 컨트랙트에 위임한 MIM 갯수가 현재 보유하고 있는 MIM 갯수보다 적을 때 다시 approve해서 보유한 만큼 권한을 위임하도록 했다. 모니터링하고 있는 MIM -> DAI 의 스왑 비율이 1.006 이상일 때(스왑하면 0.6% 이득), 슬리피지는 0.5%로 두고 스왑을 진행하도록 설정. 코드 실행 결과 현재는 스왑 비율이 0.988이라서 스왑은 진행되지 않고 있다.
continue: 적어준 곳에서 해당 조건문 블록과 그 밖의 반복문 자체를 탈출
break: 조건문 블록을 탈출하여 아래 명령문은 실행하지 않고, 다음 반복문 실행절차를 수행
finally: 예외 발생 여부와 상관없이 항상 실행할 코드