Skip to content

Commit

Permalink
fix: update initial requirements acc to traded assets limit
Browse files Browse the repository at this point in the history
  • Loading branch information
Divya-Solulab committed Oct 15, 2024
1 parent 5c3dd85 commit 55a95ad
Showing 1 changed file with 60 additions and 5 deletions.
65 changes: 60 additions & 5 deletions run_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@
import sys
import time
import typing as t
import math
from dataclasses import dataclass
from pathlib import Path
from decimal import Decimal, ROUND_UP

import requests
import yaml
Expand Down Expand Up @@ -59,7 +61,7 @@
COST_OF_BOND = 1
COST_OF_BOND_STAKING = 2 * 10 ** 19
STAKED_BONDING_TOKEN = "OLAS"
USDC_REQUIRED = 15_000_000
INITIAL_FUNDS_REQUIREMENT = {"USDC": 15_000_000, "ETH": 6_000_000_000_000_000}
USDC_ADDRESS = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
WARNING_ICON = colored('\u26A0', 'yellow')
OPERATE_HOME = Path.cwd() / ".optimus"
Expand Down Expand Up @@ -505,7 +507,59 @@ def get_service(manager: ServiceManager, template: ServiceTemplate) -> Service:
)

return service

def fetch_token_price(url: str, headers: dict) -> t.Optional[float]:
"""Fetch the price of a token from a given URL."""
try:
response = requests.get(url, headers=headers)
if response.status_code != 200:
print(f"Error fetching info from url {url}. Failed with status code: {response.status_code}")
return None
prices = response.json()
token = next(iter(prices))
return prices[token].get('usd', None)
except Exception as e:
print(f"Error fetching token price: {e}")
return None

def fetch_initial_funding_requirements() -> None:
"""Fetch initial funding requirements based on min_swap_amount_threshold."""
global INITIAL_FUNDS_REQUIREMENT
global CHAIN_ID_TO_METADATA

optimus_config = get_local_config()

headers = {
"accept": "application/json",
"x-cg-api-key": optimus_config.coingecko_api_key
}

# Fetch ETH price
eth_url = "https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd"
eth_price = fetch_token_price(eth_url, headers)
if eth_price is None:
print("Error: Could not fetch price for ETH.")
return

safety_margin = 500_000_000_000_000
eth_required = (optimus_config.min_swap_amount_threshold / eth_price)
eth_required_rounded = float(Decimal(eth_required).quantize(Decimal('0.0001'), rounding=ROUND_UP))
eth_required_in_wei = int((eth_required_rounded * 10 ** 18) + safety_margin)
INITIAL_FUNDS_REQUIREMENT['ETH'] = eth_required_in_wei
operational_fund_requirement = 15_000_000_000_000_000
CHAIN_ID_TO_METADATA[1]['firstTimeTopUp'] = eth_required_in_wei + operational_fund_requirement
# Fetch USDC price
usdc_url = f"https://api.coingecko.com/api/v3/simple/token_price/ethereum?contract_addresses={USDC_ADDRESS}&vs_currencies=usd"
usdc_price = fetch_token_price(usdc_url, headers)
if usdc_price is None:
print("Error: Could not fetch price for USDC.")
return

safety_margin = 1_000_000
usdc_required = (optimus_config.min_swap_amount_threshold / usdc_price)
usdc_required_rounded = math.ceil(usdc_required)
usdc_required_in_decimals = int((usdc_required_rounded * 10 ** 6) + safety_margin)
INITIAL_FUNDS_REQUIREMENT['USDC'] = usdc_required_in_decimals

def main() -> None:
"""Run service."""
Expand Down Expand Up @@ -554,7 +608,7 @@ def main() -> None:
wallet = operate.wallet_manager.load(ledger_type=LedgerType.ETHEREUM)

manager = operate.service_manager()

fetch_initial_funding_requirements()

for chain_id, configuration in service.chain_configs.items():
chain_metadata = CHAIN_ID_TO_METADATA[int(chain_id)]
Expand Down Expand Up @@ -654,7 +708,7 @@ def main() -> None:
)
spinner.start()

while get_erc20_balance(ledger_api, USDC_ADDRESS, address) < USDC_REQUIRED:
while get_erc20_balance(ledger_api, USDC_ADDRESS, address) < INITIAL_FUNDS_REQUIREMENT['USDC']:
time.sleep(1)

usdc_balance = get_erc20_balance(ledger_api, USDC_ADDRESS, address) / 10 ** 6
Expand All @@ -665,7 +719,8 @@ def main() -> None:
chain_id=chain_id,
fallback_staking_params=FALLBACK_STAKING_PARAMS,
)
manager.fund_service(hash=service.hash, chain_id=chain_id)
safe_fund_threshold=INITIAL_FUNDS_REQUIREMENT['ETH'] if chain_id == 1 else None
manager.fund_service(hash=service.hash, chain_id=chain_id, safe_fund_treshold=safe_fund_threshold)

usdc_balance = get_erc20_balance(ledger_api, USDC_ADDRESS, address) if chain_metadata.get("usdcRequired", False) else 0
if usdc_balance > 0:
Expand All @@ -676,7 +731,7 @@ def main() -> None:
token=USDC_ADDRESS,
safe_topup=usdc_balance,
agent_topup=0,
safe_fund_treshold=USDC_REQUIRED + usdc_balance,
safe_fund_treshold=INITIAL_FUNDS_REQUIREMENT['USDC'] + usdc_balance,
)

safes = {
Expand Down

0 comments on commit 55a95ad

Please sign in to comment.