Skip to content

Commit

Permalink
Display contract balance correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
MrNaif2018 committed May 13, 2022
1 parent 19191d2 commit d435a05
Show file tree
Hide file tree
Showing 7 changed files with 30 additions and 16 deletions.
1 change: 0 additions & 1 deletion api/ext/shopify.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ async def shopify_invoice_update(event, event_data):
client = get_shopify_client(store)
if not await client.order_exists(order_id):
return
print("UPD", invoice.status)
if invoice.status in invoices.FAILED_STATUSES or invoice.status in invoices.PAID_STATUSES:
success = invoice.status in invoices.PAID_STATUSES
await update_shopify_status(client, order_id, invoice.id, invoice.currency, invoice.price, success)
Expand Down
8 changes: 7 additions & 1 deletion api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,9 +195,15 @@ async def add_fields(self):
await super().add_fields()
from api import utils

success, self.balance = await utils.wallets.get_confirmed_wallet_balance(self)
success, self.divisibility, self.balance = await utils.wallets.get_confirmed_wallet_balance(self)
self.error = not success

@classmethod
def process_kwargs(cls, kwargs):
kwargs = super().process_kwargs(kwargs)
kwargs.pop("divisibility", None)
return kwargs

async def validate(self, kwargs):
await super().validate(kwargs)
if "xpub" in kwargs or "contract" in kwargs:
Expand Down
4 changes: 3 additions & 1 deletion api/schemes.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,9 @@ class Wallet(CreateWallet):
@root_validator(pre=True)
def set_balance(cls, values):
if "balance" in values:
values["balance"] = currency_table.format_decimal(values.get("currency"), values["balance"])
values["balance"] = currency_table.format_decimal(
values.get("currency"), values["balance"], divisibility=values.get("divisibility")
)
return values


Expand Down
18 changes: 10 additions & 8 deletions api/utils/wallets.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,18 @@ async def get_wallet_history(model, response):
async def get_wallet_balance(wallet) -> Union[bool, Decimal]:
try:
coin = settings.settings.get_coin(wallet.currency, {"xpub": wallet.xpub, "contract": wallet.contract})
return True, await coin.balance()
divisibility = None if not wallet.contract else await coin.server.readcontract(wallet.contract, "decimals")
return True, divisibility, await coin.balance()
except (BitcartBaseError, HTTPException) as e:
logger.error(
f"Error getting wallet balance for wallet {wallet.id} with currency {wallet.currency}:\n{get_exception_message(e)}"
)
return False, {attr: Decimal(0) for attr in BTC.BALANCE_ATTRS}
return False, 8, {attr: Decimal(0) for attr in BTC.BALANCE_ATTRS}


async def get_confirmed_wallet_balance(wallet) -> Union[bool, Decimal]:
success, balance = await get_wallet_balance(wallet)
return success, balance["confirmed"]
success, divisibility, balance = await get_wallet_balance(wallet)
return success, divisibility, balance["confirmed"]


async def get_wallet_balances(user):
Expand All @@ -61,10 +62,11 @@ async def get_wallet_balances(user):
rates = {}
async with utils.database.iterate_helper():
async for wallet in models.Wallet.query.where(models.Wallet.user_id == user.id).gino.iterate():
_, crypto_balance = await get_confirmed_wallet_balance(wallet)
if wallet.currency in rates: # pragma: no cover
rate = rates[wallet.currency]
_, _, crypto_balance = await get_confirmed_wallet_balance(wallet)
cache_key = (wallet.currency, wallet.contract)
if cache_key in rates: # pragma: no cover
rate = rates[cache_key]
else:
rate = rates[wallet.currency] = await get_rate(wallet, show_currency)
rate = rates[cache_key] = await get_rate(wallet, show_currency)
balances += crypto_balance * rate
return currency_table.format_decimal(show_currency, currency_table.normalize(show_currency, balances))
6 changes: 4 additions & 2 deletions api/views/wallets.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,11 @@ async def get_wallet_balance(
model_id: str, user: models.User = Security(utils.authorization.AuthDependency(), scopes=["wallet_management"])
):
wallet = await utils.database.get_object(models.Wallet, model_id, user)
response = (await utils.wallets.get_wallet_balance(wallet))[1]
got = await utils.wallets.get_wallet_balance(wallet)
response = got[2]
divisibility = got[1]
for key in response:
response[key] = currency_table.format_decimal(wallet.currency, response[key])
response[key] = currency_table.format_decimal(wallet.currency, response[key], divisibility=divisibility)
return response


Expand Down
6 changes: 4 additions & 2 deletions daemons/eth.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,9 @@ def address(self):
return self.keystore.address

async def balance(self):
return to_dict(await get_balance(self.web3, self.address))
if self.contract:
return from_wei(await daemon.readcontract(self.contract, "balanceOf", self.address), self.divisibility)
return await get_balance(self.web3, self.address)

def stop(self, block_number):
self.running = False
Expand Down Expand Up @@ -905,7 +907,7 @@ def getaddresshistory(self, *args, **kwargs):

@rpc(requires_wallet=True, requires_network=True)
async def getbalance(self, wallet):
return {"confirmed": await self.wallets[wallet].balance()}
return {"confirmed": decimal_to_string(await self.wallets[wallet].balance(), self.wallets[wallet].divisibility)}

@rpc
def getconfig(self, key, wallet=None):
Expand Down
3 changes: 2 additions & 1 deletion tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,9 @@ async def test_no_exchange_rates_available(mocker, caplog, wallet):
@pytest.mark.anyio
async def test_broken_coin(mocker, caplog, wallet):
mocker.patch("bitcart.BTC.balance", side_effect=BitcartBaseError("Coin broken"))
success, balance = await utils.wallets.get_confirmed_wallet_balance(schemes.Wallet(**wallet))
success, divisibility, balance = await utils.wallets.get_confirmed_wallet_balance(schemes.Wallet(**wallet))
assert not success
assert divisibility == 8
assert balance == Decimal(0)
assert "Error getting wallet balance" in caplog.text

Expand Down

0 comments on commit d435a05

Please sign in to comment.