refactor: delete dead Cake Pay/buy/exchange code; split di setup()

- Cake Pay: 36 files (~5.3k LOC) plus DI registrations, routes, and UI
  branches (feature was hard-disabled and unreachable)
- unreachable buy providers: robinhood, dfx, onramper, meld, kryptonim
  (~1.7k LOC); MoonPay untouched
- exchange providers that only existed as commented-out wiring:
  changenow, sideshift, chainflip, exolix, swaptrade, letsexchange,
  stealthex, xoswap, swapsxyz, thorchain, simpleswap (~5.2k LOC);
  Trocador untouched; ExchangeProviderDescription values and Hive
  adapters kept so stored trades and orders still deserialize
- di.dart setup() split from one 1,452-line function into 10 sequential
  chunk functions; registration execution order verified identical
  before and after (251 register calls)
This commit is contained in:
jwinterm
2026-08-15 16:29:03 -04:00
parent 71706314fb
commit adece963c3
75 changed files with 74 additions and 13200 deletions
@@ -1,431 +0,0 @@
import 'dart:convert';
import 'dart:math';
import 'package:hash_wallet/.secrets.g.dart' as secrets;
import 'package:hash_wallet/exchange/exchange_provider_description.dart';
import 'package:hash_wallet/exchange/limits.dart';
import 'package:hash_wallet/exchange/provider/exchange_provider.dart';
import 'package:hash_wallet/exchange/trade.dart';
import 'package:hash_wallet/exchange/trade_request.dart';
import 'package:hash_wallet/exchange/trade_state.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:hash_wallet/utils/exchange_provider_logger.dart';
class ChainflipExchangeProvider extends ExchangeProvider {
ChainflipExchangeProvider();
static final List<CryptoCurrency> _supported = [
CryptoCurrency.btc,
CryptoCurrency.eth,
CryptoCurrency.usdc,
CryptoCurrency.usdterc20,
CryptoCurrency.flip,
CryptoCurrency.wbtc,
CryptoCurrency.sol,
CryptoCurrency.usdcsol,
CryptoCurrency.usdtSol,
CryptoCurrency.arbEth,
CryptoCurrency.usdcArb,
CryptoCurrency.usdtArb,
];
static const _baseURL = 'chainflip-broker.io';
static const _assetsPath = '/assets';
static const _quotePath = '/quotes-native';
static const _swapPath = '/swap';
static const _txInfoPath = '/status-by-deposit-channel';
static const _affiliateBps = secrets.chainflipAffiliateFee;
static const _affiliateKey = secrets.chainflipApiKey;
@override
String get title => 'Chainflip';
@override
bool get isAvailable => true;
@override
bool get isEnabled => true;
@override
bool get supportsFixedRate => false;
@override
ExchangeProviderDescription get description =>
ExchangeProviderDescription.chainflip;
@override
Future<bool> checkIsAvailable() async => true;
@override
Future<Limits?> fetchLimits(
{required CryptoCurrency from,
required CryptoCurrency to,
required bool isFixedRateMode}) async {
try {
if(!_supported.contains(from) || !_supported.contains(to)) {
throw Exception('No rates found for $from to $to');
}
final assetId = _normalizeCurrency(from);
final assetsResponse = await _getAssets();
final assets = assetsResponse['assets'] as List<dynamic>;
final minAmount = assets.firstWhere(
(asset) => asset['id'] == assetId,
orElse: () => null)?['minimalAmountNative'] ?? '0';
if (minAmount == '0') throw Exception('No rates found for $from to $to');
return Limits(min: _amountFromNative(minAmount.toString(), from));
} catch (e) {
printV(e.toString());
throw Exception('Chainflip failed to fetch limits');
}
}
@override
Future<double> fetchRate({
required CryptoCurrency from,
required CryptoCurrency to,
required double amount,
required bool isFixedRateMode,
required bool isReceiveAmount
}) async {
// TODO: It seems this rate is getting cached, and re-used for different amounts, can we not do this?
try {
if (amount == 0) return 0.0;
if(!_supported.contains(from) || !_supported.contains(to)) return 0.0;
final quoteParams = {
'apiKey': _affiliateKey,
'sourceAsset': _normalizeCurrency(from),
'destinationAsset': _normalizeCurrency(to),
'amount': _amountToNative(amount, from),
'commissionBps': _affiliateBps
};
final quoteResponse = await _getSwapQuote(quoteParams);
final expectedAmountOut =
quoteResponse['egressAmountNative'] as String? ?? '0';
final rate = _amountFromNative(expectedAmountOut, to) / amount;
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'fetchRate',
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
'quoteParams': quoteParams,
},
responseData: {
'expectedAmountOut': expectedAmountOut,
'rate': rate,
'quoteResponse': quoteResponse,
},
);
return rate;
} catch (e, s) {
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
error: e,
stackTrace: s,
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
},
);
printV(e.toString());
return 0.0;
}
}
@override
Future<Trade> createTrade(
{required TradeRequest request,
required bool isFixedRateMode,
required bool isSendAll}) async {
try {
final maxSlippage = 2;
final quoteParams = {
'apiKey': _affiliateKey,
'sourceAsset': _normalizeCurrency(request.fromCurrency),
'destinationAsset': _normalizeCurrency(request.toCurrency),
'amount': _amountToNative(double.parse(request.fromAmount), request.fromCurrency),
'commissionBps': _affiliateBps
};
final quoteResponse = await _getSwapQuote(quoteParams);
final estimatedPrice = quoteResponse['estimatedPrice'] as double;
final minimumPrice = estimatedPrice * (100 - maxSlippage) / 100;
final swapParams = {
'apiKey': _affiliateKey,
'sourceAsset': _normalizeCurrency(request.fromCurrency),
'destinationAsset': _normalizeCurrency(request.toCurrency),
'destinationAddress': request.toAddress,
'commissionBps': _affiliateBps,
'minimumPrice': minimumPrice.toString(),
'refundAddress': request.refundAddress,
'boostFee': '6',
'retryDurationInBlocks': '150'
};
if (quoteResponse.containsKey('numberOfChunks') && quoteResponse.containsKey('chunkIntervalBlocks')) {
swapParams.addAll({
'numberOfChunks': quoteResponse['numberOfChunks'].toString(),
'chunkIntervalBlocks': quoteResponse['chunkIntervalBlocks'].toString(),
});
}
final swapResponse = await _openDepositChannel(swapParams);
final id = '${swapResponse['issuedBlock']}-${swapResponse['network'].toString()}-${swapResponse['channelId']}';
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'createTrade',
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'quoteParams': quoteParams,
'swapParams': swapParams,
},
responseData: {
'id': id,
'inputAddress': swapResponse['address'].toString(),
'estimatedPrice': estimatedPrice,
'minimumPrice': minimumPrice,
'swapResponse': swapResponse,
},
);
return Trade(
id: id,
from: request.fromCurrency,
to: request.toCurrency,
provider: description,
inputAddress: swapResponse['address'].toString(),
createdAt: DateTime.now(),
amount: request.fromAmount,
receiveAmount: request.toAmount,
state: TradeState.waiting,
payoutAddress: request.toAddress,
isSendAll: isSendAll,
);
} catch (e, s) {
ExchangeProviderLogger.logError(
provider: description,
function: 'createTrade',
error: e,
stackTrace: s,
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
},
);
printV(e.toString());
rethrow;
}
}
@override
Future<Trade> findTradeById({required String id}) async {
try {
final channelParts = id.split('-');
final network = channelParts[1];
final normalizedNetwork = _normalizeNetworkName(network);
final statusParams = {
'apiKey': _affiliateKey,
'issuedBlock': channelParts[0],
'network': normalizedNetwork,
'channelId': channelParts[2]
};
final statusResponse = await _getStatus(statusParams);
if (statusResponse == null)
throw Exception('Trade not found for id: $id');
final status = statusResponse['status'];
final currentState = _determineState(status['state'].toString());
final depositAmount = status['deposit']?['amount']?.toString() ?? '0.0';
final receiveAmount = status['swapEgress']?['amount']?.toString() ?? '0.0';
final refundAmount = status['refundEgress']?['amount']?.toString() ?? '0.0';
final isRefund = status['refundEgress'] != null;
final amount = isRefund ? refundAmount : receiveAmount;
final from = status['sourceAsset'].toString();
final to = status['destinationAsset'].toString();
final newTrade = Trade(
id: id,
from: _toCurrency(from),
to: _toCurrency(to),
provider: description,
amount: depositAmount,
receiveAmount: amount,
state: currentState,
payoutAddress: status['destinationAddress'].toString(),
outputTransaction:
status['swapEgress']?['transactionReference']?.toString(),
isRefund: isRefund,
);
return newTrade;
} catch (e) {
printV(e.toString());
rethrow;
}
}
String _normalizeCurrency(CryptoCurrency currency) {
final tag = currency.tag?.toLowerCase();
final title = currency.title.toLowerCase();
// Naive assets without network tag
if (tag == null) return '$title.$title';
return '$title.$tag';
}
String _normalizeNetworkName (String name) {
final networkName = switch (name) {
'BITCOIN' => 'Bitcoin',
'ETHEREUM' => 'Ethereum',
'ARBITRUM' => 'Arbitrum',
'SOLANA' => 'Solana',
_ => name
};
return networkName;
}
CryptoCurrency? _toCurrency(String name) {
final currency = switch (name) {
'btc.btc' => CryptoCurrency.btc,
'eth.eth' => CryptoCurrency.eth,
'usdc.eth' => CryptoCurrency.usdc,
'usdt.eth' => CryptoCurrency.usdterc20,
'flip.eth' => CryptoCurrency.flip,
'wbtc.eth' => CryptoCurrency.wbtc,
'sol.sol' => CryptoCurrency.sol,
'usdc.sol' => CryptoCurrency.usdcsol,
'eth.arb' => CryptoCurrency.arbEth,
'usdc.arb' => CryptoCurrency.usdcArb,
'usdt.arb' => CryptoCurrency.usdtArb,
_ => null
};
return currency;
}
String _amountToNative(double amount, CryptoCurrency currency) =>
(amount * pow(10, currency.decimals)).toInt().toString();
double _amountFromNative(String amount, CryptoCurrency currency) =>
double.parse(amount) / pow(10, currency.decimals);
Future<Map<String, dynamic>> _getAssets() async =>
_getRequest(_assetsPath, {});
Future<Map<String, dynamic>> _openDepositChannel(Map<String, String> params) async =>
_getRequest(_swapPath, params);
Future<Map<String, dynamic>> _getRequest(String path, Map<String, String> params) async {
final uri = Uri.https(_baseURL, path, params);
final response = await ProxyWrapper().get(clearnetUri: uri);
if ((response.statusCode != 200) || (response.body.contains('error'))) {
throw Exception('Unexpected response: ${response.statusCode} / ${uri.toString()} / ${response.body}');
}
return json.decode(response.body) as Map<String, dynamic>;
}
Future<Map<String, dynamic>> _getSwapQuote(Map<String, String> params) async {
final uri = Uri.https(_baseURL, _quotePath, params);
final response = await ProxyWrapper().get(clearnetUri: uri);
if ((response.statusCode != 200) || (response.body.contains('error'))) {
throw Exception('Unexpected response: ${response.statusCode} / ${uri.toString()} / ${response.body}');
}
final List<dynamic> jsonList = json.decode(response.body) as List<dynamic>;
final List<Map<String, dynamic>> quotes =
jsonList.map((e) => e as Map<String, dynamic>).toList();
Map<String, dynamic> highestQuote = quotes.reduce((current, next) {
double currentAmount = current['egressAmount'] as double;
double nextAmount = next['egressAmount'] as double;
return currentAmount > nextAmount ? current : next;
});
return highestQuote;
}
Future<Map<String, dynamic>?> _getStatus(Map<String, String> params) async {
final uri = Uri.https(_baseURL, _txInfoPath, params);
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode == 404) return null;
if ((response.statusCode != 200) || (response.body.contains('error'))) {
throw Exception('Unexpected response: ${response.statusCode} / ${uri.toString()} / ${response.body}');
}
return json.decode(response.body) as Map<String, dynamic>;
}
TradeState _determineState(String state) {
final swapState = switch (state) {
'waiting' => TradeState.waiting,
'receiving' => TradeState.processing,
'swapping' => TradeState.processing,
'sending' => TradeState.processing,
'sent' => TradeState.processing,
'completed' => TradeState.success,
'failed' => TradeState.failed,
_ => TradeState.notFound
};
return swapState;
}
}
@@ -1,366 +0,0 @@
import 'dart:convert';
import 'dart:io';
import 'package:hash_wallet/.secrets.g.dart' as secrets;
import 'package:hash_wallet/exchange/exchange_provider_description.dart';
import 'package:hash_wallet/exchange/limits.dart';
import 'package:hash_wallet/exchange/provider/exchange_provider.dart';
import 'package:hash_wallet/exchange/trade.dart';
import 'package:hash_wallet/exchange/trade_not_found_exception.dart';
import 'package:hash_wallet/exchange/trade_request.dart';
import 'package:hash_wallet/exchange/trade_state.dart';
import 'package:hash_wallet/store/settings_store.dart';
import 'package:hash_wallet/utils/distribution_info.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:hash_wallet/wallet_type_utils.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:hash_wallet/utils/exchange_provider_logger.dart';
class ChangeNowExchangeProvider extends ExchangeProvider {
ChangeNowExchangeProvider({required SettingsStore settingsStore})
: _settingsStore = settingsStore,
_lastUsedRateId = '';
static final apiKey =
isMoneroOnly ? secrets.changeNowMoneroApiKey : secrets.changeNowCakeWalletApiKey;
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';
final SettingsStore _settingsStore;
String _lastUsedRateId;
@override
String get title => 'ChangeNOW';
@override
bool get isAvailable => true;
@override
bool get isEnabled => true;
@override
bool get supportsFixedRate => true;
@override
ExchangeProviderDescription get description => ExchangeProviderDescription.changeNow;
@override
Future<bool> checkIsAvailable() async => true;
@override
Future<Limits?> fetchLimits(
{required CryptoCurrency from,
required CryptoCurrency to,
required bool isFixedRateMode}) async {
final headers = {apiHeaderKey: apiKey};
final params = <String, String>{
'fromCurrency': _normalizeCurrency(from),
'toCurrency': _normalizeCurrency(to),
'fromNetwork': _networkFor(from),
'toNetwork': _networkFor(to),
'flow': _getFlow(isFixedRateMode)
};
final uri = Uri.https(apiAuthority, rangePath, params);
final response = await ProxyWrapper().get(clearnetUri: uri, headers: headers);
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');
}
if (response.statusCode != 200)
throw Exception('Unexpected http status: ${response.statusCode}');
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final min = double.tryParse(responseJSON['minAmount']?.toString() ?? '');
final max = double.tryParse(responseJSON['maxAmount']?.toString() ?? '');
if (max == 0) return null;
return Limits(min: min, max: max);
}
@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 ProxyWrapper().get(clearnetUri: uri, headers: headers);
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final fromAmount = double.tryParse(responseJSON['fromAmount']?.toString() ?? '') ?? 0.0;
final toAmount = double.tryParse(responseJSON['toAmount']?.toString() ?? '') ?? 0.0;
if (fromAmount <= 0 || toAmount <= 0) return 0.0;
final rateId = responseJSON['rateId'] as String? ?? '';
if (rateId.isNotEmpty) _lastUsedRateId = rateId;
final rate = isReverse ? (amount / fromAmount) : (toAmount / amount);
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'fetchRate',
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
'type': type,
'flow': _getFlow(isFixedRateMode),
},
responseData: {
'fromAmount': fromAmount,
'toAmount': toAmount,
'rateId': rateId,
'rate': rate,
},
);
return rate;
} catch (e, s) {
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
error: e,
stackTrace: s,
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
},
);
printV(e.toString());
return 0.0;
}
}
@override
Future<Trade> createTrade({
required TradeRequest request,
required bool isFixedRateMode,
required bool isSendAll,
}) 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,
};
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,
);
body['rateId'] = _lastUsedRateId;
}
final uri = Uri.https(apiAuthority, createTradePath);
final response = await ProxyWrapper().post(
clearnetUri: uri,
headers: headers,
body: json.encode(body),
);
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');
}
if (response.statusCode != 200)
throw Exception('Unexpected http status: ${response.statusCode}');
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;
final fromAmount = responseJSON['fromAmount']?.toString();
final toAmount = responseJSON['toAmount']?.toString();
return Trade(
id: id,
from: request.fromCurrency,
to: request.toCurrency,
provider: description,
inputAddress: inputAddress,
refundAddress: refundAddress,
extraId: extraId,
createdAt: DateTime.now(),
amount: fromAmount ?? request.fromAmount,
receiveAmount: toAmount ?? request.toAmount,
state: TradeState.created,
payoutAddress: payoutAddress,
isSendAll: isSendAll,
);
}
@override
Future<Trade> findTradeById({required String id}) async {
final headers = {apiHeaderKey: apiKey};
final params = <String, String>{'id': id};
final uri = Uri.https(apiAuthority, findTradeByIdPath, params);
final response = await ProxyWrapper().get(clearnetUri: uri, headers: headers);
if (response.statusCode == 404) throw TradeNotFoundException(id, provider: description);
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);
}
if (response.statusCode != 200)
throw Exception('Unexpected http status: ${response.statusCode}');
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
// Parsing 'from' currency
final fromCurrency = responseJSON['fromCurrency'] as String;
final fromNetwork = responseJSON['fromNetwork'] as String?;
final _normalizedFromNetwork = _normalizeNetworkType(fromNetwork ?? '');
final fromTag = fromCurrency.toUpperCase() == _normalizedFromNetwork.toUpperCase()
? null
: _normalizedFromNetwork;
final from = CryptoCurrency.safeParseCurrencyFromString(fromCurrency, tag: fromTag);
// Parsing 'to' currency
final toCurrency = responseJSON['toCurrency'] as String;
final toNetwork = responseJSON['toNetwork'] as String?;
final _normalizedToNetwork = _normalizeNetworkType(toNetwork ?? '');
final toTag = toCurrency.toUpperCase() == _normalizedToNetwork.toUpperCase()
? null
: _normalizedToNetwork;
final to = CryptoCurrency.safeParseCurrencyFromString(toCurrency, tag: toTag);
final inputAddress = responseJSON['payinAddress'] as String;
final expectedSendAmount = responseJSON['expectedAmountFrom'].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?;
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,
);
}
String _getFlow(bool isFixedRate) => isFixedRate ? 'fixed-rate' : 'standard';
String _networkFor(CryptoCurrency currency) {
switch (currency) {
case CryptoCurrency.usdt:
return 'btc';
case CryptoCurrency.arb:
return 'arbitrum';
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';
case 'ARB':
return 'arbitrum';
default:
return tag.toLowerCase();
}
}
String _normalizeNetworkType(String network) {
return switch (network.toUpperCase()) {
'POLY' => 'MATIC',
'AVAXC' => 'CCHAIN',
'ARBITRUM' => 'ARB',
_ => network,
};
}
}
@@ -1,467 +0,0 @@
import 'dart:convert';
import 'package:hash_wallet/.secrets.g.dart' as secrets;
import 'package:hash_wallet/core/lightning_invoice_service.dart';
import 'package:hash_wallet/exchange/exchange_provider_description.dart';
import 'package:hash_wallet/exchange/limits.dart';
import 'package:hash_wallet/exchange/provider/exchange_provider.dart';
import 'package:hash_wallet/exchange/trade.dart';
import 'package:hash_wallet/exchange/trade_not_found_exception.dart';
import 'package:hash_wallet/exchange/trade_request.dart';
import 'package:hash_wallet/exchange/trade_state.dart';
import 'package:hash_wallet/wallet_type_utils.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:hash_wallet/utils/exchange_provider_logger.dart';
class ExolixExchangeProvider extends ExchangeProvider {
ExolixExchangeProvider();
static final apiKey = isMoneroOnly ? secrets.exolixMoneroApiKey : secrets.exolixCakeWalletApiKey;
static const apiBaseUrl = 'exolix.com';
static const transactionsPath = '/api/v2/transactions';
static const ratePath = '/api/v2/rate';
@override
String get title => 'Exolix';
@override
bool get isAvailable => true;
@override
bool get isEnabled => true;
@override
bool get supportsFixedRate => true;
@override
ExchangeProviderDescription get description => ExchangeProviderDescription.exolix;
@override
Future<bool> checkIsAvailable() async => true;
@override
Future<Limits?> fetchLimits({
required CryptoCurrency from,
required CryptoCurrency to,
required bool isFixedRateMode,
}) async {
final params = <String, String>{
'rateType': _getRateType(isFixedRateMode),
'amount': '1',
'apiToken': apiKey,
};
if (isFixedRateMode) {
params['coinFrom'] = _normalizeCurrency(to);
params['coinTo'] = _normalizeCurrency(_overrideFromCryptoCurrency(from));
params['networkFrom'] = _networkFor(to);
params['networkTo'] = _networkFor(from);
} else {
params['coinFrom'] = _normalizeCurrency(_overrideFromCryptoCurrency(from));
params['coinTo'] = _normalizeCurrency(to);
params['networkFrom'] = _networkFor(from);
params['networkTo'] = _networkFor(to);
}
// Maximum of 2 attempts to fetch limits
for (int i = 0; i < 2; i++) {
final uri = Uri.https(apiBaseUrl, ratePath, params);
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode == 200) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final minAmount = responseJSON['minAmount'];
final maxAmount = responseJSON['maxAmount'];
return Limits(min: _toDouble(minAmount), max: _toDouble(maxAmount));
} else if (response.statusCode == 422) {
final errorResponse = json.decode(response.body) as Map<String, dynamic>;
if (errorResponse.containsKey('minAmount')) {
params['amount'] = errorResponse['minAmount'].toString();
continue;
}
throw Exception('Error 422: ${errorResponse['message'] ?? 'Unknown error'}');
} else {
throw Exception('Unexpected HTTP status: ${response.statusCode}');
}
}
throw Exception('Failed to fetch limits after retrying.');
}
@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 params = {
'coinFrom': _normalizeCurrency(_overrideFromCryptoCurrency(from)),
'coinTo': _normalizeCurrency(to),
'networkFrom': _networkFor(from),
'networkTo': _networkFor(to),
'rateType': _getRateType(isFixedRateMode),
'apiToken': apiKey,
};
if (isReceiveAmount)
params['withdrawalAmount'] = amount.toString();
else
params['amount'] = amount.toString();
final uri = Uri.https(apiBaseUrl, ratePath, params);
final response = await ProxyWrapper().get(clearnetUri: uri);
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
if (response.statusCode != 200) {
final message = responseJSON['message'] as String?;
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
error: Exception(message ?? 'Unknown error'),
stackTrace: StackTrace.current,
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
'params': params,
'url': uri.toString(),
},
);
throw Exception(message);
}
final rate = double.tryParse(responseJSON['rate']?.toString() ?? '') ?? 0.0;
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'fetchRate',
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
'params': params,
'url': uri.toString(),
},
responseData: {
'rate': rate,
'statusCode': response.statusCode,
'responseJSON': responseJSON,
},
);
return rate;
} catch (e, s) {
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
error: e,
stackTrace: s,
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
},
);
printV(e.toString());
printV(s.toString());
return 0.0;
}
}
@override
Future<Trade> createTrade({
required TradeRequest request,
required bool isFixedRateMode,
required bool isSendAll,
}) async {
final headers = {'Content-Type': 'application/json'};
final body = {
'coinFrom': _normalizeCurrency(_overrideFromCryptoCurrency(request.fromCurrency)),
'coinTo': _normalizeCurrency(_overrideToCryptoCurrency(request.toCurrency, request.toAddress)),
'networkFrom': _networkFor(request.fromCurrency),
'networkTo': _networkFor(request.toCurrency),
'withdrawalAddress': await _normalizeAddress(request.toAddress),
'refundAddress': await _normalizeAddress(request.refundAddress),
'rateType': _getRateType(isFixedRateMode),
'apiToken': apiKey,
};
if (isFixedRateMode)
body['withdrawalAmount'] = request.toAmount;
else
body['amount'] = request.fromAmount;
final uri = Uri.https(apiBaseUrl, transactionsPath);
final response = await ProxyWrapper().post(
clearnetUri: uri,
headers: headers,
body: json.encode(body),
);
if (response.statusCode == 400) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final errors = responseJSON['error'] as Map<String, String>;
final errorMessage = errors.values.join(', ');
ExchangeProviderLogger.logError(
provider: description,
function: 'createTrade',
error: Exception(errorMessage),
stackTrace: StackTrace.current,
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'body': body,
'url': uri.toString(),
},
);
throw Exception(errorMessage);
}
if (response.statusCode != 200 && response.statusCode != 201) {
ExchangeProviderLogger.logError(
provider: description,
function: 'createTrade',
error: Exception('Unexpected http status: ${response.statusCode}'),
stackTrace: StackTrace.current,
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'body': body,
'url': uri.toString(),
},
);
throw Exception('Unexpected http status: ${response.statusCode}');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final id = responseJSON['id'] as String;
final inputAddress = responseJSON['depositAddress'] as String;
final refundAddress = responseJSON['refundAddress'] as String?;
final extraId = responseJSON['depositExtraId'] as String?;
final payoutAddress = responseJSON['withdrawalAddress'] as String;
final amount = responseJSON['amount'].toString();
final receiveAmount = responseJSON['amountTo']?.toString();
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'createTrade',
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'body': body,
'url': uri.toString(),
},
responseData: {
'id': id,
'inputAddress': inputAddress,
'refundAddress': refundAddress,
'extraId': extraId,
'payoutAddress': payoutAddress,
'amount': amount,
'receiveAmount': receiveAmount,
'statusCode': response.statusCode,
'responseJSON': responseJSON,
},
);
return Trade(
id: id,
from: request.fromCurrency,
to: request.toCurrency,
provider: description,
inputAddress: inputAddress,
refundAddress: refundAddress,
extraId: extraId,
createdAt: DateTime.now(),
amount: amount,
receiveAmount: receiveAmount ?? request.toAmount,
state: TradeState.created,
payoutAddress: payoutAddress,
isSendAll: isSendAll,
);
}
@override
Future<Trade> findTradeById({required String id}) async {
final findTradeByIdPath = '$transactionsPath/$id';
final uri = Uri.https(apiBaseUrl, findTradeByIdPath);
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode == 404) throw TradeNotFoundException(id, provider: description);
if (response.statusCode == 400) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final errors = responseJSON['errors'] as Map<String, String>;
final errorMessage = errors.values.join(', ');
throw TradeNotFoundException(id, provider: description, description: errorMessage);
}
if (response.statusCode != 200)
throw Exception('Unexpected http status: ${response.statusCode}');
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
// Parsing 'from' currency
final coinFrom = responseJSON['coinFrom']['coinCode'] as String;
final coinFromNetwork = responseJSON['coinFrom']['network'] as String?;
final _normalizedFromNetwork = _normalizeNetworkType(coinFromNetwork ?? '');
final fromTag = coinFrom.toUpperCase() == _normalizedFromNetwork.toUpperCase() ? null : coinFromNetwork;
final from = CryptoCurrency.safeParseCurrencyFromString(coinFrom, tag: fromTag);
// Parsing 'to' currency
final coinTo = responseJSON['coinTo']['coinCode'] as String;
final coinToNetwork = responseJSON['coinTo']['network'] as String?;
final _normalizedToNetwork = _normalizeNetworkType(coinToNetwork ?? '');
final toTag = coinTo.toUpperCase() == _normalizedToNetwork.toUpperCase() ? null : coinToNetwork;
final to = CryptoCurrency.safeParseCurrencyFromString(coinTo, tag: toTag);
final inputAddress = responseJSON['depositAddress'] as String;
final amount = responseJSON['amount'].toString();
final status = responseJSON['status'] as String;
final extraId = responseJSON['depositExtraId'] as String?;
final outputTransaction = responseJSON['hashOut']['hash'] as String?;
final payoutAddress = responseJSON['withdrawalAddress'] as String;
return Trade(
id: id,
from: from,
to: to,
provider: description,
inputAddress: inputAddress,
amount: amount,
state: TradeState.deserialize(raw: _prepareStatus(status)),
extraId: extraId,
outputTransaction: outputTransaction,
payoutAddress: payoutAddress,
);
}
String _getRateType(bool isFixedRate) => isFixedRate ? 'fixed' : 'float';
String _prepareStatus(String status) {
switch (status) {
case 'deleted':
case 'error':
return 'overdue';
default:
return status;
}
}
String _networkFor(CryptoCurrency currency) {
switch (currency) {
case CryptoCurrency.arb:
return 'ARBITRUM';
case CryptoCurrency.btcln:
return 'LIGHTNING';
default:
return currency.tag != null ? _normalizeTag(currency.tag!) : currency.title;
}
}
String _normalizeNetworkType(String network) {
return switch (network.toUpperCase()) {
'ARBITRUM' => 'ARB',
_ => network,
};
}
CryptoCurrency _overrideFromCryptoCurrency(CryptoCurrency currency) {
if (currency == CryptoCurrency.zec)
return CryptoCurrency.zaddr; // Sending is always shielded zcash
return currency;
}
CryptoCurrency _overrideToCryptoCurrency(CryptoCurrency currency, String address) {
if (RegExp(r'u1[a-zA-Z0-9]{100,300}').hasMatch(address) && currency == CryptoCurrency.zec)
return CryptoCurrency.zaddr; // If the user pastes a unified address use shielded zcash
return currency;
}
String _normalizeCurrency(CryptoCurrency currency) {
switch (currency) {
case CryptoCurrency.nano:
return 'XNO';
case CryptoCurrency.bttc:
return 'BTT';
case CryptoCurrency.zec:
return 'ZEC';
case CryptoCurrency.zaddr:
return 'ZEC-SHIELDED';
default:
return currency.title;
}
}
String _normalizeTag(String tag) {
switch (tag) {
case 'POLY':
return 'Polygon';
case 'ARB':
return 'Arbitrum';
default:
return tag;
}
}
Future<String> _normalizeAddress(String address) async {
if (address.startsWith('bitcoincash:'))
return address.replaceFirst('bitcoincash:', '');
// Lightning addresses
if(address.contains("@"))
return await getBolt11FromLightingAddress(address) ?? address;
return address;
}
static double? _toDouble(dynamic value) {
if (value is int) {
return value.toDouble();
} else if (value is double) {
return value;
} else if (value is String) {
return double.tryParse(value);
}
return null;
}
}
@@ -1,447 +0,0 @@
import 'dart:convert';
import 'dart:developer';
import 'package:hash_wallet/.secrets.g.dart' as secrets;
import 'package:hash_wallet/exchange/provider/exchange_provider.dart';
import 'package:hash_wallet/exchange/exchange_provider_description.dart';
import 'package:hash_wallet/exchange/limits.dart';
import 'package:hash_wallet/exchange/trade.dart';
import 'package:hash_wallet/exchange/trade_not_created_exception.dart';
import 'package:hash_wallet/exchange/trade_request.dart';
import 'package:hash_wallet/exchange/trade_state.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:hash_wallet/utils/exchange_provider_logger.dart';
class LetsExchangeExchangeProvider extends ExchangeProvider {
LetsExchangeExchangeProvider();
static const apiKey = secrets.letsExchangeBearerToken;
static const _baseUrl = 'api.letsexchange.io';
static const _infoPath = '/api/v1/info';
static const _infoRevertPath = '/api/v1/info-revert';
static const _createTransactionPath = '/api/v1/transaction';
static const _createTransactionRevertPath = '/api/v1/transaction-revert';
static const _getTransactionPath = '/api/v1/transaction';
static const _affiliateId = secrets.letsExchangeAffiliateId;
@override
String get title => 'LetsExchange';
@override
bool get isAvailable => true;
@override
bool get isEnabled => true;
@override
bool get supportsFixedRate => true;
@override
ExchangeProviderDescription get description => ExchangeProviderDescription.letsExchange;
@override
Future<bool> checkIsAvailable() async => true;
@override
Future<Limits?> fetchLimits(
{required CryptoCurrency from,
required CryptoCurrency to,
required bool isFixedRateMode}) async {
final networkFrom = _getNetworkType(from);
final networkTo = _getNetworkType(to);
try {
final params = {
'from': from.title,
'to': to.title,
if (networkFrom != null) 'network_from': networkFrom,
if (networkTo != null) 'network_to': networkTo,
'amount': '1',
'affiliate_id': _affiliateId,
'float': isFixedRateMode ? 'false' : 'true',
};
final responseJSON = await _getInfo(params, isFixedRateMode);
final min = double.tryParse(responseJSON['min_amount'] as String);
final max = double.tryParse(responseJSON['max_amount'] as String);
return Limits(min: min, max: max);
} catch (e) {
log(e.toString());
throw Exception('Failed to fetch limits');
}
}
@override
Future<double> fetchRate(
{required CryptoCurrency from,
required CryptoCurrency to,
required double amount,
required bool isFixedRateMode,
required bool isReceiveAmount}) async {
final networkFrom = _getNetworkType(from);
final networkTo = _getNetworkType(to);
try {
final params = {
'from': from.title,
'to': to.title,
if (networkFrom != null) 'network_from': networkFrom,
if (networkTo != null) 'network_to': networkTo,
'amount': amount.toString(),
'affiliate_id': _affiliateId,
'float': isFixedRateMode ? 'false' : 'true',
};
final responseJSON = await _getInfo(params, isFixedRateMode);
final amountToGet = double.tryParse(responseJSON['amount'] as String) ?? 0.0;
if (amountToGet == 0.0) return 0.0;
final rate = isFixedRateMode ? amount / amountToGet : amountToGet / amount;
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'fetchRate',
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
'networkFrom': networkFrom,
'networkTo': networkTo,
'params': params,
},
responseData: {
'amountToGet': amountToGet,
'rate': rate,
'responseJSON': responseJSON,
},
);
return rate;
} catch (e, s) {
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
error: e,
stackTrace: s,
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
'networkFrom': networkFrom,
'networkTo': networkTo,
},
);
printV(e.toString());
return 0.0;
}
}
@override
Future<Trade> createTrade(
{required TradeRequest request,
required bool isFixedRateMode,
required bool isSendAll}) async {
final networkFrom = _getNetworkType(request.fromCurrency);
final networkTo = _getNetworkType(request.toCurrency);
try {
final params = {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
if (networkFrom != null) 'network_from': networkFrom,
if (networkTo != null) 'network_to': networkTo,
'amount': isFixedRateMode ? request.toAmount.toString() : request.fromAmount.toString(),
'affiliate_id': _affiliateId,
'float': isFixedRateMode ? 'false' : 'true',
};
final responseInfoJSON = await _getInfo(params, isFixedRateMode);
final rateId = responseInfoJSON['rate_id'] as String;
final withdrawalAddress = _normalizeBchAddress(request.toAddress);
final returnAddress = _normalizeBchAddress(request.refundAddress);
final tradeParams = {
'coin_from': request.fromCurrency.title,
'coin_to': request.toCurrency.title,
if (!isFixedRateMode) 'deposit_amount': request.fromAmount.toString(),
'withdrawal': withdrawalAddress,
if (isFixedRateMode) 'withdrawal_amount': request.toAmount.toString(),
'withdrawal_extra_id': '',
'return': returnAddress,
'rate_id': rateId,
if (networkFrom != null) 'network_from': networkFrom,
if (networkTo != null) 'network_to': networkTo,
'affiliate_id': _affiliateId,
'float': isFixedRateMode ? 'false' : 'true',
};
final headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': apiKey
};
final uri = Uri.https(
_baseUrl, isFixedRateMode ? _createTransactionRevertPath : _createTransactionPath);
final response = await ProxyWrapper().post(
clearnetUri: uri,
headers: headers,
body: json.encode(tradeParams),
);
if (response.statusCode != 200) {
ExchangeProviderLogger.logError(
provider: description,
function: 'createTrade',
error: Exception('LetsExchange create trade failed: ${response.body}'),
stackTrace: StackTrace.current,
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'networkFrom': networkFrom,
'networkTo': networkTo,
'tradeParams': tradeParams,
'url': uri.toString(),
},
);
throw Exception('LetsExchange create trade failed: ${response.body}');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final id = responseJSON['transaction_id'] as String;
final from = responseJSON['coin_from'] as String;
final to = responseJSON['coin_to'] as String;
final payoutAddress = responseJSON['withdrawal'] as String;
final depositAddress = responseJSON['deposit'] as String;
final refundAddress = responseJSON['return'] as String;
final depositAmount = responseJSON['deposit_amount'] as String;
final receiveAmount = responseJSON['withdrawal_amount'] as String;
final status = responseJSON['status'] as String;
// We ignore the created_at from response and use DateTime.now() instead
final createdAtString = responseJSON['created_at'] as String;
final expiredAtTimestamp = responseJSON['expired_at'] as int;
final extraId = responseJSON['deposit_extra_id'] as String?;
final createdAt = DateTime.now();
final expiredAt = createdAt.add(Duration(minutes: 30));
CryptoCurrency fromCurrency;
if (request.fromCurrency.tag != null && request.fromCurrency.title == from) {
fromCurrency = request.fromCurrency;
} else {
fromCurrency = CryptoCurrency.fromString(from);
}
CryptoCurrency toCurrency;
if (request.toCurrency.tag != null && request.toCurrency.title == to) {
toCurrency = request.toCurrency;
} else {
toCurrency = CryptoCurrency.fromString(to);
}
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'createTrade',
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'networkFrom': networkFrom,
'networkTo': networkTo,
'tradeParams': tradeParams,
'url': uri.toString(),
},
responseData: {
'id': id,
'from': from,
'to': to,
'depositAddress': depositAddress,
'payoutAddress': payoutAddress,
'refundAddress': refundAddress,
'depositAmount': depositAmount,
'receiveAmount': receiveAmount,
'status': status,
'createdAt': createdAtString,
'expiredAt': expiredAtTimestamp,
'extraId': extraId,
'statusCode': response.statusCode,
},
);
return Trade(
id: id,
from: fromCurrency,
to: toCurrency,
provider: description,
inputAddress: depositAddress,
payoutAddress: payoutAddress,
refundAddress: refundAddress,
amount: depositAmount,
receiveAmount: receiveAmount,
state: TradeState.deserialize(raw: status),
createdAt: createdAt,
expiredAt: expiredAt,
extraId: extraId,
isSendAll: isSendAll,
);
} catch (e, s) {
ExchangeProviderLogger.logError(
provider: description,
function: 'createTrade',
error: e,
stackTrace: s,
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'networkFrom': networkFrom,
'networkTo': networkTo,
},
);
log(e.toString());
throw TradeNotCreatedException(description);
}
}
@override
Future<Trade> findTradeById({required String id}) async {
final headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': apiKey
};
final url = Uri.https(_baseUrl, '$_getTransactionPath/$id');
final response = await ProxyWrapper().get(clearnetUri: url, headers: headers);
if (response.statusCode != 200) {
throw Exception('LetsExchange fetch trade failed: ${response.body}');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
// Parsing 'from' currency
final fromCurrency = responseJSON['coin_from'] as String;
final fromNetwork = responseJSON['coin_from_network'] as String?;
final normalizedFromNetwork = _normalizeNetworkType(fromNetwork ?? '');
final fromTag = fromCurrency == normalizedFromNetwork ? null : normalizedFromNetwork;
final from = CryptoCurrency.safeParseCurrencyFromString(fromCurrency, tag: fromTag);
// Parsing 'to' currency
final toCurrency = responseJSON['coin_to'] as String;
final toNetwork = responseJSON['coin_to_network'] as String?;
final normalizedToNetwork = _normalizeNetworkType(toNetwork ?? '');
final toTag = toCurrency == normalizedToNetwork ? null : normalizedToNetwork;
final to = CryptoCurrency.safeParseCurrencyFromString(toCurrency, tag: toTag);
final payoutAddress = responseJSON['withdrawal'] as String;
final depositAddress = responseJSON['deposit'] as String;
final refundAddress = responseJSON['return'] as String;
final depositAmount = responseJSON['deposit_amount'] as String;
final receiveAmount = responseJSON['withdrawal_amount'] as String;
final status = responseJSON['status'] as String;
final extraId = responseJSON['deposit_extra_id'] as String?;
return Trade(
id: id,
from: from,
to: to,
provider: description,
inputAddress: depositAddress,
payoutAddress: payoutAddress,
refundAddress: refundAddress,
amount: depositAmount,
receiveAmount: receiveAmount,
state: TradeState.deserialize(raw: status),
isRefund: status == 'refund',
extraId: extraId,
);
}
Future<Map<String, dynamic>> _getInfo(Map<String, String> params, bool isFixedRateMode) async {
final headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': apiKey
};
try {
final uri = Uri.https(_baseUrl, isFixedRateMode ? _infoRevertPath : _infoPath);
final response = await ProxyWrapper().post(
clearnetUri: uri,
headers: headers,
body: json.encode(params),
);
if (response.statusCode != 200) {
throw Exception('LetsExchange fetch info failed: ${response.body}');
}
return json.decode(response.body) as Map<String, dynamic>;
} catch (e) {
throw Exception('LetsExchange failed to fetch info ${e.toString()}');
}
}
String? _getNetworkType(CryptoCurrency currency) {
if (currency.tag != null && currency.tag!.isNotEmpty) {
switch (currency.tag!) {
case 'TRX':
return 'TRC20';
case 'ETH':
return 'ERC20';
case 'BSC':
return 'BEP20';
case 'ARB':
return 'ARBITRUM';
default:
return currency.tag!;
}
}
return _normalizeTitleToNetwork(currency.title);
}
String _normalizeNetworkType(String network) {
return switch (network.toUpperCase()) {
'ERC20' => 'ETH',
'TRC20' => 'TRX',
'BEP20' => 'BSC',
'ARBITRUM' => 'ARB',
_ => network,
};
}
String _normalizeTitleToNetwork(String title) {
return switch (title.toUpperCase()) {
'ARB' => 'ARBITRUM',
_ => title,
};
}
String _normalizeBchAddress(String address) =>
address.startsWith('bitcoincash:') ? address.substring(12) : address;
}
@@ -1,479 +0,0 @@
import 'dart:convert';
import 'package:hash_wallet/.secrets.g.dart' as secrets;
import 'package:hash_wallet/exchange/provider/exchange_provider.dart';
import 'package:hash_wallet/exchange/exchange_provider_description.dart';
import 'package:hash_wallet/exchange/limits.dart';
import 'package:hash_wallet/exchange/trade.dart';
import 'package:hash_wallet/exchange/trade_not_created_exception.dart';
import 'package:hash_wallet/exchange/trade_not_found_exception.dart';
import 'package:hash_wallet/exchange/trade_request.dart';
import 'package:hash_wallet/exchange/trade_state.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:hash_wallet/utils/exchange_provider_logger.dart';
class SideShiftExchangeProvider extends ExchangeProvider {
SideShiftExchangeProvider();
static const affiliateId = secrets.sideShiftAffiliateId;
static const apiBaseUrl = 'https://sideshift.ai/api';
static const rangePath = '/v2/pair';
static const orderPath = '/v2/shifts';
static const quotePath = '/v2/quotes';
static const permissionPath = '/v2/permissions';
@override
String get title => 'SideShift';
@override
bool get isAvailable => true;
@override
bool get isEnabled => true;
@override
bool get supportsFixedRate => true;
@override
ExchangeProviderDescription get description => ExchangeProviderDescription.sideShift;
@override
Future<bool> checkIsAvailable() async {
const url = apiBaseUrl + permissionPath;
final uri = Uri.parse(url);
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode == 500) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['error']['message'] as String;
throw Exception('$error');
}
if (response.statusCode != 200) return false;
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
return responseJSON['createShift'] as bool;
}
@override
Future<Limits?> fetchLimits(
{required CryptoCurrency from,
required CryptoCurrency to,
required bool isFixedRateMode}) async {
final fromCurrency = isFixedRateMode ? to : from;
final toCurrency = isFixedRateMode ? from : to;
final fromNetwork = _networkFor(fromCurrency);
final toNetwork = _networkFor(toCurrency);
final url =
"$apiBaseUrl$rangePath/${fromCurrency.title.toLowerCase()}-$fromNetwork/${toCurrency.title.toLowerCase()}-$toNetwork";
final uri = Uri.parse(url);
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode == 500) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['error']['message'] as String;
throw Exception('$error');
}
if (response.statusCode != 200) {
throw Exception('Unexpected http status: ${response.statusCode}');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final min = double.tryParse(responseJSON['min'] as String? ?? '');
final max = double.tryParse(responseJSON['max'] as String? ?? '');
if (isFixedRateMode) {
final currentRate = double.parse(responseJSON['rate'] as String);
return Limits(
min: min != null ? (min * currentRate) : null,
max: max != null ? (max * currentRate) : null,
);
}
return Limits(min: min, max: max);
}
@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 fromCurrency = from.title.toLowerCase();
final toCurrency = to.title.toLowerCase();
final depositNetwork = _networkFor(from);
final settleNetwork = _networkFor(to);
final url =
"$apiBaseUrl$rangePath/$fromCurrency-$depositNetwork/$toCurrency-$settleNetwork?amount=$amount";
final uri = Uri.parse(url);
final response = await ProxyWrapper().get(clearnetUri: uri);
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
if (response.statusCode == 500) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['error']['message'] as String;
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
error: Exception('SideShift Internal Server Error: $error'),
stackTrace: StackTrace.current,
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
'url': url,
},
);
throw Exception('SideShift Internal Server Error: $error');
}
if (response.statusCode != 200) {
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
error: Exception('Unexpected http status: ${response.statusCode}'),
stackTrace: StackTrace.current,
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
'url': url,
},
);
throw Exception('Unexpected http status: ${response.statusCode}');
}
final rate = double.parse(responseJSON['rate'] as String);
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'fetchRate',
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
'url': url,
},
responseData: {
'rate': rate,
'statusCode': response.statusCode,
},
);
return rate;
} catch (e, s) {
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
error: e,
stackTrace: s,
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
},
);
printV(e.toString());
return 0.00;
}
}
@override
Future<Trade> createTrade({
required TradeRequest request,
required bool isFixedRateMode,
required bool isSendAll,
}) async {
String url = '';
final body = {
'affiliateId': affiliateId,
'settleAddress': request.toAddress,
'refundAddress': request.refundAddress,
};
if (isFixedRateMode) {
final quoteId = await _createQuote(request);
body['quoteId'] = quoteId;
url = apiBaseUrl + orderPath + '/fixed';
} else {
url = apiBaseUrl + orderPath + '/variable';
body["depositCoin"] = _normalizeCurrency(request.fromCurrency);
body["settleCoin"] = _normalizeCurrency(request.toCurrency);
body["settleNetwork"] = _networkFor(request.toCurrency);
body["depositNetwork"] = _networkFor(request.fromCurrency);
}
final headers = {'Content-Type': 'application/json'};
final uri = Uri.parse(url);
final response = await ProxyWrapper().post(
clearnetUri: uri,
headers: headers,
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']['message'] as String;
ExchangeProviderLogger.logError(
provider: description,
function: 'createTrade',
error: TradeNotCreatedException(description, description: error),
stackTrace: StackTrace.current,
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'url': url,
'body': body,
},
);
throw TradeNotCreatedException(description, description: error);
}
ExchangeProviderLogger.logError(
provider: description,
function: 'createTrade',
error: TradeNotCreatedException(description),
stackTrace: StackTrace.current,
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'url': url,
'body': body,
},
);
throw TradeNotCreatedException(description);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final id = responseJSON['id'] as String;
final inputAddress = responseJSON['depositAddress'] as String;
final settleAddress = responseJSON['settleAddress'] as String;
final depositAmount = responseJSON['depositAmount'] as String?;
final depositMemo = responseJSON['depositMemo'] as String?;
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'createTrade',
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'url': url,
'body': body,
},
responseData: {
'id': id,
'inputAddress': inputAddress,
'settleAddress': settleAddress,
'depositAmount': depositAmount,
'depositMemo': depositMemo,
'statusCode': response.statusCode,
},
);
return Trade(
id: id,
provider: description,
from: request.fromCurrency,
to: request.toCurrency,
inputAddress: inputAddress,
refundAddress: settleAddress,
state: TradeState.created,
amount: depositAmount ?? request.fromAmount,
receiveAmount: request.toAmount,
payoutAddress: settleAddress,
createdAt: DateTime.now(),
isSendAll: isSendAll,
extraId: depositMemo,
);
}
@override
Future<Trade> findTradeById({required String id}) async {
final url = apiBaseUrl + orderPath + '/' + id;
final uri = Uri.parse(url);
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode == 404) {
throw TradeNotFoundException(id, provider: description);
}
if (response.statusCode == 400) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['error']['message'] as String;
throw TradeNotFoundException(id, provider: description, description: error);
}
if (response.statusCode != 200) {
throw Exception('Unexpected http status: ${response.statusCode}');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final fromCurrency = responseJSON['depositCoin'] as String;
final fromNetwork = responseJSON['depositNetwork'] as String?;
final toCurrency = responseJSON['settleCoin'] as String;
final toNetwork = responseJSON['settleNetwork'] as String?;
final inputAddress = responseJSON['depositAddress'] as String;
final expectedSendAmount = responseJSON['depositAmount'] as String?;
final status = responseJSON['status'] as String?;
final settleAddress = responseJSON['settleAddress'] as String;
final isVariable = (responseJSON['type'] as String) == 'variable';
final expiredAtRaw = responseJSON['expiresAt'] as String;
final expiredAt = isVariable ? null : DateTime.tryParse(expiredAtRaw)?.toLocal();
final depositMemo = responseJSON['depositMemo'] as String?;
final fromParsed = CryptoCurrency.safeParseCurrencyFromString(
fromCurrency,
tag: fromNetwork,
);
final toParsed = CryptoCurrency.safeParseCurrencyFromString(
toCurrency,
tag: toNetwork,
);
return Trade(
id: id,
from: fromParsed,
to: toParsed,
provider: description,
inputAddress: inputAddress,
amount: expectedSendAmount ?? '',
state: TradeState.deserialize(raw: status ?? 'created'),
expiredAt: expiredAt,
payoutAddress: settleAddress,
extraId: depositMemo,
);
}
Future<String> _createQuote(TradeRequest request) async {
final url = apiBaseUrl + quotePath;
final headers = {'Content-Type': 'application/json'};
final body = {
'depositCoin': _normalizeCurrency(request.fromCurrency),
'settleCoin': _normalizeCurrency(request.toCurrency),
'affiliateId': affiliateId,
'settleAmount': request.toAmount,
'settleNetwork': _networkFor(request.toCurrency),
'depositNetwork': _networkFor(request.fromCurrency),
};
final uri = Uri.parse(url);
final response = await ProxyWrapper().post(
clearnetUri: uri,
headers: headers,
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']['message'] as String;
throw TradeNotCreatedException(description, description: error);
}
throw TradeNotCreatedException(description);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
return responseJSON['id'] as String;
}
String _normalizeCurrency(CryptoCurrency currency) {
switch (currency) {
case CryptoCurrency.usdcEPoly:
return 'usdc';
default:
return currency.title.toLowerCase();
}
}
String _networkFor(CryptoCurrency currency) =>
currency.tag != null ? _normalizeTag(currency.tag!) : 'mainnet';
String _normalizeTag(String tag) {
switch (tag) {
case 'ETH':
return 'ethereum';
case 'TRX':
return 'tron';
case 'LN':
return 'lightning';
case 'POL':
return 'polygon';
case 'ARB':
return 'arbitrum';
case 'ZEC':
return 'zcash';
case 'AVAXC':
return 'avax';
default:
return tag.toLowerCase();
}
}
String _normalizeNetworkType(String network) {
return switch (network) {
'ethereum' => 'ETH',
'tron' => 'TRX',
'lightning' => 'LN',
'polygon' => 'POL',
'arbitrum' => 'ARB',
'zcash' => 'ZEC',
'avax' => 'AVAXC',
_ => network,
};
}
}
@@ -1,371 +0,0 @@
import 'dart:convert';
import 'package:hash_wallet/.secrets.g.dart' as secrets;
import 'package:hash_wallet/exchange/provider/exchange_provider.dart';
import 'package:hash_wallet/exchange/exchange_provider_description.dart';
import 'package:hash_wallet/exchange/limits.dart';
import 'package:hash_wallet/exchange/trade.dart';
import 'package:hash_wallet/exchange/trade_not_created_exception.dart';
import 'package:hash_wallet/exchange/trade_not_found_exception.dart';
import 'package:hash_wallet/exchange/trade_request.dart';
import 'package:hash_wallet/exchange/trade_state.dart';
import 'package:hash_wallet/utils/device_info.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:hash_wallet/utils/exchange_provider_logger.dart';
class SimpleSwapExchangeProvider extends ExchangeProvider {
SimpleSwapExchangeProvider();
static final apiKey =
DeviceInfo.instance.isMobile ? secrets.simpleSwapApiKey : secrets.simpleSwapApiKeyDesktop;
static const apiAuthority = 'api.simpleswap.io';
static const getEstimatePath = '/v1/get_estimated';
static const rangePath = '/v1/get_ranges';
static const getExchangePath = '/v1/get_exchange';
static const createExchangePath = '/v1/create_exchange';
@override
String get title => 'SimpleSwap';
@override
bool get isAvailable => false;
@override
bool get isEnabled => false;
@override
bool get supportsFixedRate => false;
@override
ExchangeProviderDescription get description => ExchangeProviderDescription.simpleSwap;
@override
Future<bool> checkIsAvailable() async {
final uri = Uri.https(apiAuthority, getEstimatePath, <String, String>{'api_key': apiKey});
final response = await ProxyWrapper().get(clearnetUri: uri);
return !(response.statusCode == 403);
}
@override
Future<Limits?> fetchLimits(
{required CryptoCurrency from,
required CryptoCurrency to,
required bool isFixedRateMode}) async {
final params = <String, dynamic>{
'api_key': apiKey,
'fixed': isFixedRateMode.toString(),
'currency_from': _normalizeCurrency(from),
'currency_to': _normalizeCurrency(to),
};
final uri = Uri.https(apiAuthority, rangePath, params);
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode == 500) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['message'] as String;
throw Exception('$error');
}
if (response.statusCode != 200) {
throw Exception('Unexpected http status: ${response.statusCode}');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final min = double.tryParse(responseJSON['min'] as String? ?? '');
final max = double.tryParse(responseJSON['max'] as String? ?? '');
return Limits(min: min, max: max);
}
@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 params = {
'api_key': apiKey,
'currency_from': _normalizeCurrency(from),
'currency_to': _normalizeCurrency(to),
'amount': amount.toString(),
'fixed': isFixedRateMode.toString()
};
final uri = Uri.https(apiAuthority, getEstimatePath, params);
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.body == "null") {
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
error: Exception('Null response body'),
stackTrace: StackTrace.current,
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
'params': params,
'url': uri.toString(),
},
);
return 0.00;
}
final data = json.decode(response.body) as String;
final rate = double.parse(data) / amount;
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'fetchRate',
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
'params': params,
'url': uri.toString(),
},
responseData: {
'data': data,
'rate': rate,
'statusCode': response.statusCode,
'responseBody': response.body,
},
);
return rate;
} catch (e, s) {
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
error: e,
stackTrace: s,
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
},
);
return 0.00;
}
}
@override
Future<Trade> createTrade({
required TradeRequest request,
required bool isFixedRateMode,
required bool isSendAll,
}) async {
final headers = {'Content-Type': 'application/json'};
final params = {'api_key': apiKey};
final body = <String, dynamic>{
"currency_from": _normalizeCurrency(request.fromCurrency),
"currency_to": _normalizeCurrency(request.toCurrency),
"amount": request.fromAmount,
"fixed": isFixedRateMode,
"user_refund_address": _normalizeAddress(request.refundAddress),
"address_to": _normalizeAddress(request.toAddress)
};
final uri = Uri.https(apiAuthority, createExchangePath, params);
final response = await ProxyWrapper().post(
clearnetUri: uri,
headers: headers,
body: json.encode(body),
);
if (response.statusCode != 200 && response.statusCode != 201) {
if (response.statusCode == 400) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['message'] as String;
ExchangeProviderLogger.logError(
provider: description,
function: 'createTrade',
error: TradeNotCreatedException(description, description: error),
stackTrace: StackTrace.current,
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'body': body,
'url': uri.toString(),
},
);
throw TradeNotCreatedException(description, description: error);
}
ExchangeProviderLogger.logError(
provider: description,
function: 'createTrade',
error: TradeNotCreatedException(description),
stackTrace: StackTrace.current,
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'body': body,
'url': uri.toString(),
},
);
throw TradeNotCreatedException(description);
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final id = responseJSON['id'] as String;
final inputAddress = responseJSON['address_from'] as String;
final payoutAddress = responseJSON['address_to'] as String;
final settleAddress = responseJSON['user_refund_address'] as String;
final extraId = responseJSON['extra_id_from'] as String?;
final receiveAmount = responseJSON['amount_to'] as String?;
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'createTrade',
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'body': body,
'url': uri.toString(),
},
responseData: {
'id': id,
'inputAddress': inputAddress,
'payoutAddress': payoutAddress,
'settleAddress': settleAddress,
'extraId': extraId,
'receiveAmount': receiveAmount,
'statusCode': response.statusCode,
'responseJSON': responseJSON,
},
);
return Trade(
id: id,
provider: description,
from: request.fromCurrency,
to: request.toCurrency,
inputAddress: inputAddress,
refundAddress: settleAddress,
extraId: extraId,
state: TradeState.created,
amount: request.fromAmount,
receiveAmount: receiveAmount ?? request.toAmount,
payoutAddress: payoutAddress,
createdAt: DateTime.now(),
isSendAll: isSendAll,
);
}
@override
Future<Trade> findTradeById({required String id}) async {
final params = {'api_key': apiKey, 'id': id};
final uri = Uri.https(apiAuthority, getExchangePath, params);
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode == 404) {
throw TradeNotFoundException(id, provider: description);
}
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);
}
if (response.statusCode != 200) {
throw Exception('Unexpected http status: ${response.statusCode}');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final fromCurrency = responseJSON['currency_from'] as String;
final toCurrency = responseJSON['currency_to'] as String;
final inputAddress = responseJSON['address_from'] as String;
final expectedSendAmount = responseJSON['expected_amount'].toString();
final extraId = responseJSON['extra_id_from'] as String?;
final status = responseJSON['status'] as String;
final payoutAddress = responseJSON['address_to'] as String;
final fromParsed =
CryptoCurrency.safeParseCurrencyFromString(fromCurrency);
final toParsed = CryptoCurrency.safeParseCurrencyFromString(toCurrency);
return Trade(
id: id,
from: fromParsed,
to: toParsed,
extraId: extraId,
provider: description,
inputAddress: inputAddress,
amount: expectedSendAmount,
state: TradeState.deserialize(raw: status),
payoutAddress: payoutAddress,
);
}
static String _normalizeCurrency(CryptoCurrency currency) {
switch (currency) {
case CryptoCurrency.zec:
return 'zec';
case CryptoCurrency.bnb:
return currency.tag!.toLowerCase();
case CryptoCurrency.usdterc20:
return 'usdterc20';
case CryptoCurrency.usdttrc20:
return 'usdttrc20';
case CryptoCurrency.usdcpoly:
return 'usdcpoly';
case CryptoCurrency.usdtPoly:
return 'usdtpoly';
case CryptoCurrency.usdcEPoly:
return 'usdcepoly';
case CryptoCurrency.usdcsol:
return 'usdcspl';
case CryptoCurrency.matic:
return 'pol';
case CryptoCurrency.maticpoly:
return 'matic';
default:
return currency.title.toLowerCase();
}
}
String _normalizeAddress(String address) =>
address.startsWith('bitcoincash:') ? address.replaceFirst('bitcoincash:', '') : address;
}
@@ -1,448 +0,0 @@
import 'dart:convert';
import 'dart:developer';
import 'package:hash_wallet/.secrets.g.dart' as secrets;
import 'package:hash_wallet/exchange/provider/exchange_provider.dart';
import 'package:hash_wallet/exchange/exchange_provider_description.dart';
import 'package:hash_wallet/exchange/limits.dart';
import 'package:hash_wallet/exchange/trade.dart';
import 'package:hash_wallet/exchange/trade_not_created_exception.dart';
import 'package:hash_wallet/exchange/trade_request.dart';
import 'package:hash_wallet/exchange/trade_state.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:hash_wallet/utils/exchange_provider_logger.dart';
class StealthExExchangeProvider extends ExchangeProvider {
StealthExExchangeProvider();
static final apiKey = secrets.stealthExBearerToken;
static final _additionalFeePercent = double.tryParse(secrets.stealthExAdditionalFeePercent);
static const _baseUrl = 'https://api.stealthex.io';
static const _rangePath = '/v4/rates/range';
static const _amountPath = '/v4/rates/estimated-amount';
static const _exchangesPath = '/v4/exchanges';
@override
String get title => 'StealthEX';
@override
bool get isAvailable => true;
@override
bool get isEnabled => true;
@override
bool get supportsFixedRate => true;
@override
ExchangeProviderDescription get description => ExchangeProviderDescription.stealthEx;
@override
Future<bool> checkIsAvailable() async => true;
@override
Future<Limits?> fetchLimits(
{required CryptoCurrency from,
required CryptoCurrency to,
required bool isFixedRateMode}) async {
final curFrom = isFixedRateMode ? to : from;
final curTo = isFixedRateMode ? from : to;
final headers = {'Authorization': apiKey, 'Content-Type': 'application/json'};
final body = {
'route': {
'from': {'symbol': _getName(curFrom), 'network': _getNetwork(curFrom)},
'to': {'symbol': _getName(curTo), 'network': _getNetwork(curTo)}
},
'estimation': isFixedRateMode ? 'reversed' : 'direct',
'rate': isFixedRateMode ? 'fixed' : 'floating',
'additional_fee_percent': _additionalFeePercent,
};
try {
final response = await ProxyWrapper().post(
clearnetUri: Uri.parse(_baseUrl + _rangePath),
headers: headers,
body: json.encode(body),
);
if (response.statusCode != 200) {
throw Exception('StealthEx fetch limits failed: ${response.body}');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final min = _toDouble(responseJSON['min_amount']);
final max = _toDouble(responseJSON['max_amount']);
return Limits(min: min, max: max);
} catch (e) {
log(e.toString());
throw Exception('StealthEx failed to fetch limits');
}
}
@override
Future<double> fetchRate(
{required CryptoCurrency from,
required CryptoCurrency to,
required double amount,
required bool isFixedRateMode,
required bool isReceiveAmount}) async {
try {
final response = await getEstimatedExchangeAmount(
from: from,
to: to,
amount: amount,
isFixedRateMode: isFixedRateMode,
);
final estimatedAmount = response['estimated_amount'] as double? ?? 0.0;
if (estimatedAmount <= 0.0) {
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
error: Exception('Invalid estimated amount: $estimatedAmount'),
stackTrace: StackTrace.current,
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
},
);
return 0.0;
}
final rate = isFixedRateMode ? amount / estimatedAmount : estimatedAmount / amount;
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'fetchRate',
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
},
responseData: {
'estimatedAmount': estimatedAmount,
'rate': rate,
'response': response,
},
);
return rate;
} catch (e, s) {
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
error: e,
stackTrace: s,
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
},
);
return 0.0;
}
}
@override
Future<Trade> createTrade(
{required TradeRequest request,
required bool isFixedRateMode,
required bool isSendAll}) async {
String? rateId;
String? validUntil;
try {
if (isFixedRateMode) {
final response = await getEstimatedExchangeAmount(
from: request.fromCurrency,
to: request.toCurrency,
amount: double.parse(request.toAmount),
isFixedRateMode: isFixedRateMode);
rateId = response['rate_id'] as String?;
validUntil = response['valid_until'] as String?;
if (rateId == null) throw TradeNotCreatedException(description);
}
final headers = {'Authorization': apiKey, 'Content-Type': 'application/json'};
final body = {
'route': {
'from': {
'symbol': _getName(request.fromCurrency),
'network': _getNetwork(request.fromCurrency)
},
'to': {'symbol': _getName(request.toCurrency), 'network': _getNetwork(request.toCurrency)}
},
'estimation': isFixedRateMode ? 'reversed' : 'direct',
'rate': isFixedRateMode ? 'fixed' : 'floating',
if (isFixedRateMode) 'rate_id': rateId,
'amount':
isFixedRateMode ? double.parse(request.toAmount) : double.parse(request.fromAmount),
'address': _normalizeAddress(request.toAddress),
'refund_address': _normalizeAddress(request.refundAddress),
'additional_fee_percent': _additionalFeePercent,
};
final response = await ProxyWrapper().post(
clearnetUri: Uri.parse(_baseUrl + _exchangesPath),
headers: headers,
body: json.encode(body),
);
if (response.statusCode != 201) {
ExchangeProviderLogger.logError(
provider: description,
function: 'createTrade',
error: Exception('StealthEx create trade failed: ${response.body}'),
stackTrace: StackTrace.current,
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'body': body,
'rateId': rateId,
},
);
throw Exception('StealthEx create trade failed: ${response.body}');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final deposit = responseJSON['deposit'] as Map<String, dynamic>;
final withdrawal = responseJSON['withdrawal'] as Map<String, dynamic>;
final id = responseJSON['id'] as String;
final from = deposit['symbol'] as String;
final to = withdrawal['symbol'] as String;
final payoutAddress = withdrawal['address'] as String;
final depositAddress = deposit['address'] as String;
final refundAddress = responseJSON['refund_address'] as String;
final depositAmount = _toDouble(deposit['amount']);
final receiveAmount = _toDouble(withdrawal['amount']);
final status = responseJSON['status'] as String;
final createdAtString = responseJSON['created_at'] as String;
final extraId = deposit['extra_id'] as String?;
final createdAt = DateTime.parse(createdAtString).toLocal();
final expiredAt = validUntil != null
? DateTime.parse(validUntil).toLocal()
: DateTime.now().add(Duration(minutes: 5));
CryptoCurrency fromCurrency;
if (request.fromCurrency.tag != null && request.fromCurrency.title.toLowerCase() == from) {
fromCurrency = request.fromCurrency;
} else {
fromCurrency = CryptoCurrency.fromString(from);
}
CryptoCurrency toCurrency;
if (request.toCurrency.tag != null && request.toCurrency.title.toLowerCase() == to) {
toCurrency = request.toCurrency;
} else {
toCurrency = CryptoCurrency.fromString(to);
}
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'createTrade',
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'body': body,
'rateId': rateId,
},
responseData: {
'id': id,
'from': from,
'to': to,
'depositAddress': depositAddress,
'payoutAddress': payoutAddress,
'refundAddress': refundAddress,
'depositAmount': depositAmount,
'receiveAmount': receiveAmount,
'status': status,
'createdAt': createdAtString,
'extraId': extraId,
'statusCode': response.statusCode,
'responseJSON': responseJSON,
},
);
return Trade(
id: id,
from: fromCurrency,
to: toCurrency,
provider: description,
inputAddress: depositAddress,
payoutAddress: payoutAddress,
refundAddress: refundAddress,
amount: depositAmount.toString(),
receiveAmount: receiveAmount.toString(),
state: TradeState.deserialize(raw: status),
createdAt: createdAt,
expiredAt: expiredAt,
extraId: extraId,
isSendAll: isSendAll,
);
} catch (e, s) {
ExchangeProviderLogger.logError(
provider: description,
function: 'createTrade',
error: e,
stackTrace: s,
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
},
);
log(e.toString());
throw TradeNotCreatedException(description);
}
}
@override
Future<Trade> findTradeById({required String id}) async {
final headers = {'Authorization': apiKey, 'Content-Type': 'application/json'};
final uri = Uri.parse('$_baseUrl$_exchangesPath/$id');
final response = await ProxyWrapper().get(clearnetUri: uri, headers: headers);
if (response.statusCode != 200) {
throw Exception('StealthEx fetch trade failed: ${response.body}');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final deposit = responseJSON['deposit'] as Map<String, dynamic>;
final withdrawal = responseJSON['withdrawal'] as Map<String, dynamic>;
final respId = responseJSON['id'] as String;
// Parsing 'from' currency with network tag
final fromCurrency = deposit['symbol'] as String;
final fromNetwork = deposit['network'] as String?;
final fromTag = fromNetwork == 'mainnet' ? null : fromNetwork;
final from = CryptoCurrency.safeParseCurrencyFromString(fromCurrency, tag: fromTag);
// Parsing 'to' currency with network tag
final toCurrency = withdrawal['symbol'] as String;
final toNetwork = withdrawal['network'] as String?;
final toTag = toNetwork == 'mainnet' ? null : toNetwork;
final to = CryptoCurrency.safeParseCurrencyFromString(toCurrency, tag: toTag);
final payoutAddress = withdrawal['address'] as String;
final depositAddress = deposit['address'] as String;
final refundAddress = responseJSON['refund_address'] as String;
final depositAmount = _toDouble(deposit['amount']);
final receiveAmount = _toDouble(withdrawal['amount']);
final status = responseJSON['status'] as String;
final createdAtString = responseJSON['created_at'] as String;
final createdAt = DateTime.parse(createdAtString).toLocal();
final extraId = deposit['extra_id'] as String?;
return Trade(
id: respId,
from: from,
to: to,
provider: description,
inputAddress: depositAddress,
payoutAddress: payoutAddress,
refundAddress: refundAddress,
amount: depositAmount.toString(),
receiveAmount: receiveAmount.toString(),
state: TradeState.deserialize(raw: status),
createdAt: createdAt,
isRefund: status == 'refunded',
extraId: extraId,
);
}
Future<Map<String, dynamic>> getEstimatedExchangeAmount(
{required CryptoCurrency from,
required CryptoCurrency to,
required double amount,
required bool isFixedRateMode}) async {
final headers = {'Authorization': apiKey, 'Content-Type': 'application/json'};
final body = {
'route': {
'from': {'symbol': _getName(from), 'network': _getNetwork(from)},
'to': {'symbol': _getName(to), 'network': _getNetwork(to)}
},
'estimation': isFixedRateMode ? 'reversed' : 'direct',
'rate': isFixedRateMode ? 'fixed' : 'floating',
'amount': amount,
'additional_fee_percent': _additionalFeePercent,
};
try {
final response = await ProxyWrapper().post(
clearnetUri: Uri.parse(_baseUrl + _amountPath),
headers: headers,
body: json.encode(body),
);
if (response.statusCode != 200) return {};
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final rate = responseJSON['rate'] as Map<String, dynamic>?;
return {
'estimated_amount': responseJSON['estimated_amount'] as double?,
if (rate != null) 'valid_until': rate['valid_until'] as String?,
if (rate != null) 'rate_id': rate['id'] as String?
};
} catch (e) {
log(e.toString());
return {};
}
}
static double? _toDouble(dynamic value) {
if (value is int) {
return value.toDouble();
} else if (value is double) {
return value;
} else if (value is String) {
return double.tryParse(value);
}
return null;
}
String _getName(CryptoCurrency currency) {
if (currency == CryptoCurrency.usdcEPoly) return 'usdce';
return currency.title.toLowerCase();
}
String _getNetwork(CryptoCurrency currency) {
if (currency == CryptoCurrency.arb || currency.tag == 'ARB') return 'arbitrum';
if (currency.tag == null) return 'mainnet';
if (currency == CryptoCurrency.maticpoly) return 'mainnet';
if (currency.tag == 'POLY') return 'matic';
return currency.tag!.toLowerCase();
}
String _normalizeAddress(String address) =>
address.startsWith('bitcoincash:') ? address.replaceFirst('bitcoincash:', '') : address;
}
@@ -1,865 +0,0 @@
import 'dart:convert';
import 'package:hash_wallet/.secrets.g.dart' as secrets;
import 'package:hash_wallet/exchange/provider/exchange_provider.dart';
import 'package:hash_wallet/exchange/exchange_provider_description.dart';
import 'package:hash_wallet/exchange/limits.dart';
import 'package:hash_wallet/exchange/trade.dart';
import 'package:hash_wallet/exchange/trade_not_created_exception.dart';
import 'package:hash_wallet/exchange/trade_request.dart';
import 'package:hash_wallet/exchange/trade_state.dart';
import 'package:cw_core/amount_converter.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/crypto_currency.dart';
class SwapsXyzExchangeProvider extends ExchangeProvider {
SwapsXyzExchangeProvider();
static final List<CryptoCurrency> _notSupportedAsSourceToken = [
CryptoCurrency.sol,
...CryptoCurrency.all.where(
(c) => (c.tag ?? '').toUpperCase() == 'SOL' || c.tag == CryptoCurrency.bnb.tag,
),
];
static const _transferSig = '0xa9059cbb';
static const _swapAndExecuteSig = '0x9be111d1';
static final _apiKey = secrets.swapsXyzApiKey;
static const _baseUrl = 'api-v2.swaps.xyz';
static const _getChainList = 'api/getChainList';
static const _getPaths = 'api/getPaths';
static const _getQuotePaths = 'api/getQuote';
static const _getAction = 'api/getAction';
static const _registerTxs = 'api/registerTxs';
static const _getStatus = 'api/getStatus';
static final _headers = {'x-api-key': _apiKey};
static final _supportedChainList = <Chain>[];
final Map<int, List<TokenPathInfo>> _tokensCache = {};
@override
String get title => 'Swaps.XYZ';
@override
bool get isAvailable => true;
@override
bool get isEnabled => true;
// There is an issue with fixed-rate swaps on Swaps.XYZ
// when they don't guarantee that the trade will be created at the requested amount.
@override
bool get supportsFixedRate => false;
@override
ExchangeProviderDescription get description =>
ExchangeProviderDescription.swapsXyz;
@override
Future<bool> checkIsAvailable() async => true;
@override
Future<Limits?> fetchLimits({
required CryptoCurrency from,
required CryptoCurrency to,
required bool isFixedRateMode,
}) async {
try {
final chains = await _geSupportedChain();
if (chains.isEmpty) throw Exception('Failed to fetch supported chains');
final fromToUse = isFixedRateMode ? to : from;
final toToUse = isFixedRateMode ? from : to;
final srcChain = _findChainByCurrency(fromToUse, chains);
final dstChain = _findChainByCurrency(toToUse, chains);
await _ensureTokensCached(
fromChain: srcChain, toChain: dstChain, from: fromToUse, to: toToUse);
final srcToken = _getTokenAddress(currency: fromToUse, chain: srcChain);
final dstToken = _getTokenAddress(currency: toToUse, chain: dstChain);
final params = {
'srcChainId': '${srcChain.chainId}',
'srcToken': srcToken,
'dstChainId': '${dstChain.chainId}',
'dstToken': dstToken,
};
final uri = Uri.https(_baseUrl, _getPaths, params);
final res = await ProxyWrapper().get(clearnetUri: uri, headers: _headers);
if (res.statusCode != 200) {
throw Exception('Unexpected http status: ${res.statusCode}');
}
final body = json.decode(res.body) as Map<String, dynamic>;
final paths =
(body['paths'] as List? ?? const []).cast<Map<String, dynamic>>();
if (paths.isEmpty) {
throw Exception('No paths for ${fromToUse.title} -> ${toToUse.title}');
}
final int requestedDstId = dstChain.chainId;
Map<String, dynamic> path = paths.firstWhere(
(p) => p['chainId'] == requestedDstId,
orElse: () => <String, dynamic>{},
);
if (path.isEmpty) {
path = paths.firstWhere(
(p) => (p['tokens'] is List) || p['amountLimits'] != null,
orElse: () => paths.first,
);
}
final supportsExactAmountIn =
path['supportsExactAmountIn'] as bool? ?? false;
final supportsExactAmountOut =
path['supportsExactAmountOut'] as bool? ?? false;
if (isFixedRateMode && !supportsExactAmountOut) {
throw Exception(
'This route does not support fixed receive (exact-amount-out)');
}
if (!isFixedRateMode && !supportsExactAmountIn) {
throw Exception(
'This route does not support exact send (exact-amount-in)');
}
Map<String, dynamic>? useLimits;
if (isFixedRateMode) {
final tokensField = path['tokens'];
useLimits = null;
if (tokensField is List && tokensField.isNotEmpty) {
final tokens = tokensField.cast<Map<String, dynamic>>();
String norm(String s) => s.toUpperCase();
final wantSym = norm(_normalizeCakeNativeTokenName(toToUse.title));
final wantAddr = (dstToken).toLowerCase();
final match = tokens.firstWhere(
(t) {
final sym = norm(t['symbol']?.toString() ?? '');
final addr = (t['address']?.toString() ?? '').toLowerCase();
return sym == wantSym || (addr.isNotEmpty && addr == wantAddr);
},
orElse: () => const <String, dynamic>{},
);
if (match.isNotEmpty) {
useLimits = {
'minAmount': match['minAmount'],
'maxAmount': match['maxAmount'],
};
}
}
} else {
// Floating/Exact-in: use the route-level limits
useLimits = path['amountLimits'] as Map<String, dynamic>?;
}
final min = double.tryParse((useLimits?['minAmount'])?.toString() ?? '');
final max = double.tryParse((useLimits?['maxAmount'])?.toString() ?? '');
return Limits(min: min, max: max);
} catch (e) {
printV('fetchLimits error: $e');
throw Exception('Error fetching limits: $e');
}
}
Future<_PathInfo?> _pickPath({
required int srcChainId,
required String srcToken,
required int dstChainId,
required String dstToken,
}) async {
final uri = Uri.https(_baseUrl, _getPaths, {
'srcChainId': '$srcChainId',
'srcToken': srcToken,
'dstChainId': '$dstChainId',
'dstToken': dstToken,
});
final res = await ProxyWrapper().get(clearnetUri: uri, headers: _headers);
if (res.statusCode != 200) return null;
final body = json.decode(res.body) as Map<String, dynamic>;
final paths =
(body['paths'] as List?)?.cast<Map<String, dynamic>>() ?? const [];
if (paths.isEmpty) return null;
final p = paths.first;
return _PathInfo(
supportsExactOut: p['supportsExactAmountOut'] == true,
minToAmountHuman: (p['amountLimits']?['minAmount'] as String?) ?? '0',
);
}
@override
Future<double> fetchRate(
{required CryptoCurrency from,
required CryptoCurrency to,
required double amount,
required bool isFixedRateMode,
required bool isReceiveAmount}) async {
try {
if(_notSupportedAsSourceToken.contains(from) || _notSupportedAsSourceToken.contains(to)) {
printV(
'fetchRate: source token ${from.title} is not supported as source token');
return 0.0;
}
final chains = await _geSupportedChain();
if (chains.isEmpty) return 0.0;
final srcChain = _findChainByCurrency(from, chains);
final dstChain = _findChainByCurrency(to, chains);
await _ensureTokensCached(
fromChain: srcChain, toChain: dstChain, from: from, to: to);
final srcToken = _getTokenAddress(currency: from, chain: srcChain);
final dstToken = _getTokenAddress(currency: to, chain: dstChain);
if (isReceiveAmount) {
final path = await _pickPath(
srcChainId: srcChain.chainId,
srcToken: srcToken,
dstChainId: dstChain.chainId,
dstToken: dstToken,
);
if (path == null || !path.supportsExactOut) {
printV(
'fetchRate: route does not support exact-amount-out for ${from.title} -> ${to.title}');
return 0.0;
}
}
final humanAmountStr = amount.toString();
final formattedAmount = AmountConverter.toBaseUnits(
humanAmountStr,
isReceiveAmount ? to.decimals : from.decimals,
);
final params = {
'swapDirection':
isReceiveAmount ? 'exact-amount-out' : 'exact-amount-in',
'srcToken': srcToken,
'dstToken': dstToken,
'srcChainId': '${srcChain.chainId}',
'dstChainId': '${dstChain.chainId}',
'amount': formattedAmount,
};
final uri = Uri.https(_baseUrl, _getQuotePaths, params);
final response =
await ProxyWrapper().get(clearnetUri: uri, headers: _headers);
if (response.statusCode != 200) {
printV('fetchRate failed: ${response.body}');
return 0.0;
}
final data = json.decode(response.body) as Map<String, dynamic>;
final exchangeRate = (data['exchangeRate'] as num?)?.toDouble() ?? 0.0;
return exchangeRate;
} catch (e) {
printV('fetchRate error: $e');
return 0.0;
}
}
@override
Future<Trade> createTrade({
required TradeRequest request,
required bool isFixedRateMode,
required bool isSendAll,
}) async {
try {
final sender = request.refundAddress.trim();
final recipient = request.toAddress.trim();
if (sender.isEmpty || recipient.isEmpty) {
throw Exception(
'Sender (refundAddress) or recipient (toAddress) is empty');
}
final chains = await _geSupportedChain();
if (chains.isEmpty) throw Exception('Failed to fetch supported chains');
final srcChain = _findChainByCurrency(request.fromCurrency, chains);
final dstChain = _findChainByCurrency(request.toCurrency, chains);
await _ensureTokensCached(
fromChain: srcChain,
toChain: dstChain,
from: request.fromCurrency,
to: request.toCurrency,
);
final srcToken =
_getTokenAddress(currency: request.fromCurrency, chain: srcChain);
final dstToken =
_getTokenAddress(currency: request.toCurrency, chain: dstChain);
final amountStr = isFixedRateMode ? request.toAmount : request.fromAmount;
final rawAmount = double.tryParse(amountStr) ?? 0.0;
if (rawAmount <= 0) throw Exception('Invalid amount');
final formattedAmount = AmountConverter.toBaseUnits(
amountStr,
isFixedRateMode
? request.toCurrency.decimals
: request.fromCurrency.decimals,
);
final params = {
'actionType': 'swap-action',
'sender': sender,
'srcChainId': '${srcChain.chainId}',
'srcToken': srcToken,
'dstChainId': '${dstChain.chainId}',
'dstToken': dstToken,
'slippage': '300',
'swapDirection':
isFixedRateMode ? 'exact-amount-out' : 'exact-amount-in',
'amount': formattedAmount,
'recipient': recipient,
};
final uri = Uri.https(_baseUrl, _getAction, params);
final res = await ProxyWrapper().get(clearnetUri: uri, headers: _headers);
if (res.statusCode != 200) {
throw Exception('getAction failed: ${res.statusCode} ${res.body}');
}
final data = json.decode(res.body) as Map<String, dynamic>;
final txId = data['txId'] as String? ?? '';
final vmId = data['vmId'] as String? ?? '';
final txObj = (data['tx'] as Map?) ?? const {};
final txTo = txObj['to']?.toString();
final chainId = txObj['chainId']?.toString();
final routerData = txObj['data']?.toString();
// Allow only:
// - null (native / deposit-address flow)
// - '0x' (no call data)
// - ERC20 transfer(0xa9059cbb) selector
// - swapAndExecute(0x9be111d1) selector
final isAllowed = routerData == null ||
routerData == '0x' ||
_decodeMethodSelector(routerData) == _transferSig ||
_decodeMethodSelector(routerData) == _swapAndExecuteSig;
if (!isAllowed) {
throw Exception('Does not support that method selector');
}
final txValue = txObj['value']?.toString() ?? '0';
final bridgeIds = (data['bridgeIds'] as List?) ?? const [];
if (txId.isEmpty) throw Exception('No txId returned by getAction');
final amtIn = (data['amountIn'] as Map?) ?? const {};
final amtInMax = (data['amountInMax'] as Map?) ?? const {};
final srcTokenAddr = amtIn['address']?.toString();
final srcTokenDecs =
(amtIn['decimals'] as num?)?.toInt() ?? request.fromCurrency.decimals;
final requiresTokenApproval =
data['requiresTokenApproval'] as bool? ?? false;
final reqAmountStr =
(amtInMax['amount'] ?? amtIn['amount'])?.toString() ?? '0';
final reqAmountRaw = reqAmountStr.replaceAll('n', '');
final needToRegisterInSwapXyz =
vmId == 'alt-vm' || bridgeIds.contains('alt-vm')
|| chainId == 'solana' || bridgeIds.contains('solana');
final trade = Trade(
id: txId,
router: chainId,
providerId: vmId,
from: request.fromCurrency,
to: request.toCurrency,
provider: description,
inputAddress: txTo,
refundAddress: request.refundAddress,
state: TradeState.created,
providerName: title,
createdAt: DateTime.now(),
amount: request.fromAmount,
receiveAmount: request.toAmount,
payoutAddress: request.toAddress,
isSendAll: isSendAll,
needToRegisterInSwapXyz: needToRegisterInSwapXyz,
sourceTokenAddress: srcTokenAddr ?? srcToken,
sourceTokenDecimals: srcTokenDecs,
sourceTokenAmountRaw: reqAmountRaw,
requiresTokenApproval: requiresTokenApproval,
routerData: routerData,
routerValue: txValue,
);
return trade;
} catch (e) {
printV('createTrade error: $e');
throw TradeNotCreatedException(description, description: e.toString());
}
}
/// Register a broadcasted tx with Swaps.xyz (required for alt-vm).
static Future<bool> registerAltVmTx({
required String txId,
required String txHash,
required int chainId,
required String vmId,
}) async {
try {
final uri = Uri.https(_baseUrl, _registerTxs);
final payload = {
'txId': txId,
'vmId': vmId,
'txHash': txHash,
'chainId': chainId,
};
final res = await ProxyWrapper().post(
clearnetUri: uri,
headers: {
..._headers,
'content-type': 'application/json',
},
body: jsonEncode(payload),
);
if (res.statusCode != 200) {
printV('registerTxs failed: ${res.statusCode} ${res.body}');
return false;
}
final List<dynamic> body = json.decode(res.body) as List<dynamic>;
if (body.isEmpty) return false;
final isSuccess =
(body[0] as Map<String, dynamic>)['success'] as bool? ?? false;
return isSuccess;
} catch (e) {
printV('registerAltVmTx error: $e');
return false;
}
}
@override
Future<Trade> findTradeById({required String id}) async {
if (id.isEmpty) {
throw Exception('Trade id is empty');
}
final uri = Uri.https(_baseUrl, _getStatus, {'txId': id});
final resp = await ProxyWrapper().get(clearnetUri: uri, headers: _headers);
if (resp.statusCode != 200) {
throw Exception('getStatus failed: ${resp.statusCode} ${resp.body}');
}
final data = json.decode(resp.body) as Map<String, dynamic>;
final isSuccess = (data['success'] as bool?);
if (isSuccess != null && !isSuccess) {
final error = data['error'] as Map<String, dynamic>?;
if (error != null) {
final code = error['code']?.toString() ?? 'unknown';
throw Exception(
'SwapXyzExchangeProvider findTradeById error: ($id) $code');
}
}
final statusStr = (data['status'] as String?)?.toLowerCase() ?? 'NOT_FOUND';
final state = _mapSwapsStatusToTradeState(statusStr);
final refundAddress = data['sender']?.toString();
final srcTransaction = (data['srcTx'] as Map?)?.cast<String, dynamic>();
final dstTransaction = (data['dstTx'] as Map?)?.cast<String, dynamic>();
final inputAddress = srcTransaction?['toAddress']?.toString();
final payoutAddress = dstTransaction?['toAddress']?.toString();
final srcPaymentToken =
(srcTransaction?['paymentToken'] as Map?)?.cast<String, dynamic>();
final dstPaymentToken =
(dstTransaction?['paymentToken'] as Map?)?.cast<String, dynamic>();
final fromSymbol = (srcPaymentToken?['symbol'] as String?) ?? '';
final toSymbol = (dstPaymentToken?['symbol'] as String?) ?? '';
CryptoCurrency? toCurrency;
if (toSymbol.isNotEmpty) {
toCurrency = CryptoCurrency.safeParseCurrencyFromString(toSymbol);
}
final srcDecimals = (srcPaymentToken?['decimals'] as num?)?.toInt() ?? 0;
final dstDecimals = (dstPaymentToken?['decimals'] as num?)?.toInt() ?? 0;
final txHash = srcTransaction?['txHash'] as String?;
// Minimal-unit amounts like "12000n"
final srcAmountRaw = srcPaymentToken?['amount']?.toString();
final dstAmountRaw = dstPaymentToken?['amount']?.toString();
String? receiveAmount;
if (dstAmountRaw != null) {
final dstAmountMinimal = _stripN(dstAmountRaw);
receiveAmount =
AmountConverter.fromBaseUnits(dstAmountMinimal, dstDecimals);
}
final srcAmountMinimal = _stripN(srcAmountRaw);
final amount = AmountConverter.fromBaseUnits(srcAmountMinimal, srcDecimals);
final fromCurrency = CryptoCurrency.safeParseCurrencyFromString(fromSymbol);
// Timestamps can be num or "123n" handle both
final srcTs = _parseUnixSeconds(srcTransaction?['timestamp']);
final dstTs = _parseUnixSeconds(dstTransaction?['timestamp']);
final timestamp = srcTs ?? dstTs;
final createdAt = timestamp != null
? DateTime.fromMillisecondsSinceEpoch(timestamp * 1000, isUtc: true)
.toLocal()
: null;
return Trade(
id: (data['txId'] as String?) ?? id,
from: fromCurrency,
to: toCurrency,
provider: description,
inputAddress: inputAddress,
payoutAddress: payoutAddress,
amount: amount,
receiveAmount: receiveAmount,
txId: txHash,
state: state,
createdAt: createdAt,
refundAddress: refundAddress,
);
}
TradeState _mapSwapsStatusToTradeState(String s) {
switch (s) {
case 'pending':
case 'processing':
return TradeState.pending;
case 'success':
case 'completed':
case 'complete':
return TradeState.finished;
case 'failed':
case 'cancelled':
case 'canceled':
case 'error':
return TradeState.failed;
default:
return TradeState.pending;
}
}
// Load & cache supported chains once
Future<List<Chain>> _geSupportedChain() async {
if (_supportedChainList.isNotEmpty) return _supportedChainList;
try {
final uri = Uri.https(_baseUrl, _getChainList);
final response =
await ProxyWrapper().get(clearnetUri: uri, headers: _headers);
if (response.statusCode != 200) return [];
final data = json.decode(response.body) as List<dynamic>;
_supportedChainList
..clear()
..addAll(data.map((e) => Chain.fromJson(e as Map<String, dynamic>)));
return _supportedChainList;
} catch (e) {
printV(e);
return [];
}
}
Future<void> _ensureTokensCached({
required Chain fromChain,
required Chain toChain,
required CryptoCurrency from,
required CryptoCurrency to,
}) async {
final needSrc = !_tokensCache.containsKey(fromChain.chainId) ||
(_tokensCache[fromChain.chainId]?.isEmpty ?? true);
final needDst = !_tokensCache.containsKey(toChain.chainId) ||
(_tokensCache[toChain.chainId]?.isEmpty ?? true);
if (!needSrc && !needDst) return;
if (needSrc) {
await _fetchAndCacheTokens(srcChainId: fromChain.chainId);
}
if (needDst) {
await _fetchAndCacheTokens(srcChainId: toChain.chainId);
}
}
// call getPaths and merge tokens into cache keyed by the chainId
Future<void> _fetchAndCacheTokens({
required int srcChainId,
}) async {
final params = <String, String>{
'srcChainId': '$srcChainId',
'srcToken': '0x0000000000000000000000000000000000000000',
// Native placeholder
};
final uri = Uri.https(_baseUrl, _getPaths, params);
final res = await ProxyWrapper().get(clearnetUri: uri, headers: _headers);
if (res.statusCode != 200) {
printV('getPaths failed: ${res.statusCode} ${res.body}');
return;
}
Map<String, dynamic> body;
try {
body = json.decode(res.body) as Map<String, dynamic>;
} catch (e) {
printV('getPaths JSON decode error: $e');
return;
}
// Always cache the source chain's native token (from body['srcToken'])
final srcTokenJson = body['srcToken'] as Map<String, dynamic>?;
if (srcTokenJson != null) {
final symbol = (srcTokenJson['symbol'] as String? ?? '').toUpperCase();
if (symbol.isNotEmpty) {
final isNative = srcTokenJson['isNative'] == true;
final decimals = (srcTokenJson['decimals'] as num?)?.toInt();
// Treat native token as address = null so _getTokenAddress() emits zero-address
final addr = isNative ? null : (srcTokenJson['address'] as String?);
_mergeCache(srcChainId, [
TokenPathInfo(
symbol: symbol,
address: addr,
decimals: decimals,
minAmount: srcTokenJson['minAmount']?.toString(),
maxAmount: srcTokenJson['maxAmount']?.toString(),
),
]);
}
}
final paths = (body['paths'] as List?) ?? const [];
if (paths.isEmpty) return;
for (final path in paths) {
final map = path as Map<String, dynamic>;
final pathChainId = (map['chainId'] as num?)?.toInt();
if (pathChainId == null) continue;
final tokensField = map['tokens'];
// Case 1: String "all" -> cache empty list to indicate all tokens supported
if (tokensField is String) {
if (tokensField.toLowerCase() == 'all') {
_tokensCache[pathChainId] =
_tokensCache[pathChainId] ?? <TokenPathInfo>[];
}
continue;
}
// Case 2: List -> parse and merge
if (tokensField is List) {
final parsed = <TokenPathInfo>[];
for (final token in tokensField) {
if (token is Map<String, dynamic>) {
try {
parsed.add(TokenPathInfo.fromJson(token));
} catch (e) {
printV('Token parse error on chain $pathChainId: $e : $token');
}
}
}
if (parsed.isNotEmpty) {
_mergeCache(pathChainId, parsed);
}
}
}
}
// Merge by symbol, prefer entries that have a non-empty address/decimals
void _mergeCache(int chainId, List<TokenPathInfo> incoming) {
final existing = _tokensCache[chainId] ?? const <TokenPathInfo>[];
final bySymbol = <String, TokenPathInfo>{
for (final t in existing) t.symbol: t
};
for (final t in incoming) {
final cur = bySymbol[t.symbol];
if (cur == null) {
bySymbol[t.symbol] = t;
} else {
// If incoming has a real address/decimals, prefer it
final hasBetterAddr = (t.address != null && t.address!.isNotEmpty) &&
(cur.address == null || cur.address!.isEmpty);
final hasBetterDec = (t.decimals != null) && (cur.decimals == null);
if (hasBetterAddr || hasBetterDec) {
bySymbol[t.symbol] = t;
}
}
}
_tokensCache[chainId] = bySymbol.values.toList();
}
String _normalizeCakeNativeTokenName(String title) {
final name = title.toUpperCase();
return switch (name) {
'ZZEC' => 'ZEC',
_ => name,
};
}
String _getTokenAddress({
required CryptoCurrency currency,
required Chain chain,
}) {
final symbol = _normalizeCakeNativeTokenName(currency.title);
final list = _tokensCache[chain.chainId];
// Try cache hit
if (list != null && list.isNotEmpty) {
for (final t in list) {
if (t.symbol == symbol && t.address != null && t.address!.isNotEmpty) {
return t.address!;
} else if (t.symbol == symbol && (t.address == null)) {
// Native token on this chain
return '0x0000000000000000000000000000000000000000';
}
}
}
// May fail for non-native Alt-VM assets
return symbol;
}
Map<String, dynamic>? findTokenBySymbol(
{required String title, required List<dynamic> tokens}) {
final reqSymbol = title.toUpperCase();
for (final token in tokens) {
final map = token as Map<String, dynamic>;
final symbol = (map['symbol'] as String?)?.toUpperCase();
if (symbol == reqSymbol) return map;
}
return null;
}
Chain _findChainByCurrency(CryptoCurrency cur, List<Chain> chains) {
final network = _normalizeCakeNetwork(cur.tag ?? cur.title);
return chains.firstWhere(
(c) {
return c.name.toUpperCase() == network;
},
orElse: () => throw Exception('Unsupported chain for ${cur.title}'),
);
}
String _normalizeCakeNetwork(String network) {
return switch (network.toUpperCase()) {
'ETH' => 'ETHEREUM',
'BSC' => 'BNB SMART CHAIN',
'POL' => 'POLYGON',
'AVAXC' => 'AVALANCHE',
'TRX' => 'TRON',
'SOL' => 'SOLANA',
'CRO' => 'CRONOS',
'ADA' => 'CARDANO',
'KAS' => 'KASPA',
'TON' => 'TONCOIN',
'BCH' => 'BITCOIN CASH',
'ARB' => 'ARBITRUM',
_ => network.toUpperCase(),
};
}
int? _parseUnixSeconds(dynamic value) {
if (value == null) return null;
if (value is num) return value.toInt();
if (value is String) {
final clean = _stripN(value);
return int.tryParse(clean);
}
return null;
}
String _stripN(String? str) {
final s = str ?? '0';
return s.endsWith('n') ? s.substring(0, s.length - 1) : s;
}
String _decodeMethodSelector(String s) =>
(s.startsWith('0x') && s.length >= 10) ? s.substring(0, 10) : '';
}
class TokenPathInfo {
final String symbol;
final String? address;
final int? decimals;
final String? minAmount;
final String? maxAmount;
TokenPathInfo({
required this.symbol,
required this.address,
required this.decimals,
required this.minAmount,
required this.maxAmount,
});
factory TokenPathInfo.fromJson(Map<String, dynamic> json) => TokenPathInfo(
symbol: (json['symbol'] as String?)?.toUpperCase() ?? '',
address: json['address'] as String?,
decimals: json['decimals'] as int?,
minAmount: json['minAmount']?.toString(),
maxAmount: json['maxAmount']?.toString(),
);
}
class Chain {
final int chainId;
final String name;
final String vmId;
Chain({
required this.chainId,
required this.name,
required this.vmId,
});
factory Chain.fromJson(Map<String, dynamic> json) {
return Chain(
chainId: json['chainId'] as int,
name: json['name'] as String,
vmId: json['vmId'] as String,
);
}
}
class _PathInfo {
final bool supportsExactOut;
final String minToAmountHuman;
_PathInfo({required this.supportsExactOut, required this.minToAmountHuman});
}
@@ -1,411 +0,0 @@
import 'dart:convert';
import 'package:hash_wallet/.secrets.g.dart' as secrets;
import 'package:hash_wallet/exchange/exchange_provider_description.dart';
import 'package:hash_wallet/exchange/limits.dart';
import 'package:hash_wallet/exchange/provider/exchange_provider.dart';
import 'package:hash_wallet/exchange/trade.dart';
import 'package:hash_wallet/exchange/trade_not_created_exception.dart';
import 'package:hash_wallet/exchange/trade_not_found_exception.dart';
import 'package:hash_wallet/exchange/trade_request.dart';
import 'package:hash_wallet/exchange/trade_state.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:hash_wallet/utils/exchange_provider_logger.dart';
class SwapTradeExchangeProvider extends ExchangeProvider {
SwapTradeExchangeProvider();
static final markup = secrets.swapTradeExchangeMarkup;
static const apiAuthority = 'api.swaptrade.io';
static const getRate = '/api/swap/get-rate';
static const getCoins = '/api/swap/get-coins';
static const createOrder = '/api/swap/create-order';
static const order = '/api/swap/order';
@override
String get title => 'SwapTrade';
@override
bool get isAvailable => true;
@override
bool get isEnabled => true;
@override
bool get supportsFixedRate => false;
@override
ExchangeProviderDescription get description => ExchangeProviderDescription.swapTrade;
static const _headers = <String, String>{'Content-Type': 'application/json'};
@override
Future<bool> checkIsAvailable() async => true;
@override
Future<Limits?> fetchLimits({
required CryptoCurrency from,
required CryptoCurrency to,
required bool isFixedRateMode,
}) async {
try {
final uri = Uri.https(apiAuthority, getCoins);
final response = await ProxyWrapper().get(clearnetUri: uri);
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
if (response.statusCode != 200)
throw Exception('Unexpected http status: ${response.statusCode}');
final coinsInfoRaw = responseJSON['data'];
final coinsInfo = coinsInfoRaw is List<dynamic> ? coinsInfoRaw : <dynamic>[];
final normalized = _normalizeCurrency(from);
final coin = coinsInfo.cast<Map<String, dynamic>>().firstWhere(
(c) => (c['id']?.toString().toUpperCase() ?? '') == normalized,
orElse: () => <String, dynamic>{},
);
if (coin.isEmpty) {
// Currency not supported by SwapTrade (e.g. USDC, DOGE).
return null;
}
final min = double.tryParse(coin['min']?.toString() ?? '') ?? 0.0;
final max = double.tryParse(coin['max']?.toString() ?? '') ?? 0.0;
if (max == 0) return null;
return Limits(min: min, max: max);
} catch (e) {
printV(e.toString());
return null;
}
}
@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;
if (isFixedRateMode && !supportsFixedRate) {
return 0.0;
}
if(from == CryptoCurrency.btcln || to == CryptoCurrency.btcln) return 0;
final params = <String, dynamic>{};
final body = <String, String>{
'coin_send': _normalizeCurrency(from),
'coin_receive': _normalizeCurrency(to),
'amount': amount.toString(),
'ref': 'cake',
};
final uri = Uri.https(apiAuthority, getRate, params);
final response = await ProxyWrapper().post(
clearnetUri: uri,
body: json.encode(body),
headers: _headers,
);
final responseBody = json.decode(response.body) as Map<String, dynamic>;
if (response.statusCode != 200) {
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
error: Exception('Unexpected http status: ${response.statusCode}'),
stackTrace: StackTrace.current,
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
'body': body,
'url': uri.toString(),
},
);
throw Exception('Unexpected http status: ${response.statusCode}');
}
final data = responseBody['data'] as Map<String, dynamic>;
double rate = double.parse(data['price'].toString());
final calculatedRate = rate > 0 ? isFixedRateMode ? amount / rate : rate / amount : 0.0;
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'fetchRate',
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
'body': body,
'url': uri.toString(),
},
responseData: {
'rate': rate,
'calculatedRate': calculatedRate,
'statusCode': response.statusCode,
'responseBody': responseBody,
},
);
return calculatedRate;
} catch (e, s) {
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
error: e,
stackTrace: s,
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
},
);
printV("error fetching rate: ${e.toString()}");
return 0.0;
}
}
@override
Future<Trade> createTrade({
required TradeRequest request,
required bool isFixedRateMode,
required bool isSendAll,
}) async {
try {
final params = <String, dynamic>{};
var body = <String, dynamic>{
'coin_send': _normalizeCurrency(request.fromCurrency),
'coin_send_network': _networkFor(request.fromCurrency),
'coin_receive': _normalizeCurrency(request.toCurrency),
'coin_receive_network': _networkFor(request.toCurrency),
'amount_send': request.fromAmount,
'recipient': request.toAddress,
'ref': 'cake',
'markup': double.tryParse(markup.toString()) ?? 0,
'refund_address': request.refundAddress,
};
final uri = Uri.https(apiAuthority, createOrder, params);
final response = await ProxyWrapper().post(
clearnetUri: uri,
body: json.encode(body),
headers: _headers,
);
final responseBody = json.decode(response.body) as Map<String, dynamic>;
if (response.statusCode == 400 || responseBody["success"] == false) {
final List<dynamic> errorsList = responseBody['errors'] as List? ?? [];
final error = errorsList.isNotEmpty
? (errorsList[0]['msg'] as String?) ?? responseBody.toString()
: responseBody.toString();
ExchangeProviderLogger.logError(
provider: description,
function: 'createTrade',
error: TradeNotCreatedException(description, description: error),
stackTrace: StackTrace.current,
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'body': body,
'url': uri.toString(),
},
);
throw TradeNotCreatedException(description, description: error);
}
if (response.statusCode != 200) {
ExchangeProviderLogger.logError(
provider: description,
function: 'createTrade',
error: Exception('Unexpected http status: ${response.statusCode}'),
stackTrace: StackTrace.current,
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'body': body,
'url': uri.toString(),
},
);
throw Exception('Unexpected http status: ${response.statusCode}');
}
final responseData = responseBody['data'] as Map<String, dynamic>;
final receiveAmount = responseData["amount_receive"]?.toString();
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'createTrade',
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'body': body,
'url': uri.toString(),
},
responseData: {
'id': responseData["order_id"] as String,
'inputAddress': responseData["server_address"] as String,
'receiveAmount': receiveAmount,
'statusCode': response.statusCode,
'responseBody': responseBody,
},
);
return Trade(
id: responseData["order_id"] as String,
inputAddress: responseData["server_address"] as String,
amount: request.fromAmount,
receiveAmount: receiveAmount ?? request.toAmount,
from: request.fromCurrency,
to: request.toCurrency,
provider: description,
createdAt: DateTime.now(),
state: TradeState.created,
payoutAddress: request.toAddress,
isSendAll: isSendAll,
);
} catch (e, s) {
ExchangeProviderLogger.logError(
provider: description,
function: 'createTrade',
error: e,
stackTrace: s,
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
},
);
printV("error creating trade: ${e.toString()}");
throw TradeNotCreatedException(description, description: e.toString());
}
}
@override
Future<Trade> findTradeById({required String id}) async {
try {
final params = <String, dynamic>{};
var body = <String, dynamic>{
'order_id': id,
};
final uri = Uri.https(apiAuthority, order, params);
final response = await ProxyWrapper().post(
clearnetUri: uri,
body: json.encode(body),
headers: _headers,
);
final responseBody = json.decode(response.body) as Map<String, dynamic>;
if (response.statusCode == 400 || responseBody["success"] == false) {
final error = responseBody['errors'][0]['msg'] as String;
throw TradeNotCreatedException(description, description: error);
}
if (response.statusCode != 200)
throw Exception('Unexpected http status: ${response.statusCode}');
final responseData = responseBody['data'] as Map<String, dynamic>;
final fromCurrency = responseData['coin_send'] as String;
final from = CryptoCurrency.safeParseCurrencyFromString(fromCurrency);
final toCurrency = responseData['coin_receive'] as String;
final to = CryptoCurrency.safeParseCurrencyFromString(toCurrency);
final inputAddress = responseData['server_address'] as String;
final payoutAddress = responseData['recipient'] as String;
final status = responseData['status'] as String;
final state = TradeState.deserialize(raw: status);
final response_id = responseData['order_id'] as String;
final expectedSendAmount = responseData['amount_send'] as String;
final expectedReceiveAmount = responseData['amount_receive'] as String;
final memo = responseData['memo'] as String?;
final createdAt = responseData['created_at'] as String?;
return Trade(
id: response_id,
from: from,
to: to,
provider: description,
inputAddress: inputAddress,
amount: expectedSendAmount,
payoutAddress: payoutAddress,
state: state,
receiveAmount: expectedReceiveAmount,
memo: memo,
createdAt: DateTime.tryParse(createdAt ?? ''),
);
} catch (e) {
printV("error getting trade: ${e.toString()}");
throw TradeNotFoundException(
id,
provider: description,
description: e.toString(),
);
}
}
String _normalizeCurrency(CryptoCurrency currency) {
switch (currency) {
default:
return currency.title.toUpperCase();
}
}
String _networkFor(CryptoCurrency currency) {
final network = switch (currency) {
CryptoCurrency.eth => 'ETH',
CryptoCurrency.bnb => 'BNB_BSC',
CryptoCurrency.usdterc20 => 'USDT_ERC20',
CryptoCurrency.usdttrc20 => 'TRX_USDT_S2UZ',
CryptoCurrency.usdtbsc => 'USDT_BSC',
CryptoCurrency.sol => 'SOL',
CryptoCurrency.btc => 'BTC',
CryptoCurrency.xmr => 'XMR',
CryptoCurrency.ltc => 'LTC',
CryptoCurrency.ada => 'ADA',
CryptoCurrency.bch => 'BCH',
CryptoCurrency.zec => 'ZEC',
_ => currency.title.toUpperCase(),
};
return network;
}
}
@@ -1,349 +0,0 @@
import 'dart:convert';
import 'package:hash_wallet/exchange/exchange_provider_description.dart';
import 'package:hash_wallet/exchange/limits.dart';
import 'package:hash_wallet/exchange/provider/exchange_provider.dart';
import 'package:hash_wallet/exchange/trade.dart';
import 'package:hash_wallet/exchange/trade_request.dart';
import 'package:hash_wallet/exchange/trade_state.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:hash_wallet/utils/exchange_provider_logger.dart';
class ThorChainExchangeProvider extends ExchangeProvider {
ThorChainExchangeProvider();
static final isRefundAddressSupported = [CryptoCurrency.eth];
static const _baseNodeURL = 'thornode.ninerealms.com';
static const _baseURL = 'midgard.ninerealms.com';
static const _quotePath = '/thorchain/quote/swap';
static const _txInfoPath = '/thorchain/tx/status/';
static const _affiliateName = 'cakewallet';
static const _affiliateBps = '175';
static const _nameLookUpPath = 'v2/thorname/lookup/';
@override
String get title => 'THORChain';
@override
bool get isAvailable => true;
@override
bool get isEnabled => true;
@override
bool get supportsFixedRate => false;
@override
ExchangeProviderDescription get description => ExchangeProviderDescription.thorChain;
@override
Future<bool> checkIsAvailable() async => true;
@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 params = {
'from_asset': _normalizeCurrency(from),
'to_asset': _normalizeCurrency(to),
'amount': _doubleToThorChainString(amount),
'affiliate': _affiliateName,
'affiliate_bps': _affiliateBps
};
final responseJSON = await _getSwapQuote(params);
final expectedAmountOut = responseJSON['expected_amount_out'] as String? ?? '0.0';
final rate = _thorChainAmountToDouble(expectedAmountOut) / amount;
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'fetchRate',
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
'params': params,
},
responseData: {
'expectedAmountOut': expectedAmountOut,
'rate': rate,
'responseJSON': responseJSON,
},
);
return rate;
} catch (e, s) {
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
error: e,
stackTrace: s,
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
},
);
printV(e.toString());
return 0.0;
}
}
@override
Future<Limits?> fetchLimits(
{required CryptoCurrency from,
required CryptoCurrency to,
required bool isFixedRateMode}) async {
final params = {
'from_asset': _normalizeCurrency(from),
'to_asset': _normalizeCurrency(to),
'amount': _doubleToThorChainString(1),
'affiliate': _affiliateName,
'affiliate_bps': _affiliateBps
};
final responseJSON = await _getSwapQuote(params);
final minAmountIn = responseJSON['recommended_min_amount_in'] as String? ?? '0.0';
return Limits(min: _thorChainAmountToDouble(minAmountIn));
}
@override
Future<Trade> createTrade({
required TradeRequest request,
required bool isFixedRateMode,
required bool isSendAll,
}) async {
final formattedFromAmount = double.parse(request.fromAmount);
final params = {
'from_asset': _normalizeCurrency(request.fromCurrency),
'to_asset': _normalizeCurrency(request.toCurrency),
'amount': _doubleToThorChainString(formattedFromAmount),
'destination': _normalizeAddress(request.toAddress),
'affiliate': _affiliateName,
'affiliate_bps': _affiliateBps,
'refund_address':
isRefundAddressSupported.contains(request.fromCurrency) ? _normalizeAddress(request.refundAddress) : '',
};
final responseJSON = await _getSwapQuote(params);
final inputAddress = responseJSON['inbound_address'] as String?;
final memo = responseJSON['memo'] as String?;
final directAmountOutResponse = responseJSON['expected_amount_out'] as String?;
String? receiveAmount;
if (directAmountOutResponse != null) {
receiveAmount = _thorChainAmountToDouble(directAmountOutResponse).toString();
}
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'createTrade',
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'params': params,
},
responseData: {
'inputAddress': inputAddress,
'memo': memo,
'directAmountOutResponse': directAmountOutResponse,
'receiveAmount': receiveAmount,
'responseJSON': responseJSON,
},
);
return Trade(
id: '',
from: request.fromCurrency,
to: request.toCurrency,
provider: description,
inputAddress: inputAddress,
createdAt: DateTime.now(),
amount: request.fromAmount,
receiveAmount: receiveAmount ?? request.toAmount,
state: TradeState.notFound,
payoutAddress: request.toAddress,
memo: memo,
isSendAll: isSendAll,
);
}
@override
Future<Trade> findTradeById({required String id}) async {
if (id.isEmpty) throw Exception('Trade id is empty');
final formattedId = id.startsWith('0x') ? id.substring(2) : id;
final uri = Uri.https(_baseNodeURL, '$_txInfoPath$formattedId');
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode == 404) {
throw Exception('Trade not found for id: $formattedId');
} else if (response.statusCode != 200) {
throw Exception('Unexpected HTTP status: ${response.statusCode}');
}
final responseJSON = json.decode(response.body);
final Map<String, dynamic> stagesJson = responseJSON['stages'] as Map<String, dynamic>;
final inboundObservedStarted = stagesJson['inbound_observed']?['started'] as bool? ?? true;
if (!inboundObservedStarted) {
throw Exception('Trade has not started for id: $formattedId');
}
final currentState = _updateStateBasedOnStages(stagesJson) ?? TradeState.notFound;
final tx = responseJSON['tx'];
final String fromAddress = tx['from_address'] as String? ?? '';
final String toAddress = tx['to_address'] as String? ?? '';
final List<dynamic> coins = tx['coins'] as List<dynamic>;
final String? memo = tx['memo'] as String?;
final parts = memo?.split(':') ?? [];
final String toChain = parts.length > 1 ? parts[1].split('.')[0] : '';
final String toAsset = parts.length > 1 && parts[1].split('.').length > 1
? parts[1].split('.')[1].split('-')[0]
: '';
final formattedToChain = CryptoCurrency.safeParseCurrencyFromString(toChain);
final toAssetWithChain = CryptoCurrency.safeParseCurrencyFromString(toAsset, walletCurrency: formattedToChain);
final plannedOutTxs = responseJSON['planned_out_txs'] as List<dynamic>?;
final isRefund = plannedOutTxs?.any((tx) => tx['refund'] == true) ?? false;
return Trade(
id: id,
from: CryptoCurrency.fromString(tx['chain'] as String? ?? ''),
to: toAssetWithChain,
provider: description,
inputAddress: fromAddress,
payoutAddress: toAddress,
amount: coins.first['amount'] as String? ?? '0.0',
state: currentState,
memo: memo,
isRefund: isRefund,
);
}
static Future<Map<String, String>?>? lookupAddressByName(String name) async {
final uri = Uri.https(_baseURL, '$_nameLookUpPath$name');
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode != 200) {
return null;
}
final body = json.decode(response.body) as Map<String, dynamic>;
final entries = body['entries'] as List<dynamic>?;
if (entries == null || entries.isEmpty) {
return null;
}
Map<String, String> chainToAddressMap = {};
for (final entry in entries) {
final chain = entry['chain'] as String;
final address = entry['address'] as String;
chainToAddressMap[chain] = address;
}
return chainToAddressMap;
}
Future<Map<String, dynamic>> _getSwapQuote(Map<String, String> params) async {
Uri uri = Uri.https(_baseNodeURL, _quotePath, params);
final response = await ProxyWrapper().get(clearnetUri: uri);
if (response.statusCode != 200) {
ExchangeProviderLogger.logError(
provider: description,
function: '_getSwapQuote',
error: Exception('Unexpected HTTP status: ${response.statusCode}'),
stackTrace: StackTrace.current,
requestData: {
'params': params,
'url': uri.toString(),
},
);
throw Exception('Unexpected HTTP status: ${response.statusCode}');
}
if (response.body.contains('error')) {
ExchangeProviderLogger.logError(
provider: description,
function: '_getSwapQuote',
error: Exception('Unexpected response: ${response.body}'),
stackTrace: StackTrace.current,
requestData: {
'params': params,
'url': uri.toString(),
},
);
throw Exception('Unexpected response: ${response.body}');
}
return json.decode(response.body) as Map<String, dynamic>;
}
String _normalizeCurrency(CryptoCurrency currency) {
final networkTitle = currency.tag == 'ETH' ? 'ETH' : currency.tag ?? currency.title;
return '$networkTitle.${currency.title}';
}
String _doubleToThorChainString(double amount) => (amount * 1e8).toInt().toString();
double _thorChainAmountToDouble(String amount) => double.parse(amount) / 1e8;
TradeState? _updateStateBasedOnStages(Map<String, dynamic> stages) {
TradeState? currentState;
if (stages['inbound_observed']['completed'] as bool? ?? false) {
currentState = TradeState.confirmation;
}
if (stages['inbound_confirmation_counted']['completed'] as bool? ?? false) {
currentState = TradeState.confirmed;
}
if (stages['inbound_finalised']['completed'] as bool? ?? false) {
currentState = TradeState.processing;
}
if (stages['swap_finalised']['completed'] as bool? ?? false) {
currentState = TradeState.traded;
}
if (stages['outbound_signed']['completed'] as bool? ?? false) {
currentState = TradeState.success;
}
return currentState;
}
String _normalizeAddress(String address) =>
address.startsWith('bitcoincash:') ? address.replaceFirst('bitcoincash:', '') : address;
}
@@ -1,565 +0,0 @@
import 'dart:convert';
import 'package:hash_wallet/exchange/exchange_provider_description.dart';
import 'package:hash_wallet/exchange/limits.dart';
import 'package:hash_wallet/exchange/provider/exchange_provider.dart';
import 'package:hash_wallet/exchange/trade.dart';
import 'package:hash_wallet/exchange/trade_not_created_exception.dart';
import 'package:hash_wallet/exchange/trade_request.dart';
import 'package:hash_wallet/exchange/trade_state.dart';
import 'package:hash_wallet/utils/package_info.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:hash_wallet/utils/exchange_provider_logger.dart';
class XOSwapExchangeProvider extends ExchangeProvider {
XOSwapExchangeProvider() {
_addAppVersionHeader();
}
void _addAppVersionHeader() async {
final packageInfo = await PackageInfo.fromPlatform();
final currentVersion = packageInfo.version;
_headers['App-Version'] = currentVersion;
}
static const _apiAuthority = 'exchange.exodus.io';
static const _apiPath = '/v3';
static const _pairsPath = '/pairs';
static const _ratePath = '/rates';
static const _orders = '/orders';
static const _assets = '/assets';
static final _headers = {'Content-Type': 'application/json', 'App-Name': 'cake-labs'};
final _networks = <String, String>{
'POL': 'matic',
'ETH': 'ethereum',
'BTC': 'bitcoin',
'BSC': 'bsc',
'SOL': 'solana',
'TRX': 'tronmainnet',
'ZEC': 'zcash',
'ADA': 'cardano',
'DOGE': 'dogecoin',
'XMR': 'monero',
'BCH': 'bcash',
'BSV': 'bitcoinsv',
'XRP': 'ripple',
'LTC': 'litecoin',
'EOS': 'eosio',
'XLM': 'stellar',
'BASE': 'basemainnet',
'ARB': 'arbitrum',
};
static const supportedTags = [
'POL',
'ETH',
'BTC',
'BSC',
'SOL',
'TRX',
'ZEC',
'ADA',
'DOGE',
'XMR',
'BCH',
'BSV',
'XRP',
'LTC',
'EOS',
'XLM',
'BASE',
'ARB',
];
String _normalizeXOSwapsNetwork(String string) {
final lower = string.toLowerCase();
if (lower.endsWith('matic0a883d9b')) return string.replaceFirst(RegExp(r'matic0a883d9b$', caseSensitive: false), 'POL');
if (lower.endsWith('matic86e249c1')) return string.replaceFirst(RegExp(r'matic86e249c1$', caseSensitive: false), 'POL');
if (lower.endsWith('bscddedf0f8')) return string.replaceFirst(RegExp(r'bscddedf0f8$', caseSensitive: false), 'BSC');
if (lower.endsWith('basemainnetb5a52617')) return string.replaceFirst(RegExp(r'basemainnetb5a52617$', caseSensitive: false), 'BASE');
return string;
}
@override
String get title => 'XOSwap';
@override
bool get isAvailable => true;
@override
bool get isEnabled => true;
@override
bool get supportsFixedRate => true;
@override
ExchangeProviderDescription get description => ExchangeProviderDescription.xoSwap;
@override
Future<bool> checkIsAvailable() async => true;
Future<String?> _getAssets(CryptoCurrency currency) async {
if (currency.tag == null) return currency.title;
try {
final normalizedNetwork = _networks[currency.tag];
if (normalizedNetwork == null) return null;
final uri = Uri.https(_apiAuthority, _apiPath + _assets,
{'networks': normalizedNetwork, 'query': currency.title});
final response = await ProxyWrapper().get(clearnetUri: uri, headers: _headers);
if (response.statusCode != 200) {
throw Exception('Failed to fetch assets for ${currency.title} on ${currency.tag}');
}
final decoded = jsonDecode(response.body);
if (decoded is! List) throw const FormatException('Unexpected response format');
final assets = decoded.map((e) => Map<String, dynamic>.from(e as Map)).toList();
final asset = assets.firstWhere(
(asset) => removeNonAlphanumeric((asset['symbol'] ?? '').toString()) == currency.title,
orElse: () => const {},
);
return asset.isEmpty ? null : asset['id'] as String;
} catch (e) {
printV(e.toString());
return null;
}
}
String removeNonAlphanumeric(String str) => str.toUpperCase().replaceAll(RegExp(r'[^A-Z0-9]'), '');
Future<List<dynamic>> getRatesForPair({
required CryptoCurrency from,
required CryptoCurrency to,
}) async {
try {
final curFrom = await _getAssets(from);
final curTo = await _getAssets(to);
if (curFrom == null || curTo == null) return [];
final pairId = curFrom + '_' + curTo;
final uri = Uri.https(_apiAuthority, '$_apiPath$_pairsPath/$pairId$_ratePath');
final response = await ProxyWrapper().get(clearnetUri: uri, headers: _headers);
if (response.statusCode != 200) return [];
return json.decode(response.body) as List<dynamic>;
} catch (e) {
printV(e.toString());
return [];
}
}
Future<Limits?> fetchLimits({
required CryptoCurrency from,
required CryptoCurrency to,
required bool isFixedRateMode,
}) async {
try {
final rates = await getRatesForPair(from: from, to: to);
if (rates.isEmpty) throw Exception('No rates found for $from to $to');
double minLimit = double.infinity;
double maxLimit = 0;
for (var rate in rates) {
final double currentMin = double.parse(rate['min']['value'].toString());
final double currentMax = double.parse(rate['max']['value'].toString());
if (currentMin < minLimit) minLimit = currentMin;
if (currentMax > maxLimit) maxLimit = currentMax;
}
return Limits(min: minLimit, max: maxLimit);
} catch (e) {
printV(e.toString());
throw Exception('StealthEx failed to fetch limits');
}
}
@override
Future<double> fetchRate({
required CryptoCurrency from,
required CryptoCurrency to,
required double amount,
required bool isFixedRateMode,
required bool isReceiveAmount
}) async {
try {
final rates = await getRatesForPair(from: from, to: to);
if (rates.isEmpty) {
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
error: Exception('No rates found for $from to $to'),
stackTrace: StackTrace.current,
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
},
);
return 0;
}
double result;
if (!isFixedRateMode) {
double bestOutput = 0.0;
for (var rate in rates) {
final double minVal = double.parse(rate['min']['value'].toString());
final double maxVal = double.parse(rate['max']['value'].toString());
if (amount >= minVal && amount <= maxVal) {
final double rateMultiplier = double.parse(rate['amount']['value'].toString());
final double minerFee = double.parse(rate['minerFee']['value'].toString());
final double outputAmount = (amount * rateMultiplier) - minerFee;
if (outputAmount > bestOutput) {
bestOutput = outputAmount;
}
}
}
result = bestOutput > 0 ? (bestOutput / amount) : 0;
} else {
double bestInput = double.infinity;
for (var rate in rates) {
final double rateMultiplier = double.parse(rate['amount']['value'].toString());
final double minerFee = double.parse(rate['minerFee']['value'].toString());
final double minVal = double.parse(rate['min']['value'].toString());
final double maxVal = double.parse(rate['max']['value'].toString());
final double requiredSend = (amount + minerFee) / rateMultiplier;
if (requiredSend >= minVal && requiredSend <= maxVal) {
if (requiredSend < bestInput) {
bestInput = requiredSend;
}
}
}
result = bestInput < double.infinity ? amount / bestInput : 0;
}
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'fetchRate',
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
},
responseData: {
'result': result,
'ratesCount': rates.length,
'rates': rates,
},
);
return result;
} catch (e, s) {
ExchangeProviderLogger.logError(
provider: description,
function: 'fetchRate',
error: e,
stackTrace: s,
requestData: {
'from': from.title,
'to': to.title,
'amount': amount,
'isFixedRateMode': isFixedRateMode,
'isReceiveAmount': isReceiveAmount,
},
);
printV(e.toString());
return 0;
}
}
@override
Future<Trade> createTrade({
required TradeRequest request,
required bool isFixedRateMode,
required bool isSendAll,
}) async {
try {
final uri = Uri.https(_apiAuthority, '$_apiPath$_orders');
final curFrom = await _getAssets(request.fromCurrency);
final curTo = await _getAssets(request.toCurrency);
if (curFrom == null || curTo == null) {
ExchangeProviderLogger.logError(
provider: description,
function: 'createTrade',
error: TradeNotCreatedException(description),
stackTrace: StackTrace.current,
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'curFrom': curFrom,
'curTo': curTo,
},
);
throw TradeNotCreatedException(description);
}
final pairId = curFrom + '_' + curTo;
final payload = {
'fromAmount': request.fromAmount,
'fromAddress': request.refundAddress,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'pairId': pairId,
};
final response = await ProxyWrapper().post(
clearnetUri: uri,
headers: _headers,
body: json.encode(payload),
);
if (response.statusCode != 201) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['error'] ?? 'Unknown error';
final message = responseJSON['message'] ?? '';
ExchangeProviderLogger.logError(
provider: description,
function: 'createTrade',
error: Exception('$error\n$message'),
stackTrace: StackTrace.current,
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'payload': payload,
'url': uri.toString(),
},
);
throw Exception('$error\n$message');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final amount = responseJSON['amount'] as Map<String, dynamic>;
final toAmount = responseJSON['toAmount'] as Map<String, dynamic>;
final orderId = responseJSON['id'] as String;
final from = request.fromCurrency;
final to = request.toCurrency;
final payoutAddress = responseJSON['toAddress'] as String;
final depositAddress = responseJSON['payInAddress'] as String;
final refundAddress = responseJSON['fromAddress'] as String;
final depositAmountStr = amount['value'].toString();
final parsedAmount = double.tryParse(depositAmountStr);
if (parsedAmount == null || parsedAmount <= 0) {
throw Exception('Invalid deposit amount received from API');
}
final receiveAmount = toAmount['value'] as String;
final status = responseJSON['status'] as String;
final createdAtString = responseJSON['createdAt'] as String;
final extraId = responseJSON['payInAddressTag'] as String?;
final createdAt = DateTime.parse(createdAtString).toLocal();
ExchangeProviderLogger.logSuccess(
provider: description,
function: 'createTrade',
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
'payload': payload,
'url': uri.toString(),
},
responseData: {
'orderId': orderId,
'depositAddress': depositAddress,
'payoutAddress': payoutAddress,
'refundAddress': refundAddress,
'depositAmount': depositAmountStr,
'receiveAmount': receiveAmount,
'status': status,
'createdAt': createdAtString,
'extraId': extraId,
'statusCode': response.statusCode,
'responseJSON': responseJSON,
},
);
return Trade(
id: orderId,
from: from,
to: to,
provider: description,
inputAddress: depositAddress,
refundAddress: refundAddress,
state: TradeState.deserialize(raw: status),
createdAt: createdAt,
amount: depositAmountStr,
receiveAmount: receiveAmount.toString(),
payoutAddress: payoutAddress,
extraId: extraId,
isSendAll: isSendAll,
);
} catch (e, s) {
ExchangeProviderLogger.logError(
provider: description,
function: 'createTrade',
error: e,
stackTrace: s,
requestData: {
'from': request.fromCurrency.title,
'to': request.toCurrency.title,
'fromAmount': request.fromAmount,
'toAmount': request.toAmount,
'toAddress': request.toAddress,
'refundAddress': request.refundAddress,
'isFixedRateMode': isFixedRateMode,
'isSendAll': isSendAll,
},
);
printV(e.toString());
throw TradeNotCreatedException(description);
}
}
@override
Future<Trade> findTradeById({required String id}) async {
try {
final uri = Uri.https(_apiAuthority, '$_apiPath$_orders/$id');
final response = await ProxyWrapper().get(clearnetUri: uri, headers: _headers);
if (response.statusCode != 200) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
if (responseJSON.containsKey('code') && responseJSON['code'] == 'NOT_FOUND') {
throw Exception('Trade not found');
}
final error = responseJSON['error'] ?? 'Unknown error';
final message = responseJSON['message'] ?? responseJSON['details'] ?? '';
throw Exception('$error\n$message');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final pairId = responseJSON['pairId'] as String;
final pairParts = pairId.split('_');
final fromAsset = pairParts.isNotEmpty ? pairParts[0] : '';
final normalizedFromAsset = _normalizeXOSwapsNetwork(fromAsset);
String? fromAssetTag = _extractTagFromAsset(normalizedFromAsset);
String fromAssetBase = fromAssetTag != null
? normalizedFromAsset.substring(0, normalizedFromAsset.length - fromAssetTag.length)
: normalizedFromAsset;
// Special case for USDT defaulting to ETH tag
if (fromAssetBase == 'USDT' && fromAssetTag == null) {
fromAssetTag = 'ETH';
}
// Special case for BASE defaulting to BASE tag
if (fromAssetBase == 'BASE' && fromAssetTag == null) {
fromAssetTag = 'BASE';
fromAssetBase = 'ETH';
}
final toAsset = pairParts.length > 1 ? pairParts[1] : '';
final normalizedToAsset = _normalizeXOSwapsNetwork(toAsset);
String? toAssetTag = _extractTagFromAsset(normalizedToAsset);
String toAssetBase = toAssetTag != null
? normalizedToAsset.substring(0, normalizedToAsset.length - toAssetTag.length)
: normalizedToAsset;
// Special case for USDT defaulting to ETH tag
if (toAssetBase == 'USDT' && toAssetTag == null) {
toAssetTag = 'ETH';
}
// Special case for BASE defaulting to BASE tag
if (toAssetBase == 'BASE' && toAssetTag == null) {
toAssetTag = 'ETH';
toAssetBase = 'BASE';
}
final fromCurrency = CryptoCurrency.safeParseCurrencyFromString(fromAssetBase,tag: fromAssetTag);
final toCurrency = CryptoCurrency.safeParseCurrencyFromString(toAssetBase,tag: toAssetTag);
final amount = responseJSON['amount'] as Map<String, dynamic>;
final toAmount = responseJSON['toAmount'] as Map<String, dynamic>;
final orderId = responseJSON['id'] as String;
final depositAmountStr = amount['value'].toString();
final parsedAmount = double.tryParse(depositAmountStr);
if (parsedAmount == null || parsedAmount <= 0) {
throw Exception('Invalid deposit amount received from API');
}
final receiveAmount = toAmount['value'] as String;
final depositAddress = responseJSON['payInAddress'] as String;
final payoutAddress = responseJSON['toAddress'] as String;
final refundAddress = responseJSON['fromAddress'] as String;
final status = responseJSON['status'] as String;
final createdAtString = responseJSON['createdAt'] as String;
final createdAt = DateTime.parse(createdAtString).toLocal();
final extraId = responseJSON['payInAddressTag'] as String?;
return Trade(
id: orderId,
from: fromCurrency,
to: toCurrency,
provider: description,
inputAddress: depositAddress,
refundAddress: refundAddress,
state: TradeState.deserialize(raw: status),
createdAt: createdAt,
amount: depositAmountStr,
receiveAmount: receiveAmount,
payoutAddress: payoutAddress,
extraId: extraId,
);
} catch (e) {
printV(e.toString());
throw TradeNotCreatedException(description);
}
}
// ensure something remains before tag (at least 2 chars)
String? _extractTagFromAsset(String asset) {
for (final tag in supportedTags) {
if (asset.endsWith(tag)) {
final prefixLength = asset.length - tag.length;
if (prefixLength >= 2) {
return tag;
}
}
}
return null;
}
}