cake_wallet/lib/exchange/provider/changenow_exchange_provider.dart

292 lines
10 KiB
Dart
Raw Permalink Normal View History

2020-01-04 19:31:52 +00:00
import 'dart:convert';
import 'dart:io';
2020-01-04 19:31:52 +00:00
import 'package:cake_wallet/.secrets.g.dart' as secrets;
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
2020-09-21 11:50:26 +00:00
import 'package:cake_wallet/exchange/limits.dart';
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
2020-09-21 11:50:26 +00:00
import 'package:cake_wallet/exchange/trade.dart';
import 'package:cake_wallet/exchange/trade_not_found_exception.dart';
2020-09-21 11:50:26 +00:00
import 'package:cake_wallet/exchange/trade_request.dart';
import 'package:cake_wallet/exchange/trade_state.dart';
import 'package:cake_wallet/exchange/utils/currency_pairs_utils.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/utils/device_info.dart';
import 'package:cake_wallet/utils/distribution_info.dart';
import 'package:cake_wallet/wallet_type_utils.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:http/http.dart';
2020-01-04 19:31:52 +00:00
class ChangeNowExchangeProvider extends ExchangeProvider {
ChangeNowExchangeProvider({required SettingsStore settingsStore})
: _settingsStore = settingsStore,
_lastUsedRateId = '',
super(pairList: supportedPairs(_notSupported));
static const List<CryptoCurrency> _notSupported = [
CryptoCurrency.zaddr,
CryptoCurrency.xhv,
];
2020-01-08 12:26:34 +00:00
static final apiKey =
DeviceInfo.instance.isMobile ? secrets.changeNowApiKey : secrets.changeNowApiKeyDesktop;
2022-01-26 15:44:15 +00:00
static const apiAuthority = 'api.changenow.io';
static const createTradePath = '/v2/exchange';
static const findTradeByIdPath = '/v2/exchange/by-id';
static const estimatedAmountPath = '/v2/exchange/estimated-amount';
static const rangePath = '/v2/exchange/range';
static const apiHeaderKey = 'x-changenow-api-key';
2020-01-04 19:31:52 +00:00
final SettingsStore _settingsStore;
String _lastUsedRateId;
2020-01-08 12:26:34 +00:00
@override
2020-01-04 19:31:52 +00:00
String get title => 'ChangeNOW';
2020-01-08 12:26:34 +00:00
2020-11-10 14:58:40 +00:00
@override
bool get isAvailable => true;
@override
bool get isEnabled => true;
@override
bool get supportsFixedRate => true;
2020-01-08 12:26:34 +00:00
@override
ExchangeProviderDescription get description => ExchangeProviderDescription.changeNow;
2020-01-04 19:31:52 +00:00
2020-11-10 14:58:40 +00:00
@override
Future<bool> checkIsAvailable() async => true;
2020-01-08 12:26:34 +00:00
@override
Future<Limits> fetchLimits(
{required CryptoCurrency from,
required CryptoCurrency to,
required bool isFixedRateMode}) async {
2022-01-26 15:44:15 +00:00
final headers = {apiHeaderKey: apiKey};
final params = <String, String>{
'fromCurrency': _normalizeCurrency(from),
'toCurrency': _normalizeCurrency(to),
'fromNetwork': _networkFor(from),
'toNetwork': _networkFor(to),
'flow': _getFlow(isFixedRateMode)
};
2022-01-26 15:44:15 +00:00
final uri = Uri.https(apiAuthority, rangePath, params);
final response = await get(uri, headers: headers);
2022-01-26 15:44:15 +00:00
if (response.statusCode == 400) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
2022-01-26 15:44:15 +00:00
final error = responseJSON['error'] as String;
final message = responseJSON['message'] as String;
throw Exception('${error}\n$message');
}
if (response.statusCode != 200)
2022-10-12 17:09:57 +00:00
throw Exception('Unexpected http status: ${response.statusCode}');
2022-01-26 15:44:15 +00:00
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
return Limits(
min: responseJSON['minAmount'] as double?, max: responseJSON['maxAmount'] as double?);
2020-01-04 19:31:52 +00:00
}
@override
Future<double> fetchRate(
{required CryptoCurrency from,
required CryptoCurrency to,
required double amount,
required bool isFixedRateMode,
required bool isReceiveAmount}) async {
try {
if (amount == 0) return 0.0;
final headers = {apiHeaderKey: apiKey};
final isReverse = isReceiveAmount;
final type = isReverse ? 'reverse' : 'direct';
final params = <String, String>{
'fromCurrency': _normalizeCurrency(from),
'toCurrency': _normalizeCurrency(to),
'fromNetwork': _networkFor(from),
'toNetwork': _networkFor(to),
'type': type,
'flow': _getFlow(isFixedRateMode)
};
if (isReverse)
params['toAmount'] = amount.toString();
else
params['fromAmount'] = amount.toString();
final uri = Uri.https(apiAuthority, estimatedAmountPath, params);
final response = await get(uri, headers: headers);
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final fromAmount = double.parse(responseJSON['fromAmount'].toString());
final toAmount = double.parse(responseJSON['toAmount'].toString());
final rateId = responseJSON['rateId'] as String? ?? '';
if (rateId.isNotEmpty) _lastUsedRateId = rateId;
return isReverse ? (amount / fromAmount) : (toAmount / amount);
} catch (e) {
print(e.toString());
return 0.0;
}
}
2020-01-08 12:26:34 +00:00
@override
2022-10-12 17:09:57 +00:00
Future<Trade> createTrade({required TradeRequest request, required bool isFixedRateMode}) async {
final distributionPath = await DistributionInfo.instance.getDistributionPath();
final formattedAppVersion = int.tryParse(_settingsStore.appVersion.replaceAll('.', '')) ?? 0;
final payload = {
'app': isMoneroOnly ? 'monerocom' : 'cakewallet',
'device': Platform.operatingSystem,
'distribution': distributionPath,
'version': formattedAppVersion
};
final headers = {apiHeaderKey: apiKey, 'Content-Type': 'application/json'};
final type = isFixedRateMode ? 'reverse' : 'direct';
final body = <String, dynamic>{
'fromCurrency': _normalizeCurrency(request.fromCurrency),
'toCurrency': _normalizeCurrency(request.toCurrency),
'fromNetwork': _networkFor(request.fromCurrency),
'toNetwork': _networkFor(request.toCurrency),
if (!isFixedRateMode) 'fromAmount': request.fromAmount,
if (isFixedRateMode) 'toAmount': request.toAmount,
'address': request.toAddress,
'flow': _getFlow(isFixedRateMode),
'type': type,
'refundAddress': request.refundAddress,
'payload': payload,
2020-01-04 19:31:52 +00:00
};
2022-01-26 15:44:15 +00:00
if (isFixedRateMode) {
// since we schedule to calculate the rate every 5 seconds we need to ensure that
// we have the latest rate id with the given inputs before creating the trade
await fetchRate(
from: request.fromCurrency,
to: request.toCurrency,
amount: double.tryParse(request.toAmount) ?? 0,
isFixedRateMode: true,
isReceiveAmount: true,
);
2022-01-26 15:44:15 +00:00
body['rateId'] = _lastUsedRateId;
}
2020-01-08 12:26:34 +00:00
2022-01-26 15:44:15 +00:00
final uri = Uri.https(apiAuthority, createTradePath);
final response = await post(uri, headers: headers, body: json.encode(body));
2022-01-26 15:44:15 +00:00
if (response.statusCode == 400) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['error'] as String;
final message = responseJSON['message'] as String;
throw Exception('${error}\n$message');
}
2020-01-04 19:31:52 +00:00
if (response.statusCode != 200)
2022-10-12 17:09:57 +00:00
throw Exception('Unexpected http status: ${response.statusCode}');
2020-01-04 19:31:52 +00:00
2020-01-08 12:26:34 +00:00
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?;
final payoutAddress = responseJSON['payoutAddress'] as String;
2020-01-04 19:31:52 +00:00
return Trade(
2020-01-08 12:26:34 +00:00
id: id,
from: request.fromCurrency,
to: request.toCurrency,
2020-01-04 19:31:52 +00:00
provider: description,
2020-01-08 12:26:34 +00:00
inputAddress: inputAddress,
refundAddress: refundAddress,
extraId: extraId,
2020-01-04 19:31:52 +00:00
createdAt: DateTime.now(),
amount: responseJSON['fromAmount']?.toString() ?? request.fromAmount,
state: TradeState.created,
payoutAddress: payoutAddress);
2020-01-04 19:31:52 +00:00
}
2020-01-08 12:26:34 +00:00
@override
2022-10-12 17:09:57 +00:00
Future<Trade> findTradeById({required String id}) async {
2022-01-26 15:44:15 +00:00
final headers = {apiHeaderKey: apiKey};
final params = <String, String>{'id': id};
final uri = Uri.https(apiAuthority, findTradeByIdPath, params);
2022-01-26 15:44:15 +00:00
final response = await get(uri, headers: headers);
2020-01-04 19:31:52 +00:00
if (response.statusCode == 404) throw TradeNotFoundException(id, provider: description);
2020-01-08 12:26:34 +00:00
2022-01-26 15:44:15 +00:00
if (response.statusCode == 400) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['message'] as String;
2020-01-04 19:31:52 +00:00
throw TradeNotFoundException(id, provider: description, description: error);
2022-01-26 15:44:15 +00:00
}
if (response.statusCode != 200)
2022-10-12 17:09:57 +00:00
throw Exception('Unexpected http status: ${response.statusCode}');
2020-01-04 19:31:52 +00:00
2020-01-08 12:26:34 +00:00
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;
2022-01-26 15:44:15 +00:00
final expectedSendAmount = responseJSON['expectedAmountFrom'].toString();
2020-01-08 12:26:34 +00:00
final status = responseJSON['status'] as String;
final state = TradeState.deserialize(raw: status);
final extraId = responseJSON['payinExtraId'] as String?;
final outputTransaction = responseJSON['payoutHash'] as String?;
final expiredAtRaw = responseJSON['validUntil'] as String?;
final payoutAddress = responseJSON['payoutAddress'] as String;
final expiredAt = DateTime.tryParse(expiredAtRaw ?? '')?.toLocal();
return Trade(
id: id,
from: from,
to: to,
provider: description,
inputAddress: inputAddress,
amount: expectedSendAmount,
state: state,
extraId: extraId,
expiredAt: expiredAt,
outputTransaction: outputTransaction,
payoutAddress: payoutAddress);
2020-01-04 19:31:52 +00:00
}
String _getFlow(bool isFixedRate) => isFixedRate ? 'fixed-rate' : 'standard';
String _networkFor(CryptoCurrency currency) {
switch (currency) {
case CryptoCurrency.usdt:
return 'btc';
default:
return currency.tag != null ? _normalizeTag(currency.tag!) : currency.title.toLowerCase();
}
}
String _normalizeCurrency(CryptoCurrency currency) {
if (currency.title == "USDC" && currency.tag == "POLY") {
throw "Only Bridged USDC (USDC.e) is allowed in ChangeNow";
}
switch (currency) {
case CryptoCurrency.zec:
return 'zec';
default:
return currency.title.toLowerCase();
}
}
String _normalizeTag(String tag) {
switch (tag) {
case 'POLY':
return 'matic';
case 'LN':
return 'lightning';
case 'AVAXC':
return 'cchain';
default:
return tag.toLowerCase();
}
}
}