Skip to content

Commit

Permalink
Merge pull request #35 from madnesspie/post-estimate-fee
Browse files Browse the repository at this point in the history
Post estimate fee
  • Loading branch information
madnesspie committed Jun 5, 2020
2 parents c934e25 + 1f36e5a commit 5011ce4
Show file tree
Hide file tree
Showing 13 changed files with 70 additions and 44 deletions.
2 changes: 1 addition & 1 deletion django_obm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__version__ = "0.2.5"
__version__ = "0.3.0"
16 changes: 0 additions & 16 deletions django_obm/logger.py

This file was deleted.

7 changes: 4 additions & 3 deletions django_obm/management/commands/synctransactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,19 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import time
import traceback

from django.conf import settings
from django.core.management.base import BaseCommand

from django_obm import logger, models
from django_obm import models


class Command(BaseCommand):
DEFAULT_FREQUENCY = 60
logger = logger.get(__name__)
logger = logging.getLogger(__name__)
help = "Sync transactions with blockchain with specified frequency."

def add_arguments(self, parser):
Expand Down Expand Up @@ -60,7 +61,7 @@ def handle(self, *args, **options):
while True:
self.logger.debug("Run synchronization")
try:
result = models.Node.objects.sync_transactions()
models.Node.objects.sync_transactions()
except Exception as exc: # pylint: disable=broad-except
if options["raise_errors"]:
raise exc
Expand Down
2 changes: 1 addition & 1 deletion django_obm/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ def __init__(self, *args, **kwargs):
def __str__(self):
return self.name

