This commit is contained in:
M
2020-09-21 14:50:26 +03:00
parent 5e1132a299
commit e4ebfc94b2
273 changed files with 2472 additions and 7285 deletions
@@ -0,0 +1,163 @@
import 'dart:convert';
import 'package:cake_wallet/exchange/trade_not_found_exeption.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
import 'package:cake_wallet/entities/crypto_currency.dart';
import 'package:cake_wallet/exchange/exchange_pair.dart';
import 'package:cake_wallet/exchange/exchange_provider.dart';
import 'package:cake_wallet/exchange/limits.dart';
import 'package:cake_wallet/exchange/trade.dart';
import 'package:cake_wallet/exchange/trade_request.dart';
import 'package:cake_wallet/exchange/trade_state.dart';
import 'package:cake_wallet/exchange/changenow/changenow_request.dart';
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/trade_not_created_exeption.dart';
class ChangeNowExchangeProvider extends ExchangeProvider {
ChangeNowExchangeProvider()
: super(
pairList: CryptoCurrency.all
.map((i) {
return CryptoCurrency.all.map((k) {
if (i == CryptoCurrency.btc && k == CryptoCurrency.xmr) {
return ExchangePair(from: i, to: k, reverse: false);
}
if (i == CryptoCurrency.xmr && k == CryptoCurrency.btc) {
return null;
}
return ExchangePair(from: i, to: k, reverse: true);
}).where((c) => c != null);
})
.expand((i) => i)
.toList());
static const apiUri = 'https://changenow.io/api/v1';
static const apiKey = secrets.change_now_api_key;
static const _exchangeAmountUriSufix = '/exchange-amount/';
static const _transactionsUriSufix = '/transactions/';
static const _minAmountUriSufix = '/min-amount/';
@override
String get title => 'ChangeNOW';
@override
ExchangeProviderDescription get description =>
ExchangeProviderDescription.changeNow;
@override
Future<Limits> fetchLimits({CryptoCurrency from, CryptoCurrency to}) async {
final symbol = from.toString() + '_' + to.toString();
final url = apiUri + _minAmountUriSufix + symbol;
final response = await get(url);
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final min = responseJSON['minAmount'] as double;
return Limits(min: min, max: null);
}
@override
Future<Trade> createTrade({TradeRequest request}) async {
const url = apiUri + _transactionsUriSufix + apiKey;
final _request = request as ChangeNowRequest;
final body = {
'from': _request.from.toString(),
'to': _request.to.toString(),
'address': _request.address,
'amount': _request.amount,
'refundAddress': _request.refundAddress
};
final response = await post(url,
headers: {'Content-Type': 'application/json'}, body: json.encode(body));
if (response.statusCode != 200) {
if (response.statusCode == 400) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['message'] as String;
throw TradeNotCreatedException(description, description: error);
}
throw TradeNotCreatedException(description);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final id = responseJSON['id'] as String;
final inputAddress = responseJSON['payinAddress'] as String;
final refundAddress = responseJSON['refundAddress'] as String;
final extraId = responseJSON['payinExtraId'] as String;
return Trade(
id: id,
from: _request.from,
to: _request.to,
provider: description,
inputAddress: inputAddress,
refundAddress: refundAddress,
extraId: extraId,
createdAt: DateTime.now(),
amount: _request.amount,
state: TradeState.created);
}
@override
Future<Trade> findTradeById({@required String id}) async {
final url = apiUri + _transactionsUriSufix + id + '/' + apiKey;
final response = await get(url);
if (response.statusCode != 200) {
if (response.statusCode == 400) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['message'] as String;
throw TradeNotFoundException(id,
provider: description, description: error);
}
throw TradeNotFoundException(id, provider: description);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final fromCurrency = responseJSON['fromCurrency'] as String;
final from = CryptoCurrency.fromString(fromCurrency);
final toCurrency = responseJSON['toCurrency'] as String;
final to = CryptoCurrency.fromString(toCurrency);
final inputAddress = responseJSON['payinAddress'] as String;
final expectedSendAmount = responseJSON['expectedSendAmount'].toString();
final status = responseJSON['status'] as String;
final state = TradeState.deserialize(raw: status);
final extraId = responseJSON['payinExtraId'] as String;
final outputTransaction = responseJSON['payoutHash'] as String;
return Trade(
id: id,
from: from,
to: to,
provider: description,
inputAddress: inputAddress,
amount: expectedSendAmount,
state: state,
extraId: extraId,
outputTransaction: outputTransaction);
}
@override
Future<double> calculateAmount(
{CryptoCurrency from, CryptoCurrency to, double amount}) async {
final url = apiUri +
_exchangeAmountUriSufix +
amount.toString() +
'/' +
from.toString() +
'_' +
to.toString();
final response = await get(url);
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final estimatedAmount = responseJSON['estimatedAmount'] as double;
return estimatedAmount;
}
}
@@ -0,0 +1,18 @@
import 'package:flutter/foundation.dart';
import 'package:cake_wallet/entities/crypto_currency.dart';
import 'package:cake_wallet/exchange/trade_request.dart';
class ChangeNowRequest extends TradeRequest {
ChangeNowRequest(
{@required this.from,
@required this.to,
@required this.address,
@required this.amount,
@required this.refundAddress});
CryptoCurrency from;
CryptoCurrency to;
String address;
String amount;
String refundAddress;
}
+9
View File
@@ -0,0 +1,9 @@
import 'package:cake_wallet/entities/crypto_currency.dart';
class ExchangePair {
ExchangePair({this.from, this.to, this.reverse = true});
final CryptoCurrency from;
final CryptoCurrency to;
final bool reverse;
}
+24
View File
@@ -0,0 +1,24 @@
import 'package:flutter/foundation.dart';
import 'package:cake_wallet/entities/crypto_currency.dart';
import 'package:cake_wallet/exchange/trade_request.dart';
import 'package:cake_wallet/exchange/exchange_pair.dart';
import 'package:cake_wallet/exchange/limits.dart';
import 'package:cake_wallet/exchange/trade.dart';
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
abstract class ExchangeProvider {
ExchangeProvider({this.pairList});
String get title;
List<ExchangePair> pairList;
ExchangeProviderDescription description;
@override
String toString() => title;
Future<Limits> fetchLimits({CryptoCurrency from, CryptoCurrency to});
Future<Trade> createTrade({TradeRequest request});
Future<Trade> findTradeById({@required String id});
Future<double> calculateAmount(
{CryptoCurrency from, CryptoCurrency to, double amount});
}
@@ -0,0 +1,26 @@
import 'package:cake_wallet/entities/enumerable_item.dart';
class ExchangeProviderDescription extends EnumerableItem<int>
with Serializable<int> {
const ExchangeProviderDescription({String title, int raw})
: super(title: title, raw: raw);
static const xmrto = ExchangeProviderDescription(title: 'XMR.TO', raw: 0);
static const changeNow =
ExchangeProviderDescription(title: 'ChangeNOW', raw: 1);
static const morphToken =
ExchangeProviderDescription(title: 'MorphToken', raw: 2);
static ExchangeProviderDescription deserialize({int raw}) {
switch (raw) {
case 0:
return xmrto;
case 1:
return changeNow;
case 2:
return morphToken;
default:
return null;
}
}
}
+35
View File
@@ -0,0 +1,35 @@
import 'package:hive/hive.dart';
part 'exchange_template.g.dart';
@HiveType(typeId: 7)
class ExchangeTemplate extends HiveObject {
ExchangeTemplate({
this.amount,
this.depositCurrency,
this.receiveCurrency,
this.provider,
this.depositAddress,
this.receiveAddress
});
static const boxName = 'ExchangeTemplate';
@HiveField(0)
String amount;
@HiveField(1)
String depositCurrency;
@HiveField(2)
String receiveCurrency;
@HiveField(3)
String provider;
@HiveField(4)
String depositAddress;
@HiveField(5)
String receiveAddress;
}
+20
View File
@@ -0,0 +1,20 @@
import 'package:flutter/foundation.dart';
import 'package:cake_wallet/exchange/trade.dart';
abstract class ExchangeTradeState {}
class ExchangeTradeStateInitial extends ExchangeTradeState {}
class TradeIsCreating extends ExchangeTradeState {}
class TradeIsCreatedSuccessfully extends ExchangeTradeState {
TradeIsCreatedSuccessfully({@required this.trade});
final Trade trade;
}
class TradeIsCreatedFailure extends ExchangeTradeState {
TradeIsCreatedFailure({@required this.error});
final String error;
}
+6
View File
@@ -0,0 +1,6 @@
class Limits {
const Limits({this.min, this.max});
final double min;
final double max;
}
+20
View File
@@ -0,0 +1,20 @@
import 'package:flutter/foundation.dart';
import 'package:cake_wallet/exchange/limits.dart';
abstract class LimitsState {}
class LimitsInitialState extends LimitsState {}
class LimitsIsLoading extends LimitsState {}
class LimitsLoadedSuccessfully extends LimitsState {
LimitsLoadedSuccessfully({@required this.limits});
final Limits limits;
}
class LimitsLoadedFailure extends LimitsState {
LimitsLoadedFailure({@required this.error});
final String error;
}
@@ -0,0 +1,202 @@
import 'dart:convert';
import 'package:cake_wallet/core/amount_converter.dart';
import 'package:cake_wallet/monero/monero_amount_format.dart';
import 'package:hive/hive.dart';
import 'package:cake_wallet/exchange/trade_not_found_exeption.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart';
import 'package:cake_wallet/entities/crypto_currency.dart';
import 'package:cake_wallet/exchange/exchange_pair.dart';
import 'package:cake_wallet/exchange/exchange_provider.dart';
import 'package:cake_wallet/exchange/limits.dart';
import 'package:cake_wallet/exchange/trade.dart';
import 'package:cake_wallet/exchange/trade_request.dart';
import 'package:cake_wallet/exchange/trade_state.dart';
import 'package:cake_wallet/exchange/morphtoken/morphtoken_request.dart';
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/trade_not_created_exeption.dart';
class MorphTokenExchangeProvider extends ExchangeProvider {
MorphTokenExchangeProvider({@required this.trades})
: super(pairList: [
ExchangePair(from: CryptoCurrency.xmr, to: CryptoCurrency.eth),
ExchangePair(from: CryptoCurrency.xmr, to: CryptoCurrency.bch),
ExchangePair(from: CryptoCurrency.xmr, to: CryptoCurrency.ltc),
ExchangePair(from: CryptoCurrency.xmr, to: CryptoCurrency.dash),
ExchangePair(from: CryptoCurrency.dash, to: CryptoCurrency.btc),
ExchangePair(from: CryptoCurrency.dash, to: CryptoCurrency.eth),
ExchangePair(from: CryptoCurrency.dash, to: CryptoCurrency.bch),
ExchangePair(from: CryptoCurrency.dash, to: CryptoCurrency.ltc),
ExchangePair(from: CryptoCurrency.dash, to: CryptoCurrency.xmr),
ExchangePair(from: CryptoCurrency.ltc, to: CryptoCurrency.btc),
ExchangePair(from: CryptoCurrency.ltc, to: CryptoCurrency.eth),
ExchangePair(from: CryptoCurrency.ltc, to: CryptoCurrency.bch),
ExchangePair(from: CryptoCurrency.ltc, to: CryptoCurrency.dash),
ExchangePair(from: CryptoCurrency.ltc, to: CryptoCurrency.xmr),
ExchangePair(from: CryptoCurrency.bch, to: CryptoCurrency.btc),
ExchangePair(from: CryptoCurrency.bch, to: CryptoCurrency.eth),
ExchangePair(from: CryptoCurrency.bch, to: CryptoCurrency.ltc),
ExchangePair(from: CryptoCurrency.bch, to: CryptoCurrency.dash),
ExchangePair(from: CryptoCurrency.bch, to: CryptoCurrency.xmr),
ExchangePair(from: CryptoCurrency.eth, to: CryptoCurrency.btc),
ExchangePair(from: CryptoCurrency.eth, to: CryptoCurrency.bch),
ExchangePair(from: CryptoCurrency.eth, to: CryptoCurrency.ltc),
ExchangePair(from: CryptoCurrency.eth, to: CryptoCurrency.dash),
ExchangePair(from: CryptoCurrency.eth, to: CryptoCurrency.xmr),
ExchangePair(from: CryptoCurrency.btc, to: CryptoCurrency.eth),
ExchangePair(from: CryptoCurrency.btc, to: CryptoCurrency.bch),
ExchangePair(from: CryptoCurrency.btc, to: CryptoCurrency.ltc),
ExchangePair(from: CryptoCurrency.btc, to: CryptoCurrency.dash),
ExchangePair(from: CryptoCurrency.btc, to: CryptoCurrency.xmr)
]);
Box<Trade> trades;
static const apiUri = 'https://api.morphtoken.com';
static const _morphURISuffix = '/morph';
static const _limitsURISuffix = '/limits';
static const _ratesURISuffix = '/rates';
static const weight = 10000;
@override
String get title => 'MorphToken';
@override
ExchangeProviderDescription get description =>
ExchangeProviderDescription.morphToken;
@override
Future<Limits> fetchLimits({CryptoCurrency from, CryptoCurrency to}) async {
final url = apiUri + _limitsURISuffix;
final headers = {'Content-type': 'application/json'};
final body = json.encode({
"input": {"asset": from.toString()},
"output": [
{"asset": to.toString(), "weight": weight}
]
});
final response = await post(url, headers: headers, body: body);
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final min = responseJSON['input']['limits']['min'] as int;
int max;
double ethMax;
if (from == CryptoCurrency.eth) {
ethMax = responseJSON['input']['limits']['max'] as double;
} else {
max = responseJSON['input']['limits']['max'] as int;
}
double minFormatted = AmountConverter.amountIntToDouble(from, min);
double maxFormatted = AmountConverter.amountIntToDouble(from, max);
return Limits(min: minFormatted, max: maxFormatted);
}
@override
Future<Trade> createTrade({TradeRequest request}) async {
const url = apiUri + _morphURISuffix;
final _request = request as MorphTokenRequest;
final body = {
"input": {
"asset": _request.from.toString(),
"refund": _request.refundAddress
},
"output": [
{
"asset": _request.to.toString(),
"weight": weight,
"address": _request.address
}
],
"tag": "cakewallet"
};
final response = await post(url,
headers: {'Content-Type': 'application/json'}, body: json.encode(body));
if (response.statusCode != 200) {
if (response.statusCode == 400) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['description'] as String;
throw TradeNotCreatedException(description, description: error);
}
throw TradeNotCreatedException(description);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final id = responseJSON['id'] as String;
return Trade(
id: id,
provider: description,
from: _request.from,
to: _request.to,
state: TradeState.created,
amount: _request.amount,
createdAt: DateTime.now());
}
@override
Future<Trade> findTradeById({@required String id}) async {
final url = apiUri + _morphURISuffix + '/' + id;
final response = await get(url);
if (response.statusCode != 200) {
if (response.statusCode == 400) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['description'] as String;
throw TradeNotFoundException(id,
provider: description, description: error);
}
throw TradeNotFoundException(id, provider: description);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final fromCurrency = responseJSON['input']['asset'] as String;
final from = CryptoCurrency.fromString(fromCurrency.toLowerCase());
final toCurrency = responseJSON['output'][0]['asset'] as String;
final to = CryptoCurrency.fromString(toCurrency.toLowerCase());
final inputAddress = responseJSON['input']['deposit_address'] as String;
final status = responseJSON['state'] as String;
final state = TradeState.deserialize(raw: status.toLowerCase());
String amount = "";
for (final trade in trades.values) {
if (trade.id == id) {
amount = trade.amount;
break;
}
}
return Trade(
id: id,
from: from,
to: to,
provider: description,
inputAddress: inputAddress,
amount: amount,
state: state);
}
@override
Future<double> calculateAmount(
{CryptoCurrency from, CryptoCurrency to, double amount}) async {
final url = apiUri + _ratesURISuffix;
final response = await get(url);
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final rate = responseJSON['data'][from.toString()][to.toString()] as String;
try {
final estimatedAmount = double.parse(rate) * amount;
return estimatedAmount;
} catch (e) {
return 0.0;
}
}
}
@@ -0,0 +1,18 @@
import 'package:flutter/foundation.dart';
import 'package:cake_wallet/entities/crypto_currency.dart';
import 'package:cake_wallet/exchange/trade_request.dart';
class MorphTokenRequest extends TradeRequest {
MorphTokenRequest(
{@required this.from,
@required this.to,
@required this.address,
@required this.amount,
@required this.refundAddress});
CryptoCurrency from;
CryptoCurrency to;
String address;
String amount;
String refundAddress;
}
+108
View File
@@ -0,0 +1,108 @@
import 'package:hive/hive.dart';
import 'package:cake_wallet/entities/crypto_currency.dart';
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/trade_state.dart';
import 'package:cake_wallet/entities/format_amount.dart';
part 'trade.g.dart';
@HiveType(typeId: 3)
class Trade extends HiveObject {
Trade(
{this.id,
ExchangeProviderDescription provider,
CryptoCurrency from,
CryptoCurrency to,
TradeState state,
this.createdAt,
this.expiredAt,
this.amount,
this.inputAddress,
this.extraId,
this.outputTransaction,
this.refundAddress,
this.walletId})
: providerRaw = provider?.raw,
fromRaw = from?.raw,
toRaw = to?.raw,
stateRaw = state?.raw;
static const boxName = 'Trades';
static const boxKey = 'tradesBoxKey';
@HiveField(0)
String id;
@HiveField(1)
int providerRaw;
ExchangeProviderDescription get provider =>
ExchangeProviderDescription.deserialize(raw: providerRaw);
@HiveField(2)
int fromRaw;
CryptoCurrency get from => CryptoCurrency.deserialize(raw: fromRaw);
@HiveField(3)
int toRaw;
CryptoCurrency get to => CryptoCurrency.deserialize(raw: toRaw);
@HiveField(4)
String stateRaw;
TradeState get state => TradeState.deserialize(raw: stateRaw);
@HiveField(5)
DateTime createdAt;
@HiveField(6)
DateTime expiredAt;
@HiveField(7)
String amount;
@HiveField(8)
String inputAddress;
@HiveField(9)
String extraId;
@HiveField(10)
String outputTransaction;
@HiveField(11)
String refundAddress;
@HiveField(12)
String walletId;
static Trade fromMap(Map map) {
return Trade(
id: map['id'] as String,
provider: ExchangeProviderDescription.deserialize(
raw: map['provider'] as int),
from: CryptoCurrency.deserialize(raw: map['input'] as int),
to: CryptoCurrency.deserialize(raw: map['output'] as int),
createdAt: map['date'] != null
? DateTime.fromMillisecondsSinceEpoch(map['date'] as int)
: null,
amount: map['amount'] as String,
walletId: map['wallet_id'] as String);
}
Map<String, dynamic> toMap() {
return <String, dynamic>{
'id': id,
'provider': provider.serialize(),
'input': from.serialize(),
'output': to.serialize(),
'date': createdAt != null ? createdAt.millisecondsSinceEpoch : null,
'amount': amount,
'wallet_id': walletId
};
}
String amountFormatted() => formatAmount(amount);
}
@@ -0,0 +1,19 @@
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/generated/i18n.dart';
class TradeNotCreatedException implements Exception {
TradeNotCreatedException(this.provider, {this.description = ''});
ExchangeProviderDescription provider;
String description;
@override
String toString() {
var text = provider != null
? S.current.trade_for_not_created(provider.title)
: S.current.trade_not_created;
text += ' $description';
return text;
}
}
@@ -0,0 +1,20 @@
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/generated/i18n.dart';
class TradeNotFoundException implements Exception {
TradeNotFoundException(this.tradeId, {this.provider, this.description = ''});
String tradeId;
ExchangeProviderDescription provider;
String description;
@override
String toString() {
var text = tradeId != null && provider != null
? S.current.trade_id_not_found(tradeId, provider.title)
: S.current.trade_not_found;
text += ' $description';
return text;
}
}
+1
View File
@@ -0,0 +1 @@
abstract class TradeRequest {}
+72
View File
@@ -0,0 +1,72 @@
import 'package:flutter/foundation.dart';
import 'package:cake_wallet/entities/enumerable_item.dart';
class TradeState extends EnumerableItem<String> with Serializable<String> {
const TradeState({@required String raw, @required String title})
: super(raw: raw, title: title);
@override
bool operator ==(Object other) => other is TradeState && other.raw == raw;
static const pending = TradeState(raw: 'pending', title: 'Pending');
static const confirming = TradeState(raw: 'confirming', title: 'Confirming');
static const trading = TradeState(raw: 'trading', title: 'Trading');
static const traded = TradeState(raw: 'traded', title: 'Traded');
static const complete = TradeState(raw: 'complete', title: 'Complete');
static const toBeCreated =
TradeState(raw: 'TO_BE_CREATED', title: 'To be created');
static const unpaid = TradeState(raw: 'UNPAID', title: 'Unpaid');
static const underpaid = TradeState(raw: 'UNDERPAID', title: 'Underpaid');
static const paidUnconfirmed =
TradeState(raw: 'PAID_UNCONFIRMED', title: 'Paid unconfirmed');
static const paid = TradeState(raw: 'PAID', title: 'Paid');
static const btcSent = TradeState(raw: 'BTC_SENT', title: 'Btc sent');
static const timeout = TradeState(raw: 'TIMED_OUT', title: 'Timeout');
static const notFound = TradeState(raw: 'NOT_FOUND', title: 'Not found');
static const created = TradeState(raw: 'created', title: 'Created');
static const finished = TradeState(raw: 'finished', title: 'Finished');
static const waiting = TradeState(raw: 'waiting', title: 'Waiting');
static const processing = TradeState(raw: 'processing', title: 'Processing');
static TradeState deserialize({String raw}) {
switch (raw) {
case 'pending':
return pending;
case 'confirming':
return confirming;
case 'trading':
return trading;
case 'traded':
return traded;
case 'complete':
return complete;
case 'TO_BE_CREATED':
return toBeCreated;
case 'UNPAID':
return unpaid;
case 'UNDERPAID':
return underpaid;
case 'PAID_UNCONFIRMED':
return paidUnconfirmed;
case 'PAID':
return paid;
case 'BTC_SENT':
return btcSent;
case 'TIMED_OUT':
return timeout;
case 'created':
return created;
case 'finished':
return finished;
case 'waiting':
return waiting;
case 'processing':
return processing;
default:
return null;
}
}
@override
int get hashCode => raw.hashCode ^ title.hashCode;
}
@@ -0,0 +1,198 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart';
import 'package:cake_wallet/entities/crypto_currency.dart';
import 'package:cake_wallet/exchange/exchange_pair.dart';
import 'package:cake_wallet/exchange/exchange_provider.dart';
import 'package:cake_wallet/exchange/limits.dart';
import 'package:cake_wallet/exchange/trade.dart';
import 'package:cake_wallet/exchange/trade_request.dart';
import 'package:cake_wallet/exchange/trade_state.dart';
import 'package:cake_wallet/exchange/xmrto/xmrto_trade_request.dart';
import 'package:cake_wallet/exchange/trade_not_created_exeption.dart';
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/exchange/trade_not_found_exeption.dart';
class XMRTOExchangeProvider extends ExchangeProvider {
XMRTOExchangeProvider()
: super(pairList: [
ExchangePair(
from: CryptoCurrency.xmr, to: CryptoCurrency.btc, reverse: false)
]);
static const userAgent = 'CakeWallet/XMR iOS';
static const originalApiUri = 'https://xmr.to/api/v2/xmr2btc';
static const proxyApiUri = 'https://xmrproxy.net/api/v2/xmr2btc';
static const _orderParameterUriSufix = '/order_parameter_query';
static const _orderStatusUriSufix = '/order_status_query/';
static const _orderCreateUriSufix = '/order_create/';
static String _apiUri = '';
static Future<String> getApiUri() async {
if (_apiUri != null && _apiUri.isNotEmpty) {
return _apiUri;
}
const url = originalApiUri + _orderParameterUriSufix;
final response =
await get(url, headers: {'Content-Type': 'application/json'});
_apiUri = response.statusCode == 403 ? proxyApiUri : originalApiUri;
return _apiUri;
}
@override
String get title => 'XMR.TO';
@override
ExchangeProviderDescription get description =>
ExchangeProviderDescription.xmrto;
double _rate = 0;
@override
Future<Limits> fetchLimits({CryptoCurrency from, CryptoCurrency to}) async {
final url = await getApiUri() + _orderParameterUriSufix;
final response = await get(url);
final correction = 0.001;
if (response.statusCode != 200) {
return Limits(min: 0, max: 0);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
double min = responseJSON['lower_limit'] as double;
double max = responseJSON['upper_limit'] as double;
final price = responseJSON['price'] as double;
if (price > 0) {
try {
min = min/price + correction;
min = _limitsFormat(min);
max = max/price - correction;
max = _limitsFormat(max);
} catch (e) {
min = 0;
max = 0;
}
} else {
min = 0;
max = 0;
}
return Limits(min: min, max: max);
}
@override
Future<Trade> createTrade({TradeRequest request}) async {
final _request = request as XMRTOTradeRequest;
final url = await getApiUri() + _orderCreateUriSufix;
final body = {
'xmr_amount': _request.amount,
'btc_dest_address': _request.address
};
final response = await post(url,
headers: {'Content-Type': 'application/json'}, body: json.encode(body));
if (response.statusCode != 201) {
if (response.statusCode == 400) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['error_msg'] as String;
throw TradeNotCreatedException(description, description: error);
}
throw TradeNotCreatedException(description);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final uuid = responseJSON["uuid"] as String;
return Trade(
id: uuid,
provider: description,
from: _request.from,
to: _request.to,
state: TradeState.created,
amount: _request.amount,
createdAt: DateTime.now());
}
@override
Future<Trade> findTradeById({@required String id}) async {
const headers = {
'Content-Type': 'application/json',
'User-Agent': userAgent
};
final url = await getApiUri() + _orderStatusUriSufix;
final body = {'uuid': id};
final response = await post(url, headers: headers, body: json.encode(body));
if (response.statusCode != 200) {
if (response.statusCode == 400) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['error_msg'] as String;
throw TradeNotFoundException(id,
provider: description, description: error);
}
throw TradeNotFoundException(id, provider: description);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final address = responseJSON['xmr_receiving_integrated_address'] as String;
final paymentId = responseJSON['xmr_required_payment_id_short'] as String;
final amount = responseJSON['xmr_amount_total'].toString();
final stateRaw = responseJSON['state'] as String;
final expiredAtRaw = responseJSON['expires_at'] as String;
final expiredAt = DateTime.parse(expiredAtRaw).toLocal();
final outputTransaction = responseJSON['btc_transaction_id'] as String;
final state = TradeState.deserialize(raw: stateRaw);
return Trade(
id: id,
provider: description,
from: CryptoCurrency.xmr,
to: CryptoCurrency.btc,
inputAddress: address,
extraId: paymentId,
expiredAt: expiredAt,
amount: amount,
state: state,
outputTransaction: outputTransaction);
}
@override
Future<double> calculateAmount(
{CryptoCurrency from, CryptoCurrency to, double amount}) async {
if (from != CryptoCurrency.xmr && to != CryptoCurrency.btc) {
return 0;
}
if (_rate == null || _rate == 0) {
_rate = await _fetchRates();
}
final double result = _rate * amount;
return double.parse(result.toStringAsFixed(12));
}
Future<double> _fetchRates() async {
try {
final url = await getApiUri() + _orderParameterUriSufix;
final response =
await get(url, headers: {'Content-Type': 'application/json'});
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final price = responseJSON['price'] as double;
return price;
} catch (e) {
print(e.toString());
return 0.0;
}
}
double _limitsFormat(double limit) => double.parse(limit.toStringAsFixed(3));
}
@@ -0,0 +1,18 @@
import 'package:flutter/foundation.dart';
import 'package:cake_wallet/entities/crypto_currency.dart';
import 'package:cake_wallet/exchange/trade_request.dart';
class XMRTOTradeRequest extends TradeRequest {
XMRTOTradeRequest(
{@required this.from,
@required this.to,
@required this.amount,
@required this.address,
@required this.refundAddress});
final CryptoCurrency from;
final CryptoCurrency to;
final String amount;
final String address;
final String refundAddress;
}