diff --git a/api/currencies.json b/api/currencies.json new file mode 100644 index 00000000..f246908d --- /dev/null +++ b/api/currencies.json @@ -0,0 +1,8 @@ +{ + "1":"USD", + "2":"EUR", + "3":"ETH", + "4":"AUD", + "5":"BRL", + "6":"CAD" +} diff --git a/api/logics.py b/api/logics.py index ec56372f..ecfb2f38 100644 --- a/api/logics.py +++ b/api/logics.py @@ -61,7 +61,7 @@ class Logics(): if order.is_explicit: satoshis_now = order.satoshis else: - exchange_rate = get_exchange_rate(Order.Currencies(order.currency).label) + exchange_rate = get_exchange_rate(Order.currency_dict[str(order.currency)]) premium_rate = exchange_rate * (1+float(order.premium)/100) satoshis_now = (float(order.amount) / premium_rate) * 100*1000*1000 @@ -350,4 +350,4 @@ class Logics(): return False, {'bad_request':'You cannot confirm the fiat payment at this stage'} order.save() - return True, None \ No newline at end of file + return True, None diff --git a/api/models.py b/api/models.py index 3a268841..359ba096 100644 --- a/api/models.py +++ b/api/models.py @@ -8,7 +8,7 @@ from django.utils.html import mark_safe from decouple import config from pathlib import Path from .utils import get_exchange_rate - +import json MIN_TRADE = int(config('MIN_TRADE')) MAX_TRADE = int(config('MAX_TRADE')) @@ -64,11 +64,6 @@ class Order(models.Model): BUY = 0, 'BUY' SELL = 1, 'SELL' - class Currencies(models.IntegerChoices): - USD = 1, 'USD' - EUR = 2, 'EUR' - ETH = 3, 'ETH' - class Status(models.IntegerChoices): WFB = 0, 'Waiting for maker bond' PUB = 1, 'Public' @@ -88,7 +83,10 @@ class Order(models.Model): FAI = 15, 'Failed lightning network routing' MLD = 16, 'Maker lost dispute' TLD = 17, 'Taker lost dispute' - + + currency_dict = json.load(open('./api/currencies.json')) + currency_choices = [(int(val), label) for val, label in list(currency_dict.items())] + print(currency_choices) # order info status = models.PositiveSmallIntegerField(choices=Status.choices, null=False, default=Status.WFB) @@ -97,7 +95,7 @@ class Order(models.Model): # order details type = models.PositiveSmallIntegerField(choices=Types.choices, null=False) - currency = models.PositiveSmallIntegerField(choices=Currencies.choices, null=False) + currency = models.PositiveSmallIntegerField(choices=currency_choices, null=False) amount = models.DecimalField(max_digits=9, decimal_places=4, validators=[MinValueValidator(0.00001)]) payment_method = models.CharField(max_length=35, null=False, default="not specified", blank=True) @@ -133,7 +131,7 @@ class Order(models.Model): def __str__(self): # Make relational back to ORDER - return (f'Order {self.id}: {self.Types(self.type).label} BTC for {float(self.amount)} {self.Currencies(self.currency).label}') + return (f'Order {self.id}: {self.Types(self.type).label} BTC for {float(self.amount)} {self.currency_dict[str(self.currency)]}') @receiver(pre_delete, sender=Order) def delelete_HTLCs_at_order_deletion(sender, instance, **kwargs): @@ -204,7 +202,7 @@ class MarketTick(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2, default=None, null=True, validators=[MinValueValidator(0)]) volume = models.DecimalField(max_digits=8, decimal_places=8, default=None, null=True, validators=[MinValueValidator(0)]) premium = models.DecimalField(max_digits=5, decimal_places=2, default=None, null=True, validators=[MinValueValidator(-100), MaxValueValidator(999)], blank=True) - currency = models.PositiveSmallIntegerField(choices=Order.Currencies.choices, null=True) + currency = models.PositiveSmallIntegerField(choices=Order.currency_choices, null=True) timestamp = models.DateTimeField(auto_now_add=True) # Relevant to keep record of the historical fee, so the insight on the premium can be better analyzed @@ -221,7 +219,7 @@ class MarketTick(models.Model): elif order.taker_bond.status == LNPayment.Status.LOCKED: volume = order.last_satoshis / 100000000 price = float(order.amount) / volume # Amount Fiat / Amount BTC - premium = 100 * (price / get_exchange_rate(Order.Currencies(order.currency).label) - 1) + premium = 100 * (price / get_exchange_rate(Order.currency_dict[str(order.currency)]) - 1) tick = MarketTick.objects.create( price=price, diff --git a/api/urls.py b/api/urls.py index 563fb14c..172994dd 100644 --- a/api/urls.py +++ b/api/urls.py @@ -1,5 +1,5 @@ from django.urls import path -from .views import MakerView, OrderView, UserView, BookView, InfoView +from .views import MakerView, OrderView, UserView, BookView, InfoView, get_currencies_json urlpatterns = [ path('make/', MakerView.as_view()), @@ -8,4 +8,5 @@ urlpatterns = [ path('book/', BookView.as_view()), # path('robot/') # Profile Info path('info/', InfoView.as_view()), + path('currencies/', get_currencies_json), ] \ No newline at end of file diff --git a/api/views.py b/api/views.py index 511891c9..4215f793 100644 --- a/api/views.py +++ b/api/views.py @@ -21,6 +21,9 @@ from datetime import timedelta from django.utils import timezone from decouple import config +import json +from django.http import HttpResponse + EXP_MAKER_BOND_INVOICE = int(config('EXP_MAKER_BOND_INVOICE')) FEE = float(config('FEE')) @@ -349,6 +352,7 @@ class BookView(ListAPIView): def get(self,request, format=None): currency = request.GET.get('currency') + print("currency:", currency) type = request.GET.get('type') queryset = Order.objects.filter(currency=currency, type=type, status=int(Order.Status.PUB)) if len(queryset)== 0: @@ -382,7 +386,10 @@ class InfoView(ListAPIView): context['total_volume'] = None return Response(context, status.HTTP_200_OK) - + +def get_currencies_json(request): + currency_dict = json.load(open('./api/currencies.json')) + return HttpResponse(json.dumps(currency_dict),content_type="application/json") diff --git a/frontend/src/components/BookPage.js b/frontend/src/components/BookPage.js index bdf30d83..10a591ae 100644 --- a/frontend/src/components/BookPage.js +++ b/frontend/src/components/BookPage.js @@ -9,7 +9,9 @@ export default class BookPage extends Component { orders: new Array(), currency: 1, type: 1, + currencies_dict: {"1":"USD"} }; + this.getCurrencyDict() this.getOrderDetails() this.state.currencyCode = this.getCurrencyCode(this.state.currency) } @@ -44,11 +46,19 @@ export default class BookPage extends Component { }) this.getOrderDetails(); } - + + getCurrencyDict() { + fetch('/api/currencies') + .then((response) => response.json()) + .then((data) => + this.setState({ + currencies_dict: data + })); + } // Gets currency code (3 letters) from numeric (e.g., 1 -> USD) // Improve this function so currencies are read from json getCurrencyCode(val){ - return (val == 1 ) ? "USD": ((val == 2 ) ? "EUR":"ETH") + return this.state.currencies_dict[val.toString()] } // pretty numbers @@ -156,9 +166,10 @@ export default class BookPage extends Component { }} onChange={this.handleCurrencyChange} > - USD - EUR - ETH + { + Object.entries(this.state.currencies_dict) + .map( ([key, value]) => {value} ) + } diff --git a/frontend/src/components/MakerPage.js b/frontend/src/components/MakerPage.js index 8057e86a..5bd46427 100644 --- a/frontend/src/components/MakerPage.js +++ b/frontend/src/components/MakerPage.js @@ -37,7 +37,9 @@ export default class MakerPage extends Component { payment_method: this.defaultPaymentMethod, premium: 0, satoshis: null, + currencies_dict: {"1":"USD"} } + this.getCurrencyDict() } handleTypeChange=(e)=>{ @@ -46,10 +48,9 @@ export default class MakerPage extends Component { }); } handleCurrencyChange=(e)=>{ - var code = (e.target.value == 1 ) ? "USD": ((e.target.value == 2 ) ? "EUR":"ETH") this.setState({ currency: e.target.value, - currencyCode: code, + currencyCode: this.getCurrencyCode(e.target.value), }); } handleAmountChange=(e)=>{ @@ -108,6 +109,20 @@ export default class MakerPage extends Component { & (data.id ? this.props.history.push('/order/' + data.id) :""))); } + getCurrencyDict() { + fetch('/api/currencies') + .then((response) => response.json()) + .then((data) => + this.setState({ + currencies_dict: data + })); + + } + + getCurrencyCode(val){ + return this.state.currencies_dict[val.toString()] + } + render() { return ( @@ -163,9 +178,10 @@ export default class MakerPage extends Component { }} onChange={this.handleCurrencyChange} > - USD - EUR - ETH + { + Object.entries(this.state.currencies_dict) + .map( ([key, value]) => {value} ) + } diff --git a/frontend/src/components/OrderPage.js b/frontend/src/components/OrderPage.js index 4030915b..9eff532f 100644 --- a/frontend/src/components/OrderPage.js +++ b/frontend/src/components/OrderPage.js @@ -68,8 +68,10 @@ export default class OrderPage extends Component { this.state = { isExplicit: false, delay: 5000, // Refresh every 5 seconds + currencies_dict: {"1":"USD"} }; this.orderId = this.props.match.params.orderId; + this.getCurrencyDict(); this.getOrderDetails(); } @@ -78,7 +80,6 @@ export default class OrderPage extends Component { fetch('/api/order' + '?order_id=' + this.orderId) .then((response) => response.json()) .then((data) => { - console.log(data) & this.setState({ statusCode: data.status, statusText: data.status_message, @@ -111,7 +112,6 @@ export default class OrderPage extends Component { }); } - // These are used to refresh the data componentDidMount() { this.interval = setInterval(this.tick, this.state.delay); @@ -132,8 +132,6 @@ export default class OrderPage extends Component { this.setState({ delay: Number(e.target.value) }); } - - // Gets currency code (3 letters) from numeric (e.g., 1 -> USD) // Improve this function so currencies are read from json getCurrencyCode(val){ @@ -158,6 +156,22 @@ export default class OrderPage extends Component { .then((response) => response.json()) .then((data) => (console.log(data) & this.getOrderDetails(data.id))); } + getCurrencyDict() { + fetch('/api/currencies') + .then((response) => response.json()) + .then((data) => + this.setState({ + currencies_dict: data + })); + } + + // Gets currency code (3 letters) from numeric (e.g., 1 -> USD) + // Improve this function so currencies are read from json + getCurrencyCode(val){ + console.log("---------------------------------") + console.log(val) + return this.state.currencies_dict[val.toString()] + } handleClickCancelOrderButton=()=>{ console.log(this.state) diff --git a/frontend/src/components/TradeBox.js b/frontend/src/components/TradeBox.js index eb819bf3..b278ffd0 100644 --- a/frontend/src/components/TradeBox.js +++ b/frontend/src/components/TradeBox.js @@ -160,31 +160,31 @@ export default class TradeBox extends Component { ) } - showInputInvoice(){ + // showInputInvoice(){ - } + // } - showWaitingForEscrow(){ + // showWaitingForEscrow(){ - } - showWaitingForBuyerInvoice({ + // } + // showWaitingForBuyerInvoice({ - }) + // }) - showFiatSentButton(){ + // showFiatSentButton(){ - } - showFiatReceivedButton(){ + // } + // showFiatReceivedButton(){ - } + // } - showOpenDisputeButton(){ + // showOpenDisputeButton(){ - } + // } - showRateSelect(){ + // showRateSelect(){ - } + // } render() { @@ -220,7 +220,7 @@ export default class TradeBox extends Component { {/* */} {/* */} - + diff --git a/frontend/urls.py b/frontend/urls.py index 74fb0594..d7b68630 100644 --- a/frontend/urls.py +++ b/frontend/urls.py @@ -8,5 +8,6 @@ urlpatterns = [ path('make/', index), path('book/', index), path('order/', index), - path('wait/', index), + path('wait/', index), + path('currencies/',index) ] \ No newline at end of file