def save(self, *args, **kwargs): # pylint: disable=arguments-differ
def save(self, *args, **kwargs): # pylint: disable=arguments-differ, signature-differs
validators.validate_node_is_supported(self.name)
default_nodes = self.currency.nodes.filter(is_default=True).exclude(
id=self.id
Expand Down
17 changes: 17 additions & 0 deletions django_obm/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,20 @@ def create(self, validated_data):
return models.Address.objects.create(
value=address_value, currency=currency,
)


# pylint: disable=abstract-method
class CurrencyEstimateFeeSerializer(serializers.Serializer):
currency = serializers.CharField(required=True)

def validate(self, attrs):
currency_name = attrs["currency"]
currency = models.Currency.objects \
.filter(name=currency_name) \
.first()
if not currency:
raise serializers.ValidationError(
f"Currency '{currency.name}'' does not exist."
)
attrs["currency"] = currency
return attrs
13 changes: 8 additions & 5 deletions django_obm/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,14 @@ class CurrencyViewSet(viewsets.ModelViewSet):
serializer_class = serializers.CurrencySerializer
queryset = models.Currency.objects.all()

@decorators.action(detail=True, methods=["get"])
def estimated_fee(
self, request, pk=None
): # pylint: disable=unused-argument
currency = self.get_object()
# pylint: disable=unused-argument, no-self-use
@decorators.action(detail=False, methods=["post"])
def estimate_fee(self, request):
serializer = serializers.CurrencyEstimateFeeSerializer(
data=request.data
)
assert serializer.is_valid(raise_exception=True)
currency = serializer.validated_data["currency"]
node = currency.default_node
estimated_fee = node.estimate_fee(
from_address=request.query_params.get("from_address"),
Expand Down
11 changes: 8 additions & 3 deletions example/example/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,10 @@
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import logging
import os
import sys

from django_obm import logger

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

Expand Down Expand Up @@ -123,6 +122,12 @@
STATIC_URL = "/static/"

# Logging
logging.addLevelName(logging.DEBUG, "🐛 DEBUG")
logging.addLevelName(logging.INFO, "📑 INFO")
logging.addLevelName(logging.WARNING, "⚠️ WARNING")
logging.addLevelName(logging.ERROR, "🚨 ERROR")
logging.addLevelName(logging.CRITICAL, "💥 CRITICAL")

LOGGING = {
"version": 1,
"disable_existing_loggers": True,
Expand All @@ -136,7 +141,7 @@
"filters": {
"info_filter": {
"()": "django.utils.log.CallbackFilter",
"callback": logger.info_filter,
"callback": lambda record: record.levelno < logging.WARNING,
},
},
"handlers": {
Expand Down
4 changes: 3 additions & 1 deletion pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ disable=
fixme,
too-many-ancestors,
logging-format-interpolation,
R0801, # Stupid similar lines in 2 files :)
R0801, # Stupid similar lines in 2 files :),
bad-continuation,
logging-fstring-interpolation,


[REPORTS]
Expand Down
2 changes: 1 addition & 1 deletion pytest.ini
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[pytest]
addopts = -vs -r fEP --tb=short --maxfail=1 --reuse-db
addopts = -vs -r fEP --tb=short --reuse-db
markers =
integration: Run integration tests with main test suite.
DJANGO_SETTINGS_MODULE = tests.settings
Expand Down
7 changes: 5 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,13 @@ def geth_node(ethereum_currency):
node.delete()


# pylint: disable=unused-argument
@pytest.fixture(params=["bitcoin-core", "geth"])
def node(
request, geth_node, bitcoin_core_node
): # pylint: disable=unused-argument
request,
geth_node,
bitcoin_core_node
):
node_mapping = {
'bitcoin-core': bitcoin_core_node,
'geth': geth_node,
Expand Down
11 changes: 8 additions & 3 deletions tests/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,10 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import os
import sys

from django_obm import logger

SECRET_KEY = "fake-key"
INSTALLED_APPS = [
"django.contrib.auth",
Expand All @@ -32,6 +31,12 @@
}

# Logging
logging.addLevelName(logging.DEBUG, "🐛 DEBUG")
logging.addLevelName(logging.INFO, "📑 INFO")
logging.addLevelName(logging.WARNING, "⚠️ WARNING")
logging.addLevelName(logging.ERROR, "🚨 ERROR")
logging.addLevelName(logging.CRITICAL, "💥 CRITICAL")

LOGGING = {
"version": 1,
"disable_existing_loggers": True,
Expand All @@ -45,7 +50,7 @@
"filters": {
"info_filter": {
"()": "django.utils.log.CallbackFilter",
"callback": logger.info_filter,
"callback": lambda record: record.levelno < logging.WARNING,
},
},
"handlers": {
Expand Down
20 changes: 13 additions & 7 deletions tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,17 @@ def test_get(client):

@staticmethod
@pytest.mark.django_db
def test_get_estimated_fee(monkeypatch, client, node):
def test_get_estimate_fee(monkeypatch, client, node):
monkeypatch.setattr(
models.Node, "estimate_fee", lambda *_, **__: 0.0001,
models.Node,
"estimate_fee",
lambda *_, **__: 0.0001,
)
response = client.get(
urls.reverse("currency-estimated-fee", args=(node.id,),)
response = client.post(
urls.reverse("currency-estimate-fee"),
data={
"currency": node.connector.currency,
}
)
assert response.status_code == 200
result = response.json()
Expand All @@ -48,13 +53,14 @@ def test_get_estimated_fee(monkeypatch, client, node):
class TestCurrencyViewSetIntegration:
@staticmethod
@pytest.mark.django_db
def test_get_estimated_fee(client, node):
def test_get_estimate_fee(client, node):
ethereum_tx = {
"currency": node.connector.currency,
"to_address": str(os.environ.get("GETH_IN_WALLET_ADDRESS")),
"amount": 10,
}
response = client.get(
urls.reverse("currency-estimated-fee", args=(node.id,)),
response = client.post(
urls.reverse("currency-estimate-fee"),
data=ethereum_tx,
)
assert response.status_code == 200
Expand Down
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ envlist =

[testenv]
extras = tests
commands = pytest -vs -r fEP --tb=short --maxfail=1 --reuse-db {posargs}
commands = pytest -vs -r fEP --tb=short --reuse-db {posargs}
setenv =
PYTHONPATH = {toxinidir}:{env:PYTHONPATH:}

Expand Down

0 comments on commit 5011ce4

Please sign in to comment.