Reformat project

This commit is contained in:
2022-07-15 11:09:54 +01:00
parent 933642def6
commit ea81748c0a
29 changed files with 6924 additions and 1009 deletions

View File

@@ -3,18 +3,13 @@
# Large API. Lots of lines can't be avoided.
import json
import logging
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Union
from typing import Any, Dict, List, Optional, Union
import arrow
import treq
from twisted.internet.defer import inlineCallbacks
# Project imports
import util
from twisted.internet.defer import inlineCallbacks
__author__ = "marvin8"
__copyright__ = "(C) 2021 https://codeberg.org/MarvinsCryptoTools/agoradesk_py"
@@ -88,7 +83,8 @@ class AgoraDesk:
headers = {
"Content-Type": "application/json",
"User-Agent": f"agoradesk_py/{__version__} " f"https://codeberg.org/MarvinsCryptoTools/agoradesk_py",
"User-Agent": f"agoradesk_py/{__version__} "
f"https://codeberg.org/MarvinsCryptoTools/agoradesk_py",
"Authorization": self.api_key,
}
@@ -253,7 +249,9 @@ class AgoraDesk:
# ===========================
# post/feedback/{username} • Give feedback to a user
def feedback(self, username: str, feedback: str, msg: Optional[str]) -> Dict[str, Any]:
def feedback(
self, username: str, feedback: str, msg: Optional[str]
) -> Dict[str, Any]:
"""See Agoradesk API.
https://agoradesk.com/api-docs/v1#operation/setUserFeedback
@@ -279,7 +277,9 @@ class AgoraDesk:
https://agoradesk.com/api-docs/v1#operation/markPaid
"""
return self._api_call(api_method=f"contact_mark_as_paid/{trade_id}", http_method="POST")
return self._api_call(
api_method=f"contact_mark_as_paid/{trade_id}", http_method="POST"
)
# post/contact_cancel/{trade_id} • Cancel the trade
def contact_cancel(
@@ -299,7 +299,9 @@ class AgoraDesk:
# post/contact_escrow/{trade_id} • Enable escrow
# get/contact_messages/{trade_id} • Get trade messages
def contact_messages(self, trade_id: str, after: Optional[arrow.Arrow] = None) -> Dict[str, Any]:
def contact_messages(
self, trade_id: str, after: Optional[arrow.Arrow] = None
) -> Dict[str, Any]:
"""See Agoradesk API.
https://agoradesk.com/api-docs/v1#operation/getTradeMessages
@@ -354,7 +356,9 @@ class AgoraDesk:
# Todo: Add image upload functionality
# post/contact_message_post/{trade_id} • Send a chat message/attachment
def contact_message_post(self, trade_id: str, msg: Optional[str] = None) -> Dict[str, Any]:
def contact_message_post(
self, trade_id: str, msg: Optional[str] = None
) -> Dict[str, Any]:
"""See Agoradesk API.
https://agoradesk.com/api-docs/v1#operation/sendChatMessage
@@ -504,7 +508,9 @@ class AgoraDesk:
if track_max_amount:
params["track_max_amount"] = 1 if track_max_amount else 0
if require_trusted_by_advertiser:
params["require_trusted_by_advertiser"] = 1 if require_trusted_by_advertiser else 0
params["require_trusted_by_advertiser"] = (
1 if require_trusted_by_advertiser else 0
)
if verified_email_required:
params["verified_email_required"] = 1 if verified_email_required else 0
if online_provider:
@@ -680,7 +686,8 @@ class AgoraDesk:
params = self._generic_search_parameters(amount, page)
return self._api_call(
api_method=f"{direction}-{main_currency}-online/" f"{exchange_currency}{add_to_api_method}",
api_method=f"{direction}-{main_currency}-online/"
f"{exchange_currency}{add_to_api_method}",
query_values=params,
)
@@ -823,7 +830,8 @@ class AgoraDesk:
params = self._generic_search_parameters(amount, page)
return self._api_call(
api_method=f"{direction}-{main_currency}-with-cash/" f"{exchange_currency}/{country_code}/{lat}/{lon}",
api_method=f"{direction}-{main_currency}-with-cash/"
f"{exchange_currency}/{country_code}/{lat}/{lon}",
query_values=params,
)
@@ -938,7 +946,9 @@ class AgoraDesk:
# Statistics related API Methods
# ==============================
def moneroaverage(self, currency: Optional[str] = "ticker-all-currencies") -> Dict[str, Any]:
def moneroaverage(
self, currency: Optional[str] = "ticker-all-currencies"
) -> Dict[str, Any]:
"""See Agoradesk API.
https://agoradesk.com/api-docs/v1#operation/getXmrTicker and
@@ -1028,7 +1038,9 @@ class AgoraDesk:
if otp:
params["otp"] = otp
return self._api_call(api_method="wallet-send", http_method="POST", query_values=params)
return self._api_call(
api_method="wallet-send", http_method="POST", query_values=params
)
def wallet_send_xmr(
self,

View File

@@ -1,6 +1,6 @@
# Project imports
import util
import db
import util
class AntiFraud(util.Base):
@@ -46,7 +46,9 @@ class AntiFraud(util.Base):
return True
if platform_buyer in senders:
return True
self.ux.notify.notify_sender_name_mismatch(reference, platform_buyer, bank_sender)
self.ux.notify.notify_sender_name_mismatch(
reference, platform_buyer, bank_sender
)
return False
def check_tx_sender(self, tx, reference):
@@ -65,7 +67,9 @@ class AntiFraud(util.Base):
bank_sender = stored_tx["sender"]
platform_buyer = stored_trade["buyer"]
platform = stored_trade["subclass"]
is_allowed = self.check_valid_sender(reference, platform, bank_sender, platform_buyer)
is_allowed = self.check_valid_sender(
reference, platform, bank_sender, platform_buyer
)
if is_allowed is True:
return True
return False

View File

@@ -1,29 +1,22 @@
"""See https://agoradesk.com/api-docs/v1."""
# pylint: disable=too-many-lines
# Large API. Lots of lines can't be avoided.
import json
import logging
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Union
import arrow
# Project imports
import util
import hashlib
import hmac as hmac_lib
import requests
import json
import logging
import sys
import time
import treq
from twisted.internet.defer import inlineCallbacks
from typing import Any, Dict, List, Optional, Union
from urllib.parse import urlparse
import arrow
import requests
import treq
# Project imports
import util
from twisted.internet.defer import inlineCallbacks
__author__ = "marvin8"
__copyright__ = "(C) 2021 https://codeberg.org/MarvinsCryptoTools/agoradesk_py"
__version__ = "0.1.0"
@@ -86,17 +79,25 @@ class LocalBitcoins:
message += params_encoded.encode("ascii")
else:
message += params_encoded
signature = hmac_lib.new(self.hmac_secret, msg=message, digestmod=hashlib.sha256).hexdigest().upper()
signature = (
hmac_lib.new(self.hmac_secret, msg=message, digestmod=hashlib.sha256)
.hexdigest()
.upper()
)
return signature
def encode_params(self, http_method, api_call_url, query_values):
if http_method == "POST":
api_request = requests.Request("POST", api_call_url, data=query_values).prepare()
api_request = requests.Request(
"POST", api_call_url, data=query_values
).prepare()
params_encoded = api_request.body
# GET method
else:
api_request = requests.Request("GET", api_call_url, params=query_values).prepare()
api_request = requests.Request(
"GET", api_call_url, params=query_values
).prepare()
params_encoded = urlparse(api_request.url).query
return (api_request, params_encoded)
@@ -132,7 +133,9 @@ class LocalBitcoins:
url = url[len(SERVER) :] # noqa
# HMAC crypto stuff
api_request, params_encoded = self.encode_params(http_method, api_call_url, query_values)
api_request, params_encoded = self.encode_params(
http_method, api_call_url, query_values
)
nonce = str(int(time.time() * 1000)).encode("ascii")
signature = self.sign_payload(nonce, url, params_encoded)
@@ -288,7 +291,9 @@ class LocalBitcoins:
# ===========================
# post/feedback/{username} • Give feedback to a user
def feedback(self, username: str, feedback: str, msg: Optional[str]) -> Dict[str, Any]:
def feedback(
self, username: str, feedback: str, msg: Optional[str]
) -> Dict[str, Any]:
"""See LocalBitcoins API.
https://localbitcoins.com/api-docs/#feedback
@@ -314,7 +319,9 @@ class LocalBitcoins:
https://localbitcoins.com/api-docs/#contact-paid
"""
return self._api_call(api_method=f"contact_mark_as_paid/{trade_id}/", http_method="POST")
return self._api_call(
api_method=f"contact_mark_as_paid/{trade_id}/", http_method="POST"
)
# post/contact_cancel/{trade_id} • Cancel the trade
def contact_cancel(
@@ -334,7 +341,9 @@ class LocalBitcoins:
# post/contact_escrow/{trade_id} • Enable escrow
# get/contact_messages/{trade_id} • Get trade messages
def contact_messages(self, trade_id: str, after: Optional[arrow.Arrow] = None) -> Dict[str, Any]:
def contact_messages(
self, trade_id: str, after: Optional[arrow.Arrow] = None
) -> Dict[str, Any]:
"""See LocalBitcoins API.
https://localbitcoins.com/api-docs/#contact-message
@@ -389,7 +398,9 @@ class LocalBitcoins:
# Todo: Add image upload functionality
# post/contact_message_post/{trade_id} • Send a chat message/attachment
def contact_message_post(self, trade_id: str, msg: Optional[str] = None) -> Dict[str, Any]:
def contact_message_post(
self, trade_id: str, msg: Optional[str] = None
) -> Dict[str, Any]:
"""See LocalBitcoins API.
https://localbitcoins.com/api-docs/#contact-post
@@ -726,7 +737,8 @@ class LocalBitcoins:
params = self._generic_search_parameters(amount, page)
return self._api_call(
api_method=f"{direction}-{main_currency}-online/" f"{exchange_currency}{add_to_api_method}/.json",
api_method=f"{direction}-{main_currency}-online/"
f"{exchange_currency}{add_to_api_method}/.json",
query_values=params,
)

View File

@@ -1,8 +1,8 @@
# Other library imports
from json import dumps
import logstash
import logging
from json import dumps
import logstash
# Project imports
from settings import settings

View File

@@ -1,10 +1,10 @@
# Other library imports
from json import loads
import db
import util
# Project imports
from settings import settings
import util
import db
class Markets(util.Base):
@@ -60,7 +60,9 @@ class Markets(util.Base):
self.log.info(f"Sending bank details/reference for {platform}/{trade_id}")
if send_setting == "1":
account_info = self.get_matching_account_details(platform, currency)
formatted_account_info = self.format_payment_details(currency, account_info, real=True)
formatted_account_info = self.format_payment_details(
currency, account_info, real=True
)
if not formatted_account_info:
self.log.error(f"Payment info invalid: {formatted_account_info}")
return
@@ -110,12 +112,21 @@ class Markets(util.Base):
currencies = self.get_all_currencies(platform)
providers = self.get_all_providers(platform)
if platform == "lbtc":
providers = [self.sources.lbtc.map_provider(x, reverse=True) for x in providers]
providers = [
self.sources.lbtc.map_provider(x, reverse=True) for x in providers
]
sinks_currencies = self.sinks.currencies
supported_currencies = [currency for currency in currencies if currency in sinks_currencies]
supported_currencies = [
currency for currency in currencies if currency in sinks_currencies
]
currencies = supported_currencies
brute = [(asset, currency, provider) for asset in assets for currency in currencies for provider in providers]
brute = [
(asset, currency, provider)
for asset in assets
for currency in currencies
for provider in providers
]
for asset, currency, provider in brute:
# Filter currency
try:
@@ -123,22 +134,32 @@ class Markets(util.Base):
except KeyError:
# self.log.error("Error getting public ads for currency {currency}", currency=currency)
if currency == "GBP":
self.log.error("Error getting public ads for currency GBP, aborting")
self.log.error(
"Error getting public ads for currency GBP, aborting"
)
break
continue
# Filter asset
public_ads_filtered = [ad for ad in public_ads_currency if ad[4] == asset]
# Filter provider
public_ads_filtered = [ad for ad in public_ads_filtered if ad[3] == provider]
public_ads_filtered = [
ad for ad in public_ads_filtered if ad[3] == provider
]
our_ads = [ad for ad in public_ads_filtered if ad[1] == username]
if not our_ads:
self.log.warning(f"No ads found in {platform} public listing for {asset} {currency} {provider}")
self.log.warning(
f"No ads found in {platform} public listing for {asset} {currency} {provider}"
)
continue
new_margin = self.autoprice(username, min_margin, max_margin, public_ads_filtered, currency)
new_margin = self.autoprice(
username, min_margin, max_margin, public_ads_filtered, currency
)
# self.log.info("New rate for {currency}: {rate}", currency=currency, rate=new_margin)
if platform == "agora":
new_formula = f"coingecko{asset.lower()}usd*usd{currency.lower()}*{new_margin}"
new_formula = (
f"coingecko{asset.lower()}usd*usd{currency.lower()}*{new_margin}"
)
elif platform == "lbtc":
new_formula = f"btc_in_usd*{new_margin}*USD_in_{currency}"
for ad in our_ads:
@@ -172,7 +193,9 @@ class Markets(util.Base):
ads_without_us = [ad for ad in ads if not ad[1] == username]
# self.log.debug("Ads without us: {x}", x=ads_without_us)
# Find ads above our min that are not us
ads_above_our_min_not_us = [ad for ad in ads_without_us if ad[6] > float(min_margin)]
ads_above_our_min_not_us = [
ad for ad in ads_without_us if ad[6] > float(min_margin)
]
# self.log.debug("Ads above our min not us: {x}", x=ads_above_our_min_not_us)
# Check that this list without us is not empty
if ads_without_us:
@@ -247,7 +270,9 @@ class Markets(util.Base):
currencies = self.sinks.currencies
account_info = self.sinks.account_info
all_currencies = self.get_all_currencies(platform)
supported_currencies = [currency for currency in currencies if currency in all_currencies]
supported_currencies = [
currency for currency in currencies if currency in all_currencies
]
currency_account_info_map = {}
for currency in supported_currencies:
for bank, accounts in account_info.items():
@@ -255,11 +280,16 @@ class Markets(util.Base):
if account["currency"] == currency:
currency_account_info_map[currency] = account["account_number"]
currency_account_info_map[currency]["bank"] = bank.split("_")[0]
currency_account_info_map[currency]["recipient"] = account["recipient"]
currency_account_info_map[currency]["recipient"] = account[
"recipient"
]
return (supported_currencies, currency_account_info_map)
def get_matching_account_details(self, platform, currency):
supported_currencies, currency_account_info_map = self.get_valid_account_details(platform)
(
supported_currencies,
currency_account_info_map,
) = self.get_valid_account_details(platform)
if currency not in supported_currencies:
return False
return currency_account_info_map[currency]
@@ -278,7 +308,10 @@ class Markets(util.Base):
currencies = self.sinks.currencies
if not account_info:
account_info = self.sinks.account_info
supported_currencies, currency_account_info_map = self.get_valid_account_details(platform)
(
supported_currencies,
currency_account_info_map,
) = self.get_valid_account_details(platform)
# not_supported = [currency for currency in all_currencies if currency not in supported_currencies]
@@ -329,7 +362,9 @@ class Markets(util.Base):
"""
platforms = ("agora", "lbtc")
for platform in platforms:
self._distribute_account_details(platform, currencies=currencies, account_info=account_info)
self._distribute_account_details(
platform, currencies=currencies, account_info=account_info
)
def format_ad(self, asset, currency, payment_details_text):
"""

View File

@@ -1,19 +1,18 @@
# Twisted imports
from twisted.internet.task import LoopingCall
from twisted.internet.defer import inlineCallbacks
# Other library imports
from pycoingecko import CoinGeckoAPI
from forex_python.converter import CurrencyRates
import urllib3
import logging
from opensearchpy import OpenSearch
from datetime import datetime
import urllib3
import util
from forex_python.converter import CurrencyRates
from lib.logstash import send_logstash
from opensearchpy import OpenSearch
# Other library imports
from pycoingecko import CoinGeckoAPI
# Project imports
from settings import settings
import util
from lib.logstash import send_logstash
from twisted.internet.defer import inlineCallbacks
from twisted.internet.task import LoopingCall
# TODO: secure ES traffic properly
urllib3.disable_warnings()
@@ -74,7 +73,15 @@ class Money(util.Base):
total_remaining = self.get_total_remaining()
total_with_trades = self.get_total_with_trades()
# This will make them all run concurrently, hopefully not hitting rate limits
for x in (total, remaining, profit, profit_with_trades, open_trades, total_remaining, total_with_trades):
for x in (
total,
remaining,
profit,
profit_with_trades,
open_trades,
total_remaining,
total_with_trades,
):
yield x
def setup_loops(self):
@@ -382,7 +389,9 @@ class Money(util.Base):
if not total_usd:
return False
withdraw_threshold = float(settings.Money.BaseUSD) + float(settings.Money.WithdrawLimit)
withdraw_threshold = float(settings.Money.BaseUSD) + float(
settings.Money.WithdrawLimit
)
remaining = withdraw_threshold - total_usd
cast_es = {
"remaining_usd": remaining,
@@ -416,13 +425,17 @@ class Money(util.Base):
asset = "BTC"
if asset == "XMR":
amount_crypto = contact["data"]["amount_xmr"]
history = self.cg.get_coin_history_by_id(id="monero", date=date_formatted)
history = self.cg.get_coin_history_by_id(
id="monero", date=date_formatted
)
if "market_data" not in history:
return False
crypto_usd = float(history["market_data"]["current_price"]["usd"])
elif asset == "BTC":
amount_crypto = contact["data"]["amount_btc"]
history = self.cg.get_coin_history_by_id(id="bitcoin", date=date_formatted)
history = self.cg.get_coin_history_by_id(
id="bitcoin", date=date_formatted
)
crypto_usd = float(history["market_data"]["current_price"]["usd"])
# Convert crypto to fiat
amount = float(amount_crypto) * crypto_usd
@@ -476,7 +489,9 @@ class Money(util.Base):
if not total_usd:
return False
total_usd += total_trades_usd
withdraw_threshold = float(settings.Money.BaseUSD) + float(settings.Money.WithdrawLimit)
withdraw_threshold = float(settings.Money.BaseUSD) + float(
settings.Money.WithdrawLimit
)
remaining = withdraw_threshold - total_usd
cast_es = {

View File

@@ -1,16 +1,14 @@
# Twisted/Klein imports
from twisted.internet.defer import inlineCallbacks
# Other library imports
from json import dumps
from random import choices
from string import ascii_uppercase
# Project imports
from settings import settings
import db
import util
# Project imports
from settings import settings
from twisted.internet.defer import inlineCallbacks
class Transactions(util.Base):
@@ -95,7 +93,9 @@ class Transactions(util.Base):
if len(stored_trade_reference) > 1:
self.log.error(f"Multiple references valid for TXID {txid}: {reference}")
self.irc.sendmsg(f"Multiple references valid for TXID {txid}: {reference}")
self.ux.notify.notify_tx_lookup_failed(currency, amount, reference, "MULTIPLE_REFS_MATCH")
self.ux.notify.notify_tx_lookup_failed(
currency, amount, reference, "MULTIPLE_REFS_MATCH"
)
return False
if len(stored_trade_reference) == 0:
return None
@@ -105,10 +105,16 @@ class Transactions(util.Base):
amount_usd = self.money.to_usd(amount, currency)
# Amount is reliable here as it is checked by find_trade, so no need for stored_trade["amount"]
if float(amount_usd) > float(settings.Agora.AcceptableAltLookupUSD):
self.log.info("Not checking against amount and currency as amount exceeds MAX")
self.irc.sendmsg("Not checking against amount and currency as amount exceeds MAX")
self.log.info(
"Not checking against amount and currency as amount exceeds MAX"
)
self.irc.sendmsg(
"Not checking against amount and currency as amount exceeds MAX"
)
# Close here if the amount exceeds the allowable limit for no reference
self.ux.notify.notify_tx_lookup_failed(currency, amount, reference, "EXCEEDS_MAX")
self.ux.notify.notify_tx_lookup_failed(
currency, amount, reference, "EXCEEDS_MAX"
)
return False
return True
@@ -124,9 +130,15 @@ class Transactions(util.Base):
return False
stored_trade = self.find_trade(txid, currency, amount)
if not stored_trade:
self.log.info(f"Failed to get reference by amount and currency: {txid} {currency} {amount}")
self.irc.sendmsg(f"Failed to get reference by amount and currency: {txid} {currency} {amount}")
self.ux.notify.notify_tx_lookup_failed(currency, amount, reference, "ALT_LOOKUP_FAILED")
self.log.info(
f"Failed to get reference by amount and currency: {txid} {currency} {amount}"
)
self.irc.sendmsg(
f"Failed to get reference by amount and currency: {txid} {currency} {amount}"
)
self.ux.notify.notify_tx_lookup_failed(
currency, amount, reference, "ALT_LOOKUP_FAILED"
)
return None
stored_trade["amount"] = float(stored_trade["amount"]) # convert to float
return stored_trade
@@ -136,15 +148,21 @@ class Transactions(util.Base):
if not stored_trade:
self.log.info(f"No reference in DB for {reference}")
self.irc.sendmsg(f"No reference in DB for {reference}")
self.ux.notify.notify_tx_lookup_failed(currency, amount, reference, "NOREF", stored_trade_reference)
self.ux.notify.notify_tx_lookup_failed(
currency, amount, reference, "NOREF", stored_trade_reference
)
return False
stored_trade["amount"] = float(stored_trade["amount"]) # convert to float
return stored_trade
def currency_check(self, currency, amount, reference, stored_trade):
if not stored_trade["currency"] == currency:
self.log.info(f"Currency mismatch, Agora: {stored_trade['currency']} / Sink: {currency}")
self.irc.sendmsg(f"Currency mismatch, Agora: {stored_trade['currency']} / Sink: {currency}")
self.log.info(
f"Currency mismatch, Agora: {stored_trade['currency']} / Sink: {currency}"
)
self.irc.sendmsg(
f"Currency mismatch, Agora: {stored_trade['currency']} / Sink: {currency}"
)
self.ux.notify.notify_tx_lookup_failed(
currency,
amount,
@@ -157,9 +175,15 @@ class Transactions(util.Base):
def alt_amount_check(self, platform, amount, currency, reference, stored_trade):
# If the amount does not match exactly, get the min and max values for our given acceptable margins for trades
min_amount, max_amount = self.money.get_acceptable_margins(platform, currency, stored_trade["amount"])
self.log.info(f"Amount does not match exactly, trying with margins: min: {min_amount} / max: {max_amount}")
self.irc.sendmsg(f"Amount does not match exactly, trying with margins: min: {min_amount} / max: {max_amount}")
min_amount, max_amount = self.money.get_acceptable_margins(
platform, currency, stored_trade["amount"]
)
self.log.info(
f"Amount does not match exactly, trying with margins: min: {min_amount} / max: {max_amount}"
)
self.irc.sendmsg(
f"Amount does not match exactly, trying with margins: min: {min_amount} / max: {max_amount}"
)
if not min_amount < amount < max_amount:
self.log.info(
"Amount mismatch - not in margins: {stored_trade['amount']} (min: {min_amount} / max: {max_amount}"
@@ -209,9 +233,13 @@ class Transactions(util.Base):
db.r.hmset(f"tx.{txid}", to_store)
self.log.info(f"Transaction processed: {dumps(to_store, indent=2)}")
self.irc.sendmsg(f"AUTO Incoming transaction on {subclass}: {txid} {amount}{currency} ({reference})")
self.irc.sendmsg(
f"AUTO Incoming transaction on {subclass}: {txid} {amount}{currency} ({reference})"
)
stored_trade_reference = self.reference_partial_check(reference, txid, currency, amount)
stored_trade_reference = self.reference_partial_check(
reference, txid, currency, amount
)
if stored_trade_reference is False: # can be None though
return
@@ -220,14 +248,18 @@ class Transactions(util.Base):
# Normal implementation for when we have a reference
if stored_trade_reference:
stored_trade = self.normal_lookup(stored_trade_reference, reference, currency, amount)
stored_trade = self.normal_lookup(
stored_trade_reference, reference, currency, amount
)
# if not stored_trade:
# return
# Amount/currency lookup implementation for when we have no reference
else:
if not stored_trade: # check we don't overwrite the lookup above
stored_trade = self.amount_currency_lookup(amount, currency, txid, reference)
stored_trade = self.amount_currency_lookup(
amount, currency, txid, reference
)
if stored_trade is False:
return
if stored_trade:
@@ -249,13 +281,17 @@ class Transactions(util.Base):
if looked_up_without_reference:
return
platform = stored_trade["subclass"]
if not self.alt_amount_check(platform, amount, currency, reference, stored_trade):
if not self.alt_amount_check(
platform, amount, currency, reference, stored_trade
):
return
platform = stored_trade["subclass"]
platform_buyer = stored_trade["buyer"]
# Check sender - we don't do anything with this yet
sender_valid = self.antifraud.check_valid_sender(reference, platform, sender, platform_buyer)
sender_valid = self.antifraud.check_valid_sender(
reference, platform, sender, platform_buyer
)
self.log.info(f"Trade {reference} buyer {platform_buyer} valid: {sender_valid}")
# trade_released = self.release_map_trade(reference, txid)
# if trade_released:
@@ -325,7 +361,9 @@ class Transactions(util.Base):
return True
elif is_updated is False:
# Already mapped
self.log.error(f"Trade {reference} already has a TX mapped, cannot map {tx}.")
self.log.error(
f"Trade {reference} already has a TX mapped, cannot map {tx}."
)
return False
def new_trade(
@@ -396,9 +434,13 @@ class Transactions(util.Base):
# TODO: use get_ref_map in this function instead of calling get_ref multiple times
for ref in refs:
stored_trade = db.get_ref(ref)
if stored_trade["currency"] == currency and float(stored_trade["amount"]) == float(amount):
if stored_trade["currency"] == currency and float(
stored_trade["amount"]
) == float(amount):
matching_refs.append(stored_trade)
if len(matching_refs) != 1:
self.log.error(f"Find trade returned multiple results for TXID {txid}: {matching_refs}")
self.log.error(
f"Find trade returned multiple results for TXID {txid}: {matching_refs}"
)
return False
return matching_refs[0]