Refactor swap logic and state management (#3472)
What changed, and why it matters
This is a very large code refactor of the cryptocurrency swap/exchange feature in Cake Wallet. It rewrites how exchange rates are fetched, how trades are created and tracked, and how trade history is stored in the local database. The commit also adds many unit tests and fixes numerous small bugs in individual exchange providers. While the changes touch security-sensitive areas (sending money, storing trade data, parsing amounts), the commit message and diff do not describe this as a security patch, and there is no explicit disclosure of a vulnerability. The biggest security-relevant change is a database migration that restructures how past trades are stored; a bug here could affect user records but is not shown to be exploitable by an attacker.
Treat this as a high-risk functional refactor rather than a confirmed security fix. Reviewers should focus on: (1) correctness of the SQLite trade migration and data loss potential; (2) accuracy of Money.safeParse and ExchangeRate.fromAmounts to prevent amount manipulation; (3) that each exchange provider still sends the intended API requests and validates responses; (4) that the new SwapBloc correctly gates external sends, refund addresses, and hardware-wallet confirmations; (5) that the CI change allowing http imports in tool/ and test/ does not weaken production code checks. Regression testing of swap creation, rate display, and trade history is strongly advised before release.
Security signals we found
Large-scale rewrite of trade creation, rate fetching, and status monitoring
Database schema migration for Trade table with data reconstruction from old columns
New amount parsing helper (Money.safeParse) and exchange-rate math (ExchangeRate.fromAmounts)
Multiple provider-specific fixes for request/response handling (swaptrade, swapsxyz, trocador, changenow, etc.)
Removal of old ExchangeViewModel/ExchangeTradeViewModel and replacement with SwapBloc/RateCubit
Changes to Thorchain address lookup and LNURL pay address provider logic
Addition of hardware wallet confirmation popup in swap flow
External send/refund address handling added for internal swaps
CI workflow change allowing http imports in tool/ and test/ directories
Evidence from the diff
The commit refactors the swap stack from MobX view models to a BLoC/Cubit architecture, introduces new Money/ExchangeRate primitives with safeParse and fromAmounts helpers, adds per-provider API schemas and JSON converters, rewrites Trade/TradeRequest/TradeState models, and migrates the SQLite Trade table from an auto-increment primary key to a TEXT tradeId primary key. It also moves several exchange providers into sub-packages, adds a provider registry, rate cubit, swap bloc, trade creator, transaction service, and many widget updates. Security-relevant code paths include amount parsing, address resolution, trade creation, external send URI handling, refund addresses, and database serialization/deserialization. The diff shows many bug-fix commits squashed together, including comments such as ‘apparently we sent the wrong request to swaptrade and nobody noticed for years’ and ‘fix extremely embarassing swapsxyz bug’, indicating prior incorrect provider behavior is being corrected, but no CVE or advisory is referenced.
Changed components
lib/exchange/provider/* (all exchange provider implementations)lib/new-ui/viewmodels/swap/bloc/swap_bloc.dartlib/new-ui/viewmodels/swap/rates/rate_cubit.dartlib/new-ui/viewmodels/swap/trade_creator.dartlib/new-ui/services/transaction_service.dartlib/exchange/trade.dartlib/exchange/trade_request.dartlib/exchange/rate_request.dartcw_core/lib/amount/money.dartcw_core/lib/amount/exchange_rate.dartcw_core/lib/db/sqlite.dartcw_core/lib/db/trade_migration.dartlib/core/trade_monitor.dartlib/di.dart.github/workflows/no_http_imports.yamlInspect captured patch +26666 / −15194
### .github/workflows/no_http_imports.yaml
@@ -14,7 +14,7 @@ jobs:
- name: Check for http package usage
if: github.event_name == 'pull_request'
run: |
- GIT_GREP_OUT="$(git grep package:http | (grep .dart: || test $? = 1) | (grep -v proxy_wrapper.dart || test $? = 1) | (grep -v very_insecure_http_do_not_use || test $? = 1) | (grep -v '^cw_custom_lints/' || test $? = 1) || true)"
+ GIT_GREP_OUT="$(git grep package:http | (grep .dart: || test $? = 1) | (grep -v proxy_wrapper.dart || test $? = 1) | (grep -v very_insecure_http_do_not_use || test $? = 1) | (grep -v '^cw_custom_lints/' || test $? = 1) | (grep -v '^tool/' || test $? = 1) | (grep -v -E '^([^/]+/)?test/' || test $? = 1) || true)"
[[ "x$GIT_GREP_OUT" == "x" ]] && exit 0
echo "$GIT_GREP_OUT"
echo "There are .dart files which use http imports"
### analysis_options.yaml
@@ -18,9 +18,9 @@ analyzer:
strict-casts: true
strict-raw-types: true
-plugins:
- cw_custom_lints:
- path: cw_custom_lints
+#plugins:
+# cw_custom_lints:
+# path: cw_custom_lints
linter:
rules:
### cw_core/lib/amount/exchange_rate.dart
@@ -1,9 +1,27 @@
-import 'package:cw_core/amount/money.dart';
-import 'package:cw_core/currency.dart';
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/currency.dart";
+
+class ExchangeRate implements Comparable<ExchangeRate> {
-class ExchangeRate {
const ExchangeRate({required this.base, required this.quote});
+ factory ExchangeRate.fromAmounts(Money from, Money to) {
+ if (from.isZero) {
+ throw ArgumentError(
+ "from has a zero amount, cannot create exchange rate",
+ );
+ }
+
+ final quote = Money(
+ to.amount * BigInt.from(10).pow(2 * from.decimals),
+ to.currency,
+ from.decimals + to.decimals,
+ ) /
+ from.amount;
+
+ return ExchangeRate(base: from.currency, quote: quote);
+ }
+
/// The currency being priced (e.g. BTC in a BTC/USD pair).
final Currency base;
@@ -27,13 +45,12 @@ class ExchangeRate {
return quote.isZero
? Money.zero(quote.currency)
- : Money(amount.amount * quote.amount ~/ scale, quote.currency, quote.decimals);
+ : Money(amount.amount * quote.amount ~/ scale, quote.currency, quote.decimals)
+ .copyWith(currency: quote.currency);
}
if (amount.currency == quote.currency) {
- if (quote.isZero) {
- return Money.zero(base);
- }
+ if (quote.isZero) return Money.zero(base);
final numerator = amount.amount * BigInt.from(10).pow(base.decimals + quote.decimals);
final denominator = quote.amount * BigInt.from(10).pow(amount.decimals);
@@ -42,7 +59,21 @@ class ExchangeRate {
}
throw ArgumentError(
- "Unable to convert ${amount.currency.symbol} in ${base.symbol}/${quote.currency.symbol} pair",
- );
+ "Unable to convert ${amount.currency.symbol} in ${base.symbol}/${quote.currency.symbol} pair",);
+ }
+
+ @override
+ int compareTo(ExchangeRate other) {
+
+ if(other.base != base) {
+ throw ArgumentError("cannot compare rates for different base currencies");
+ }
+
+ if(other.quote.currency != quote.currency) {
+ throw ArgumentError("cannot compare rates for different quote currencies");
+ }
+
+
+ return quote.compareTo(other.quote);
}
}
### cw_core/lib/amount/money.dart
@@ -36,7 +36,15 @@ class Money implements Comparable<Money> {
return Money(amount, currency, decimals);
}
- /// Parse the [source] and turn it into [Money] if possible trimming trailing 0s
+ factory Money.safeParse(source, Currency currency, {bool isBaseUnit = false}) {
+ final amount = isBaseUnit
+ ? BigInt.parse(source.toString())
+ : parseFixed(source.toString().withDecimals(currency.decimals), currency.decimals);
+
+ return Money(amount, currency);
+ }
+
+ /// Parse the [source] and turn it into [Money] if possible
///
/// As [parse] except that this method returns `null` if the input is not
/// valid or if it is a decimal when [isBaseUnit]
@@ -335,4 +343,6 @@ class Money implements Comparable<Money> {
/// new [Money] with absolute value of this instance
Money abs() => copyWith(amount: amount.abs());
+
+ String get serialized => "${currency.serialized}:${amount.toString()}";
}
### cw_core/lib/crypto_currency.dart
@@ -5,6 +5,8 @@ import 'package:cw_core/enumerable_item.dart';
import 'package:collection/collection.dart';
import 'package:cw_core/format_fixed.dart';
+enum MemoLabelType { destinationTag, memo }
+
class CryptoCurrency extends EnumerableItem<int> with Serializable<int> implements Currency {
const CryptoCurrency({
String title = '',
@@ -19,13 +21,15 @@ class CryptoCurrency extends EnumerableItem<int> with Serializable<int> implemen
this.enabled = false,
this.isPotentialScam = false,
this.groups = const {},
+ this.memoLabelType,
}) : super(title: title, raw: raw);
final String? flatIconPath;
final String? chainIconPath;
final bool enabled;
final bool isPotentialScam;
final Set<String> groups;
+ final MemoLabelType? memoLabelType;
@override
final String name;
@@ -234,7 +238,9 @@ class CryptoCurrency extends EnumerableItem<int> with Serializable<int> implemen
raw: 7,
name: 'eos',
iconPath: 'assets/images/eos_icon.png',
- decimals: 4);
+ decimals: 4,
+ memoLabelType: MemoLabelType.memo,
+ );
static const eth = CryptoCurrency(
title: 'ETH',
fullName: 'Ethereum',
@@ -294,14 +300,18 @@ class CryptoCurrency extends EnumerableItem<int> with Serializable<int> implemen
raw: 14,
name: 'xlm',
iconPath: 'assets/images/xlm_icon.png',
- decimals: 7);
+ decimals: 7,
+ memoLabelType: MemoLabelType.memo,
+ );
static const xrp = CryptoCurrency(
title: 'XRP',
fullName: 'Ripple',
raw: 15,
name: 'xrp',
iconPath: 'assets/images/xrp_icon.png',
- decimals: 6);
+ decimals: 6,
+ memoLabelType: MemoLabelType.destinationTag,
+ );
static const xhv = CryptoCurrency(
title: 'XHV',
fullName: 'Haven Protocol',
@@ -392,7 +402,9 @@ class CryptoCurrency extends EnumerableItem<int> with Serializable<int> implemen
raw: 37,
name: 'hbar',
iconPath: 'assets/images/hbar_icon.png',
- decimals: 8);
+ decimals: 8,
+ memoLabelType: MemoLabelType.memo,
+ );
static const sc = CryptoCurrency(
title: 'SC',
fullName: 'Siacoin',
@@ -849,7 +861,9 @@ class CryptoCurrency extends EnumerableItem<int> with Serializable<int> implemen
raw: 95,
name: 'ton',
iconPath: 'assets/new-ui/crypto_full_icons/ton.svg',
- decimals: 8);
+ decimals: 8,
+ memoLabelType: MemoLabelType.memo,
+ );
static const zano = CryptoCurrency(
title: 'ZANO',
tag: 'ZANO',
@@ -1180,4 +1194,7 @@ class CryptoCurrency extends EnumerableItem<int> with Serializable<int> implemen
/// Format the raw amount into its decimal representation eg. turn Sats into Bitcoin
String formatAmount(BigInt amount, {int? fractionalDigits, bool trimZeros = true}) =>
formatFixed(amount, decimals, fractionalDigits: fractionalDigits, trimZeros: trimZeros);
+
+ @override
+ String get serialized => tag == null ? "crypto^$symbol" : "crypto^$symbol^$tag";
}
### cw_core/lib/currencies_with_memo.dart
@@ -1,13 +0,0 @@
-import 'package:cw_core/crypto_currency.dart';
-
-enum MemoLabelType { destinationTag, memo }
-
-const Map<CryptoCurrency, MemoLabelType> _currenciesRequiringMemo = {
- CryptoCurrency.xrp: MemoLabelType.destinationTag,
- CryptoCurrency.xlm: MemoLabelType.memo,
- CryptoCurrency.ton: MemoLabelType.memo,
- CryptoCurrency.eos: MemoLabelType.memo,
- CryptoCurrency.hbar: MemoLabelType.memo,
-};
-
-MemoLabelType? memoLabelTypeFor(CryptoCurrency currency) => _currenciesRequiringMemo[currency];
### cw_core/lib/currency.dart
@@ -1,4 +1,4 @@
-import 'package:cw_core/amount/money.dart';
+import "package:cw_core/amount/money.dart";
abstract class Currency {
String get symbol;
@@ -21,4 +21,6 @@ abstract class Currency {
@override
int get hashCode => decimals.hashCode ^ symbol.hashCode ^ tag.hashCode;
String get apiString;
+
+ String get serialized;
}
### cw_core/lib/db/sqlite.dart
@@ -8,6 +8,13 @@ import "package:cw_core/wallet_type.dart";
import "package:flutter/foundation.dart";
import "package:path/path.dart" as p;
import "package:sqflite_common_ffi/sqflite_ffi.dart";
+import "package:cw_core/db/sqlite_debug.dart";
+import "package:cw_core/db/trade_migration.dart";
+import "package:cw_core/root_dir.dart";
+import "package:cw_core/utils/print_verbose.dart";
+import "package:flutter/foundation.dart";
+import "package:sqflite_common_ffi/sqflite_ffi.dart";
+import "package:path/path.dart" as p;
Database? db;
@@ -71,7 +78,7 @@ Future<void> _initDb({String? pathOverride}) async {
await db?.close();
db = await openDatabase(
dbFile.path,
- version: 15,
+ version: 16,
onUpgrade: (db, oldVersion, newVersion) async {
printV("migrating: $oldVersion, $newVersion");
if (oldVersion <= 1) {
@@ -128,7 +135,7 @@ CREATE TABLE IF NOT EXISTS BalanceCardStyleSettings (
}
if (oldVersion <= 5) {
- await _createTradeTable(db);
+ await _createOldTradeTable(db);
}
if (oldVersion <= 6) {
await _addColumnIfNotExists(
@@ -206,6 +213,9 @@ CREATE TABLE IF NOT EXISTS BalanceCardStyleSettings (
definition: "BOOLEAN DEFAULT FALSE",
);
}
+ if(oldVersion <= 15) {
+ await migrateTradeTableToNewSchema(db);
+ }
},
onCreate: (Database db, int version) async {
await db.execute('''
@@ -306,7 +316,7 @@ CREATE TABLE BalanceCardStyleSettings (
''');
await _createBridgeTransferTable(db);
await _createNodeTable(db);
- await _createTradeTable(db);
+ await createTradeTable(db);
await _createChartsTables(db);
await _createErc20TokenTable(db);
await _createSplTokenTable(db);
@@ -335,7 +345,7 @@ CREATE TABLE ChartsAssets (
""");
}
-Future<void> _createTradeTable(Database db) async {
+Future<void> _createOldTradeTable(Database db) async {
await db.execute("""
CREATE TABLE IF NOT EXISTS Trade (
tradeId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
@@ -398,6 +408,37 @@ ON Trade (id);
""");
}
+
+Future<void> createTradeTable(Database db) async {
+ await db.execute("""
+CREATE TABLE Trade (
+ tradeId TEXT PRIMARY KEY NOT NULL,
+ provider INTEGER,
+ state TEXT,
+ accountIndex INTEGER,
+ depositAmount TEXT,
+ payoutAmount TEXT,
+ fundingAddress TEXT,
+ refundAddress TEXT,
+ payoutAddress TEXT,
+ createdAt INTEGER,
+ expiredAt INTEGER,
+ extraId TEXT,
+ outputTransaction TEXT,
+ walletId TEXT,
+ toAddressExtraId TEXT,
+ password TEXT,
+ providerId TEXT,
+ providerName TEXT,
+ memo TEXT,
+ txId TEXT,
+ isRefund INTEGER,
+ chainId INTEGER,
+ fromWalletAddress TEXT
+);
+""");
+}
+
Future<void> _createWalletInfoAccountTable(Database db) async {
await db.execute("""
CREATE TABLE IF NOT EXISTS WalletInfoAccount (
### cw_core/lib/db/trade_migration.dart
@@ -0,0 +1,81 @@
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/db/sqlite.dart";
+import "package:sqflite/sqflite.dart";
+
+Future<void> migrateTradeTableToNewSchema(Database db) async {
+ await db.execute("ALTER TABLE Trade RENAME TO Trade_old;");
+ await db.execute("DROP INDEX IF EXISTS idx_trade_id_unique;");
+ await createTradeTable(db);
+ final List<Map<String, Object?>> oldTrades = await db.query("Trade_old");
+
+ for (final row in oldTrades) {
+ try {
+ final depositMoney = Money.safeParse(
+ row["amount"] as String? ?? "0",
+ _reconstructCurrency(row, .from),
+ );
+ final payoutMoney = Money.safeParse(
+ row["receiveAmount"] as String? ?? "0",
+ _reconstructCurrency(row, .to),
+ );
+
+ final newRow = {
+ "tradeId": row["id"],
+ "provider": row["providerRaw"] ?? 0,
+ "state": row["stateRaw"] ?? "",
+ "depositAmount": depositMoney.serialized,
+ "payoutAmount": payoutMoney.serialized,
+ "fundingAddress": row["inputAddress"],
+ "refundAddress": row["refundAddress"],
+ "payoutAddress": row["payoutAddress"],
+ "accountIndex": row["fromTitle"] == CryptoCurrency.xmr.title ? -1 : 0,
+ "fromWalletAddress":
+ row["fromTitle"] == CryptoCurrency.xmr.title ? row["fromWalletAddress"] : null,
+ "createdAt": row["createdAt"],
+ "expiredAt": row["expiredAt"],
+ "extraId": row["extraId"],
+ "outputTransaction": row["outputTransaction"],
+ "walletId": row["walletId"],
+ "toAddressExtraId": row["toAddressExtraId"],
+ "password": row["password"],
+ "providerId": row["providerId"],
+ "providerName": row["providerName"],
+ "memo": row["memo"],
+ "txId": row["txId"],
+ "isRefund": row["isRefund"],
+ "chainId": row["chainId"],
+ };
+
+ await db.insert("Trade", newRow, conflictAlgorithm: ConflictAlgorithm.replace);
+ } catch (e) {}
+ }
+}
+
+enum _direction {to, from}
+
+CryptoCurrency _reconstructCurrency(Map<String, dynamic> row, _direction dir) {
+ final prefix = switch(dir) {
+ .to => "to",
+ .from => "from"
+ };
+
+ final title = row["${prefix}Title"] as String?;
+
+ final tag = row["${prefix}Tag"] as String?;
+
+ final live = CryptoCurrency.safeParseCurrencyFromString(title, tag: tag);
+ if (live != null) return live;
+
+ return CryptoCurrency(
+ title: title ?? "",
+ name: row["${prefix}Name"] as String? ?? "",
+ tag: tag,
+ fullName: row["${prefix}FullName"] as String?,
+ decimals: row["${prefix}Decimals"] as int? ?? 1,
+ raw: row["${prefix}Raw"] as int? ?? -1,
+ iconPath: row["${prefix}IconPath"] as String?,
+ flatIconPath: row["${prefix}FlatIconPath"] as String?,
+ chainIconPath: row["${prefix}ChainIconPath"] as String?,
+ );
+}
### cw_core/lib/erc20_token.dart
@@ -193,4 +193,7 @@ class Erc20Token extends CryptoCurrency {
@override
String get apiString => "evm.$contractAddress";
+
+ @override
+ String get serialized => "evm^$contractAddress^$chainId";
}
### cw_core/lib/spl_token.dart
@@ -200,4 +200,7 @@ class SPLToken extends CryptoCurrency {
@override
String get apiString => "sol.$mintAddress";
+
+ @override
+ String get serialized => "sol^$mintAddress";
}
### cw_core/lib/tron_token.dart
@@ -178,4 +178,7 @@ class TronToken extends CryptoCurrency {
@override
String get apiString => "trx.$contractAddress";
+
+ @override
+ String get serialized => "trx^$contractAddress";
}
### cw_core/lib/wallet_info.dart
@@ -855,10 +855,12 @@ class WalletInfo {
);
return List.generate(list.length, (index) => WalletInfo.fromJson(list[index]));
}
-
+
static Future<List<WalletInfo>> getAll() async {
return selectList('', []);
}
+
+ static Future<List<WalletInfo>> getAllForType(WalletType type) => selectList("type = ?", [type.index]);
static Future<WalletInfo?> get(String name, WalletType type) async {
final list = await selectList('name = ? AND type = ?', [name, type.index]);
### cw_core/pubspec.yaml
@@ -5,7 +5,7 @@ publish_to: none
homepage: https://cakewallet.com
environment:
- sdk: '>=3.0.6 <4.0.0'
+ sdk: '>=3.11.0 <4.0.0'
flutter: ">=1.20.0"
dependencies:
### cw_core/test/amount/exchange_rate_test.dart
@@ -33,6 +33,165 @@ void main() {
});
});
+ group('fromAmounts', () {
+ test('derives rate from amounts: 10 BTC for 100 ETH is 1 BTC = 10 ETH', () {
+ final rate = ExchangeRate.fromAmounts(
+ Money.parse('10', CryptoCurrency.btc),
+ Money.parse('100', CryptoCurrency.eth),
+ );
+
+ expect(rate.base, CryptoCurrency.btc);
+ expect(rate.quote, Money.parse('10', CryptoCurrency.eth));
+ });
+
+ test('base currency with 18 decimal places: 2 ETH for 5.000 EUR', () {
+ final rate = ExchangeRate.fromAmounts(
+ Money.parse('2', CryptoCurrency.eth),
+ Money.parse('5000.00', EUR),
+ );
+
+ expect(rate.base, CryptoCurrency.eth);
+ expect(rate.quote, Money.parse('2500.00', EUR));
+ });
+
+ test('fiat base currency: 60.000 EUR for 1 BTC', () {
+ final rate = ExchangeRate.fromAmounts(
+ Money.parse('60000.00', EUR),
+ Money.parse('1', CryptoCurrency.btc),
+ );
+
+ expect(rate.base, EUR);
+ expect(rate.quote, Money.parse('0.0000166667', CryptoCurrency.btc, strictParsing: false));
+ });
+
+ test('same currency on both sides: 2 BTC for 2 BTC is a rate of 1', () {
+ final rate = ExchangeRate.fromAmounts(
+ Money.parse('2', CryptoCurrency.btc),
+ Money.parse('2', CryptoCurrency.btc),
+ );
+
+ expect(rate.quote, Money.parse('1', CryptoCurrency.btc));
+ });
+
+ test('derived rate converts the from amount back into the to amount', () {
+ final from = Money.parse('0.5', CryptoCurrency.btc);
+ final to = Money.parse('30000.00', EUR);
+ final rate = ExchangeRate.fromAmounts(from, to);
+
+ expect(rate.quote, Money.parse('60000.00', EUR));
+ expect(rate.convert(from), to);
+ });
+
+ test('base currency without decimal places: 500 JPY for 5 EUR', () {
+ final rate = ExchangeRate.fromAmounts(
+ Money.fromInt(500, JPY),
+ Money.parse('5.00', EUR),
+ );
+
+ expect(rate.quote, Money.parse('0.01', EUR));
+ });
+
+ test('quote keeps the from decimals on top of the to decimals', () {
+ final roundedDown = ExchangeRate.fromAmounts(
+ Money.parse('3', CryptoCurrency.btc),
+ Money.parse('1.00', EUR),
+ );
+ expect(roundedDown.quote, Money.parse('0.3333333333', EUR, strictParsing: false));
+
+ final belowOneCent = ExchangeRate.fromAmounts(
+ Money.parse('2', CryptoCurrency.btc),
+ Money.parse('0.01', EUR),
+ );
+ expect(belowOneCent.quote, Money.parse('0.005', EUR, strictParsing: false));
+ });
+
+ test('rounding the quote makes the round trip lossy', () {
+ final from = Money.parse('3', CryptoCurrency.btc);
+ final rate = ExchangeRate.fromAmounts(from, Money.parse('1.00', EUR));
+
+ expect(rate.convert(from), Money.parse('0.99', EUR));
+ });
+
+ test('negative amounts keep their sign', () {
+ final negativeTo = ExchangeRate.fromAmounts(
+ Money.parse('4', CryptoCurrency.btc),
+ Money.parse('-200.00', EUR),
+ );
+ expect(negativeTo.quote, Money.parse('-50.00', EUR));
+
+ final negativeBelowOneCent = ExchangeRate.fromAmounts(
+ Money.parse('2', CryptoCurrency.btc),
+ Money.fromInt(-1, EUR),
+ );
+ expect(negativeBelowOneCent.quote, Money.parse('-0.005', EUR, strictParsing: false));
+ });
+
+ test('a rate below one base unit of the quote currency is kept', () {
+ final rate = ExchangeRate.fromAmounts(
+ Money.parse('3', CryptoCurrency.btc),
+ Money.fromInt(1, EUR),
+ );
+
+ expect(rate.quote, Money.parse('0.0033333333', EUR, strictParsing: false));
+ });
+
+ test('low value into high value: SHIB to BTC', () {
+ final from = Money.parse('1000000', CryptoCurrency.shib);
+ final to = Money.parse('0.00012345', CryptoCurrency.btc);
+ final rate = ExchangeRate.fromAmounts(from, to);
+
+ expect(rate.quote.isZero, isFalse);
+ expect(rate.convert(from), to);
+ expect(rate.convert(to), from);
+ });
+
+ test('low value into a stablecoin keeps the cents: SHIB to USDC', () {
+ final from = Money.parse('1000000', CryptoCurrency.shib);
+ final to = Money.parse('12.34', CryptoCurrency.usdc);
+ final rate = ExchangeRate.fromAmounts(from, to);
+
+ expect(rate.convert(from), to);
+ expect(rate.convert(Money.parse('2000000', CryptoCurrency.shib)), Money.parse('24.68', CryptoCurrency.usdc));
+ });
+
+ test('single base unit from amount: 1 sat for 1 EUR', () {
+ final rate = ExchangeRate.fromAmounts(
+ Money(BigInt.one, CryptoCurrency.btc),
+ Money.parse('1.00', EUR),
+ );
+
+ expect(rate.quote, Money.parse('100000000.00', EUR));
+ });
+
+ test('no int overflow with large amounts', () {
+ final rate = ExchangeRate.fromAmounts(
+ Money.parse('21000000', CryptoCurrency.btc),
+ Money.parse('1260000000000.00', EUR),
+ );
+
+ expect(rate.quote, Money.parse('60000.00', EUR));
+ });
+
+ test('zero to amount gives a zero rate', () {
+ final rate = ExchangeRate.fromAmounts(
+ Money.parse('1', CryptoCurrency.btc),
+ Money.zero(EUR),
+ );
+
+ expect(rate.quote, Money.zero(EUR));
+ });
+
+ test('throws on a zero from amount', () {
+ expect(
+ () => ExchangeRate.fromAmounts(
+ Money.zero(CryptoCurrency.btc),
+ Money.parse('1.00', EUR),
+ ),
+ throwsArgumentError,
+ );
+ });
+ });
+
group('Edge Cases', () {
final rate = ExchangeRate(
base: CryptoCurrency.btc,
@@ -112,18 +271,19 @@ void main() {
quote: Money.parse("0.00000444", EUR, strictParsing: false),
);
+ expect(zeroRate.convert(Money.parse("1", CryptoCurrency.shib)), Money.zero(EUR));
expect(
- zeroRate.convert(Money.parse("1", CryptoCurrency.shib)),
- Money.parse("0.00000444", EUR, strictParsing: false),
+ zeroRate.convert(Money.parse("1000000", CryptoCurrency.shib)),
+ Money.parse("4.44", EUR),
);
expect(
zeroRate.convert(Money.fromInt(10000, EUR)),
Money.parse("22522522.522522522522522522", CryptoCurrency.shib),
);
expect(
- zeroRate.convert(Money.parse("200", CryptoCurrency.shib)),
- Money.parse("0.000888", EUR, strictParsing: false),
+ zeroRate.convert(Money.parse("200000000", CryptoCurrency.shib)),
+ Money.parse("888.00", EUR),
);
});
@@ -157,16 +317,16 @@ void main() {
expect(rate.convert(overPrecise), Money.parse("60000.00", EUR));
});
- test('the result carries the quote scale, not the currency default', () {
+ test('the result is truncated to the quote currency decimals, not the quote scale', () {
final preciseRate = ExchangeRate(
base: CryptoCurrency.btc,
quote: Money.parse("60000.123456", EUR, strictParsing: false),
);
final result = preciseRate.convert(Money.parse("1", CryptoCurrency.btc));
- expect(result.decimals, 6);
- expect(result, Money.parse("60000.123456", EUR, strictParsing: false));
+ expect(result.decimals, EUR.decimals);
+ expect(result, Money.parse("60000.12", EUR));
});
test('a quote scale finer than the currency survives the round trip', () {
@@ -211,10 +371,7 @@ void main() {
final oneQuoteUnitInBaseUnits =
BigInt.from(10).pow(CryptoCurrency.btc.decimals) ~/ rate.quote.amount;
- expect(
- (original - back).amount.abs(),
- lessThanOrEqualTo(oneQuoteUnitInBaseUnits + BigInt.one),
- );
+ expect(original.amount - back.amount <= oneQuoteUnitInBaseUnits + BigInt.one, isTrue);
});
test('round trip never inflates the amount', () {
### cw_core/test/amount/money_test.dart
@@ -44,6 +44,45 @@ void main() {
expect(() => Money.parse("1.0", CryptoCurrency.btc, isBaseUnit: true), throwsFormatException);
});
+ test("safeParse", () {
+ var money = Money.safeParse("1", CryptoCurrency.btc);
+ expect(money.amount, BigInt.from(100000000));
+
+ money = Money.safeParse("-1", CryptoCurrency.btc);
+ expect(money.amount, BigInt.from(-100000000));
+
+ money = Money.safeParse("1.11", CryptoCurrency.btc);
+ expect(money.amount, BigInt.from(111000000));
+
+ money = Money.safeParse("-1.11", CryptoCurrency.btc);
+ expect(money.amount, BigInt.from(-111000000));
+
+ money = Money.safeParse("-.11", CryptoCurrency.btc);
+ expect(money.amount, BigInt.from(-11000000));
+
+ money = Money.safeParse(".11", CryptoCurrency.btc);
+ expect(money.amount, BigInt.from(11000000));
+
+ // Invalid representation
+ expect(() => Money.safeParse("1,11", CryptoCurrency.btc), throwsFormatException);
+
+ // To many decimals
+ money = Money.safeParse("1.000000000000000", CryptoCurrency.btc);
+ expect(money.amount, BigInt.from(100000000));
+
+ money = Money.safeParse("1", CryptoCurrency.btc, isBaseUnit: true);
+ expect(money.amount, BigInt.from(1));
+
+ money = Money.safeParse("0", CryptoCurrency.btc, isBaseUnit: true);
+ expect(money.amount, BigInt.from(0));
+
+ money = Money.safeParse("-1", CryptoCurrency.btc, isBaseUnit: true);
+ expect(money.amount, BigInt.from(-1));
+
+ // canonical representation when expecting base units
+ expect(() => Money.safeParse("1.0", CryptoCurrency.btc, isBaseUnit: true), throwsFormatException);
+ });
+
test("tryParse", () {
var money = Money.tryParse("1", CryptoCurrency.btc);
expect(money?.amount, BigInt.from(100000000));
### cw_core/test/amount/utils.dart
@@ -32,6 +32,9 @@ class FiatCurrency implements Currency {
@override
String get apiString => "fiat.$symbol";
+ @override
+ String get serialized => "fiat^$symbol";
+
@override
Money parseAmount(String value) => Money.parse(value, this);
### cw_custom_lints/pubspec.lock
@@ -1,429 +0,0 @@
-# Generated by pub
-# See https://dart.dev/tools/pub/glossary#lockfile
-packages:
- _fe_analyzer_shared:
- dependency: transitive
- description:
- name: _fe_analyzer_shared
- sha256: cd6add6f846f35fb79f3c315296703c1a24f3cfd7f4739d91a74961c1c7e9f1b
- url: "https://pub.dev"
- source: hosted
- version: "100.0.0"
- analysis_server_plugin:
- dependency: "direct main"
- description:
- name: analysis_server_plugin
- sha256: c4021359e7a673ecd9c6db5f11fea12fabb55e0ba96fa08c78920ae81936f1d1
- url: "https://pub.dev"
- source: hosted
- version: "0.3.15"
- analyzer:
- dependency: "direct main"
- description:
- name: analyzer
- sha256: "6ba98576948803398b69e3a444df24eacdbe12ed699c7014e120ea38552debbf"
- url: "https://pub.dev"
- source: hosted
- version: "13.0.0"
- analyzer_plugin:
- dependency: "direct main"
- description:
- name: analyzer_plugin
- sha256: "9a81dc36f7f71890d7cf83960a3a7df1e6c9a24035f98eb848e91ad48b1d21c6"
- url: "https://pub.dev"
- source: hosted
- version: "0.14.9"
- analyzer_testing:
- dependency: "direct dev"
- description:
- name: analyzer_testing
- sha256: da27ae9bd4bf3ce4ebab6295cf922ca21a2b14ea8fcacc859342aca796a48a2d
- url: "https://pub.dev"
- source: hosted
- version: "0.2.6"
- args:
- dependency: transitive
- description:
- name: args
- sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
- url: "https://pub.dev"
- source: hosted
- version: "2.7.0"
- async:
- dependency: transitive
- description:
- name: async
- sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37
- url: "https://pub.dev"
- source: hosted
- version: "2.13.1"
- boolean_selector:
- dependency: transitive
- description:
- name: boolean_selector
- sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
- url: "https://pub.dev"
- source: hosted
- version: "2.1.2"
- cli_config:
- dependency: transitive
- description:
- name: cli_config
- sha256: ac20a183a07002b700f0c25e61b7ee46b23c309d76ab7b7640a028f18e4d99ec
- url: "https://pub.dev"
- source: hosted
- version: "0.2.0"
- collection:
- dependency: transitive
- description:
- name: collection
- sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
- url: "https://pub.dev"
- source: hosted
- version: "1.19.1"
- convert:
- dependency: transitive
- description:
- name: convert
- sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68
- url: "https://pub.dev"
- source: hosted
- version: "3.1.2"
- coverage:
- dependency: transitive
- description:
- name: coverage
- sha256: "956a3de0725ca232ad353565a8290d3357592bf4250f6f298a185e2d949c5d3d"
- url: "https://pub.dev"
- source: hosted
- version: "1.15.1"
- crypto:
- dependency: transitive
- description:
- name: crypto
- sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
- url: "https://pub.dev"
- source: hosted
- version: "3.0.7"
- dart_style:
- dependency: transitive
- description:
- name: dart_style
- sha256: "59d53ef8eaed9d288ed9767618e2b31c4fa0383a127db59d5eb2e737a7638a60"
- url: "https://pub.dev"
- source: hosted
- version: "3.1.9"
- file:
- dependency: transitive
- description:
- name: file
- sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
- url: "https://pub.dev"
- source: hosted
- version: "7.0.1"
- frontend_server_client:
- dependency: transitive
- description:
- name: frontend_server_client
- sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694
- url: "https://pub.dev"
- source: hosted
- version: "4.0.0"
- glob:
- dependency: transitive
- description:
- name: glob
- sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de
- url: "https://pub.dev"
- source: hosted
- version: "2.1.3"
- http_multi_server:
- dependency: transitive
- description:
- name: http_multi_server
- sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8
- url: "https://pub.dev"
- source: hosted
- version: "3.2.2"
- http_parser:
- dependency: transitive
- description:
- name: http_parser
- sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
- url: "https://pub.dev"
- source: hosted
- version: "4.1.2"
- io:
- dependency: transitive
- description:
- name: io
- sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b
- url: "https://pub.dev"
- source: hosted
- version: "1.0.5"
- logging:
- dependency: transitive
- description:
- name: logging
- sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
- url: "https://pub.dev"
- source: hosted
- version: "1.3.0"
- matcher:
- dependency: transitive
- description:
- name: matcher
- sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
- url: "https://pub.dev"
- source: hosted
- version: "0.12.20"
- meta:
- dependency: transitive
- description:
- name: meta
- sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
- url: "https://pub.dev"
- source: hosted
- version: "1.19.0"
- mime:
- dependency: transitive
- description:
- name: mime
- sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6"
- url: "https://pub.dev"
- source: hosted
- version: "2.0.0"
- node_preamble:
- dependency: transitive
- description:
- name: node_preamble
- sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db"
- url: "https://pub.dev"
- source: hosted
- version: "2.0.2"
- package_config:
- dependency: transitive
- description:
- name: package_config
- sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc
- url: "https://pub.dev"
- source: hosted
- version: "2.2.0"
- path:
- dependency: transitive
- description:
- name: path
- sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
- url: "https://pub.dev"
- source: hosted
- version: "1.9.1"
- pool:
- dependency: transitive
- description:
- name: pool
- sha256: "978783255c543aa3586a1b3c21f6e9d720eb315376a915872c61ef8b5c20177d"
- url: "https://pub.dev"
- source: hosted
- version: "1.5.2"
- pub_semver:
- dependency: transitive
- description:
- name: pub_semver
- sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585"
- url: "https://pub.dev"
- source: hosted
- version: "2.2.0"
- shelf:
- dependency: transitive
- description:
- name: shelf
- sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12
- url: "https://pub.dev"
- source: hosted
- version: "1.4.2"
- shelf_packages_handler:
- dependency: transitive
- description:
- name: shelf_packages_handler
- sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e"
- url: "https://pub.dev"
- source: hosted
- version: "3.0.2"
- shelf_static:
- dependency: transitive
- description:
- name: shelf_static
- sha256: c87c3875f91262785dade62d135760c2c69cb217ac759485334c5857ad89f6e3
- url: "https://pub.dev"
- source: hosted
- version: "1.1.3"
- shelf_web_socket:
- dependency: transitive
- description:
- name: shelf_web_socket
- sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925"
- url: "https://pub.dev"
- source: hosted
- version: "3.0.0"
- source_map_stack_trace:
- dependency: transitive
- description:
- name: source_map_stack_trace
- sha256: c0713a43e323c3302c2abe2a1cc89aa057a387101ebd280371d6a6c9fa68516b
- url: "https://pub.dev"
- source: hosted
- version: "2.1.2"
- source_maps:
- dependency: transitive
- description:
- name: source_maps
- sha256: "190222579a448b03896e0ca6eca5998fa810fda630c1d65e2f78b3f638f54812"
- url: "https://pub.dev"
- source: hosted
- version: "0.10.13"
- source_span:
- dependency: transitive
- description:
- name: source_span
- sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab"
- url: "https://pub.dev"
- source: hosted
- version: "1.10.2"
- stack_trace:
- dependency: transitive
- description:
- name: stack_trace
- sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1"
- url: "https://pub.dev"
- source: hosted
- version: "1.12.1"
- stream_channel:
- dependency: transitive
- description:
- name: stream_channel
- sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
- url: "https://pub.dev"
- source: hosted
- version: "2.1.4"
- string_scanner:
- dependency: transitive
- description:
- name: string_scanner
- sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
- url: "https://pub.dev"
- source: hosted
- version: "1.4.1"
- term_glyph:
- dependency: transitive
- description:
- name: term_glyph
- sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
- url: "https://pub.dev"
- source: hosted
- version: "1.2.2"
- test:
- dependency: "direct dev"
- description:
- name: test
- sha256: "0d5ba5602ec3baa28c8ce365e1efc5575969c765f45c554a3e167dc7945b9c30"
- url: "https://pub.dev"
- source: hosted
- version: "1.31.2"
- test_api:
- dependency: transitive
- description:
- name: test_api
- sha256: "475610b2aa23c19687cce2961e44b0cc57cafe220f67c2b80201231b2a07fbe7"
- url: "https://pub.dev"
- source: hosted
- version: "0.7.13"
- test_core:
- dependency: transitive
- description:
- name: test_core
- sha256: a39c204a4fc7a7ccb04a2b985e359fda3cc37e45e0b8ac61c3fb1a05aa832132
- url: "https://pub.dev"
- source: hosted
- version: "0.6.19"
- test_reflective_loader:
- dependency: "direct dev"
- description:
- name: test_reflective_loader
- sha256: d828d5ca15179aaac2aaf8f510cf0a52ec28e0031681b044ec5e581a4b8002e7
- url: "https://pub.dev"
- source: hosted
- version: "0.4.0"
- typed_data:
- dependency: transitive
- description:
- name: typed_data
- sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
- url: "https://pub.dev"
- source: hosted
- version: "1.4.0"
- vm_service:
- dependency: transitive
- description:
- name: vm_service
- sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360"
- url: "https://pub.dev"
- source: hosted
- version: "15.2.0"
- watcher:
- dependency: transitive
- description:
- name: watcher
- sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635"
- url: "https://pub.dev"
- source: hosted
- version: "1.2.1"
- web:
- dependency: transitive
- description:
- name: web
- sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
- url: "https://pub.dev"
- source: hosted
- version: "1.1.1"
- web_socket:
- dependency: transitive
- description:
- name: web_socket
- sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c"
- url: "https://pub.dev"
- source: hosted
- version: "1.0.1"
- web_socket_channel:
- dependency: transitive
- description:
- name: web_socket_channel
- sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8
- url: "https://pub.dev"
- source: hosted
- version: "3.0.3"
- webkit_inspection_protocol:
- dependency: transitive
- description:
- name: webkit_inspection_protocol
- sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572"
- url: "https://pub.dev"
- source: hosted
- version: "1.2.1"
- yaml:
- dependency: transitive
- description:
- name: yaml
- sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce
- url: "https://pub.dev"
- source: hosted
- version: "3.1.3"
- yaml_edit:
- dependency: transitive
- description:
- name: yaml_edit
- sha256: "07c9e63ba42519745182b88ca12264a7ba2484d8239958778dfe4d44fe760488"
- url: "https://pub.dev"
- source: hosted
- version: "2.2.4"
-sdks:
- dart: ">=3.11.0 <4.0.0"
### cw_monero/lib/api/exceptions/wallet_creation_exception.dart
[binary or diff unavailable]
### cw_monero/lib/api/wallet_manager.dart
@@ -5,7 +5,6 @@ import 'dart:isolate';
import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_monero/api/account_list.dart';
-import 'package:cw_monero/api/exceptions/wallet_creation_exception.dart';
import 'package:cw_monero/api/exceptions/wallet_opening_exception.dart';
import 'package:cw_monero/api/exceptions/wallet_restore_from_keys_exception.dart';
import 'package:cw_monero/api/exceptions/wallet_restore_from_seed_exception.dart';
### cw_solana/lib/solana_client.dart
@@ -1008,6 +1008,20 @@ class SolanaWalletClient {
}
}
+ /// Whether the transaction landed without an error, or null while the cluster hasn't confirmed it
+ Future<bool?> getTransactionResult(String signature) async {
+ final statuses = await _provider!.request(
+ SolanaRPCGetSignatureStatuses(signatures: [signature], searchTransactionHistory: true),
+ );
+
+ final status = statuses.first;
+ if (status == null || status.confirmationStatus == TransactionConfirmationStatus.processed) {
+ return null;
+ }
+
+ return status.err == null;
+ }
+
/// Extracts token mint addresses from transaction metadata
/// It returns a list of unique token mint addresses (excluding wrapped SOL)
List<String> _extractTokenMintsFromMeta(ConfirmedTransactionMeta? meta) {
### lib/core/address_resolver/lnurl_pay/lnurl_pay_address_provider.dart
@@ -6,7 +6,6 @@ import 'package:cake_wallet/store/settings_store.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_base.dart';
-import 'package:cw_core/wallet_type.dart';
class LNUrlPayAddressProvider extends AddressLookupProvider {
@override
@@ -29,8 +28,6 @@ class LNUrlPayAddressProvider extends AddressLookupProvider {
required WalletBase wallet,
}) async {
try {
- if (wallet.type != WalletType.bitcoin) return [];
-
final formattedName = query.trim();
if (formattedName.isEmpty) return [];
### lib/core/address_resolver/thorchain/thorchain_address_provider.dart
@@ -1,13 +1,15 @@
-import 'package:cake_wallet/core/address_resolver/address_lookup_provider.dart';
-import 'package:cake_wallet/core/address_resolver/address_resolver_utils.dart';
-import 'package:cake_wallet/core/address_resolver/address_sources.dart';
-import 'package:cake_wallet/core/address_resolver/parsed_address.dart';
-import 'package:cake_wallet/core/address_validator.dart';
-import 'package:cake_wallet/exchange/provider/thorchain_exchange.provider.dart';
-import 'package:cake_wallet/store/settings_store.dart';
-import 'package:cw_core/crypto_currency.dart';
-import 'package:cw_core/utils/print_verbose.dart';
-import 'package:cw_core/wallet_base.dart';
+import "dart:convert";
+
+import "package:cake_wallet/core/address_resolver/address_lookup_provider.dart";
+import "package:cake_wallet/core/address_resolver/address_resolver_utils.dart";
+import "package:cake_wallet/core/address_resolver/address_sources.dart";
+import "package:cake_wallet/core/address_resolver/parsed_address.dart";
+import "package:cake_wallet/core/address_validator.dart";
+import "package:cake_wallet/store/settings_store.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:cw_core/wallet_base.dart";
class ThorchainAddressProvider extends AddressLookupProvider {
@override
@@ -22,6 +24,41 @@ class ThorchainAddressProvider extends AddressLookupProvider {
@override
bool isEnabled(SettingsStore settingsStore) => settingsStore.lookupsThorChain;
+ static const _baseURL = "midgard.ninerealms.com";
+ static const _nameLookUpPath = "v2/thorname/lookup/";
+
+
+ static Future<Map<String, String>?>? lookupAddressByName(String name) async {
+ final uri = Uri.https(_baseURL, "$_nameLookUpPath$name");
+ try {
+ 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;
+ } catch (e) {
+ printV(e.toString());
+ return null;
+ }
+ }
+
@override
Future<List<ParsedAddress>> resolve({
required String query,
@@ -33,15 +70,15 @@ class ThorchainAddressProvider extends AddressLookupProvider {
AddressResolverUtils.extractAddressByType(raw: query, type: cur)?.isNotEmpty ?? false);
if (query.length > 30 || isNormalAddress) return [];
- final map = await ThorChainExchangeProvider.lookupAddressByName(query);
+ final map = await lookupAddressByName(query);
if (map == null || map.isEmpty) return [];
final result = <CryptoCurrency, String>{};
for (final cur in currencies) {
final key = cur.title.toUpperCase();
final addr = map[key];
- final runeAddr = cur.title.toUpperCase() == 'RUNE' ? map['THOR'] : null;
+ final runeAddr = cur.title.toUpperCase() == "RUNE" ? map["THOR"] : null;
final resolvedAddress = addr ?? runeAddr;
if (resolvedAddress != null && resolvedAddress.isNotEmpty) {
if (!result.containsValue(resolvedAddress)) result[cur] = resolvedAddress;
@@ -58,7 +95,7 @@ class ThorchainAddressProvider extends AddressLookupProvider {
)
];
} catch (e) {
- printV('[address resolver] Error resolving address: $e');
+ printV("[address resolver] Error resolving address: $e");
return [];
}
}
### lib/core/csv_export_service.dart
@@ -137,15 +137,15 @@ class CsvExportService {
'swap',
'',
'',
- trade.fee?.toString() ?? '',
+ '',
trade.outputTransaction ?? '',
- trade.payoutAddress ?? '',
+ trade.payoutAddress,
trade.state.title,
trade.memo ?? '',
- trade.amount,
- trade.from?.name ?? '',
- trade.receiveAmount ?? '',
- trade.to?.name ?? '',
+ trade.depositAmount.toString(),
+ trade.depositCurrency.name,
+ trade.payoutAmount.toString(),
+ trade.payoutCurrency.name,
trade.id,
trade.provider.title,
'',
### lib/core/trade_monitor.dart
@@ -1,24 +1,21 @@
import 'dart:async';
-import 'package:cake_wallet/exchange/provider/jupiter_exchange_provider.dart';
-import 'package:cake_wallet/exchange/provider/near_Intents_exchange_provider.dart';
-import 'package:cake_wallet/exchange/provider/simpleswap_exchange_provider.dart';
-import 'package:cake_wallet/exchange/provider/swapsxyz_exchange_provider.dart';
+import 'package:cake_wallet/exchange/provider/jupiter/jupiter_exchange_provider.dart';
+import 'package:cake_wallet/exchange/provider/near_intents/near_intents_exchange_provider.dart';
+import 'package:cake_wallet/exchange/provider/swapsxyz/swapsxyz_exchange_provider.dart';
import 'package:cake_wallet/exchange/trade.dart';
import 'package:cake_wallet/exchange/trade_state.dart';
import 'package:cake_wallet/store/dashboard/trades_store.dart';
import 'package:cake_wallet/entities/exchange_api_mode.dart';
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/provider/chainflip_exchange_provider.dart';
-import 'package:cake_wallet/exchange/provider/changenow_exchange_provider.dart';
+import 'package:cake_wallet/exchange/provider/chainflip/chainflip_exchange_provider.dart';
+import 'package:cake_wallet/exchange/provider/changenow/changenow_exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
-import 'package:cake_wallet/exchange/provider/exolix_exchange_provider.dart';
-import 'package:cake_wallet/exchange/provider/swaptrade_exchange_provider.dart';
-import 'package:cake_wallet/exchange/provider/sideshift_exchange_provider.dart';
-import 'package:cake_wallet/exchange/provider/stealth_ex_exchange_provider.dart';
-import 'package:cake_wallet/exchange/provider/thorchain_exchange.provider.dart';
-import 'package:cake_wallet/exchange/provider/trocador_exchange_provider.dart';
-import 'package:cake_wallet/exchange/provider/whynot_exchange_provider.dart';
-import 'package:cake_wallet/exchange/provider/xoswap_exchange_provider.dart';
+import 'package:cake_wallet/exchange/provider/exolix/exolix_exchange_provider.dart';
+import 'package:cake_wallet/exchange/provider/swaptrade/swaptrade_exchange_provider.dart';
+import 'package:cake_wallet/exchange/provider/stealthex/stealthex_exchange_provider.dart';
+import 'package:cake_wallet/exchange/provider/trocador/trocador_exchange_provider.dart';
+import 'package:cake_wallet/exchange/provider/whynot/whynot_exchange_provider.dart';
+import 'package:cake_wallet/exchange/provider/xoswap/xoswap_exchange_provider.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -38,39 +35,26 @@ class TradeMonitor {
final Map<String, Timer> _tradeTimers = {};
final SharedPreferences preferences;
- ExchangeProvider? _getProviderByDescription(ExchangeProviderDescription description) {
- switch (description) {
- case ExchangeProviderDescription.changeNow:
- return ChangeNowExchangeProvider(settingsStore: appStore.settingsStore);
- case ExchangeProviderDescription.sideShift:
- return SideShiftExchangeProvider();
- case ExchangeProviderDescription.simpleSwap:
- return SimpleSwapExchangeProvider();
- case ExchangeProviderDescription.trocador:
- return TrocadorExchangeProvider();
- case ExchangeProviderDescription.exolix:
- return ExolixExchangeProvider();
- case ExchangeProviderDescription.thorChain:
- return ThorChainExchangeProvider();
- case ExchangeProviderDescription.swapTrade:
- return SwapTradeExchangeProvider();
- case ExchangeProviderDescription.whyNot:
- return WhyNotExchangeProvider();
- case ExchangeProviderDescription.stealthEx:
- return StealthExExchangeProvider();
- case ExchangeProviderDescription.chainflip:
- return ChainflipExchangeProvider();
- case ExchangeProviderDescription.xoSwap:
- return XOSwapExchangeProvider();
- case ExchangeProviderDescription.swapsXyz:
- return SwapsXyzExchangeProvider();
- case ExchangeProviderDescription.jupiter:
- return JupiterExchangeProvider();
- case ExchangeProviderDescription.nearIntents:
- return NearIntentsExchangeProvider();
- }
- return null;
- }
+ ExchangeProvider? _getProviderByDescription(ExchangeProviderDescription description) =>
+ switch (description) {
+ .changeNow =>
+ ChangeNowExchangeProvider(settingsStore: appStore.settingsStore),
+ .trocador => TrocadorExchangeProvider(),
+ .exolix => ExolixExchangeProvider(),
+ .swapTrade => SwapTradeExchangeProvider(),
+ .whyNot => WhyNotExchangeProvider(),
+ .stealthEx => StealthExExchangeProvider(),
+ .chainflip => ChainflipExchangeProvider(),
+ .xoSwap => XOSwapExchangeProvider(),
+ .jupiter => JupiterExchangeProvider(),
+ .nearIntents => NearIntentsExchangeProvider(),
+ .swapsXyz =>
+ SwapsXyzExchangeProvider(settingsStore: appStore.settingsStore),
+ .xmrto ||
+ .morphToken || .sideShift ||
+ .simpleSwap || .all ||
+ .thorChain => null
+ };
void monitorActiveTrades(String walletId) {
// Checks if the trade monitoring is permitted
@@ -97,14 +81,38 @@ class TradeMonitor {
if (_tradeTimers.containsKey(trade.id)) {
continue;
} else {
- _startTradeMonitoring(trade, provider!);
+ _startTradeMonitoring(trade.id, provider!);
}
}
// After going through the list of available trades, we cancel the timers in the tradesToCancel list
_cancelMultipleTradeTimers(tradesToCancel);
}
+ Future<void> recordDeposit(String tradeId, String txId) async {
+ if (txId.isEmpty) {
+ return;
+ }
+
+ try {
+ final trade = await Trade.getByTradeId(tradeId);
+ if (trade == null) {
+ return;
+ }
+
+ await trade.copyWith(txId: txId).save();
+
+ final provider = _getProviderByDescription(trade.provider);
+ if (provider == null || !_isTradeMonitoringPermitted() || _isBlockedByTor(provider)) {
+ return;
+ }
+
+ await _checkTradeStatus(tradeId, provider, force: true);
+ } catch (e) {
+ printV("Error recording deposit $txId for $tradeId: $e");
+ }
+ }
+
bool _isTradeMonitoringPermitted() {
final disableAutomaticExchangeStatusUpdates =
appStore.settingsStore.disableAutomaticExchangeStatusUpdates;
@@ -147,57 +155,65 @@ class TradeMonitor {
return true;
}
- if (appStore.settingsStore.exchangeStatus == ExchangeApiMode.torOnly &&
- !provider.supportsOnionAddress) {
+ if (_isBlockedByTor(provider)) {
printV('Skipping ${provider.description}, no TOR support');
return true;
}
return false;
}
- void _startTradeMonitoring(Trade trade, ExchangeProvider provider) {
+ bool _isBlockedByTor(ExchangeProvider provider) =>
+ appStore.settingsStore.exchangeStatus == ExchangeApiMode.torOnly &&
+ !provider.supportsOnionAddress;
+
+ void _startTradeMonitoring(String tradeId, ExchangeProvider provider) {
final timer = Timer.periodic(
Duration(minutes: _tradeCheckIntervalMinutes),
- (_) => _checkTradeStatus(trade, provider),
+ (_) => _checkTradeStatus(tradeId, provider),
);
- _checkTradeStatus(trade, provider);
+ _checkTradeStatus(tradeId, provider);
- _tradeTimers[trade.id] = timer;
+ _tradeTimers[tradeId] = timer;
}
- Future<void> _checkTradeStatus(Trade trade, ExchangeProvider provider) async {
- final lastUpdatedAtFromPrefs = preferences.getString('trade_${trade.id}_updated_at');
+ Future<void> _checkTradeStatus(String tradeId, ExchangeProvider provider, {bool force = false}) async {
+ final lastUpdatedAtFromPrefs = preferences.getString('trade_${tradeId}_updated_at');
- if (lastUpdatedAtFromPrefs != null) {
+ if (!force && lastUpdatedAtFromPrefs != null) {
final lastUpdatedAtDateTime = DateTime.parse(lastUpdatedAtFromPrefs);
final timeSinceLastUpdate = DateTime.now().difference(lastUpdatedAtDateTime).inMinutes;
if (timeSinceLastUpdate < _tradeCheckIntervalMinutes) {
printV(
- 'Skipping trade ${trade.id} status update check because it was updated less than ${_tradeCheckIntervalMinutes} minutes ago ($timeSinceLastUpdate minutes ago)',
+ "Skipping trade ${tradeId} status update check because it was updated less than ${_tradeCheckIntervalMinutes} minutes ago ($timeSinceLastUpdate minutes ago)",
);
return;
}
}
try {
- final updated = await provider.findTradeById(id: trade.id);
- trade.mergeFindTradeByIdResult(updated);
- printV('Trade ${trade.id} updated: ${trade.state}');
- await trade.save();
+ final trade = await Trade.getByTradeId(tradeId);
+ if (trade == null) {
+ _cancelSingleTradeTimer(tradeId);
+ return;
+ }
+
+ final updated = await provider.updateTrade(trade);
+ printV('Trade ${tradeId} updated: ${updated.state}');
+ await updated.save();
- await preferences.setString('trade_${trade.id}_updated_at', DateTime.now().toIso8601String());
- printV('Trade ${trade.id} updated at: ${DateTime.now().toIso8601String()}');
+ await preferences.setString('trade_${tradeId}_updated_at', DateTime.now().toIso8601String());
+ printV('Trade ${tradeId} updated at: ${DateTime.now().toIso8601String()}');
// If the updated trade is in a final state, we cancel the timer
if (_isFinalState(updated.state)) {
- printV('Trade ${trade.id} is in final state');
- _cancelSingleTradeTimer(trade.id);
+ printV('Trade ${tradeId} is in final state');
+ _cancelSingleTradeTimer(tradeId);
}
} catch (e) {
- printV('Error fetching status for ${trade.id}: $e');
+ printV('Error fetching status for ${tradeId}: $e');
}
}
### lib/di.dart
@@ -1,4 +1,5 @@
import 'dart:async' show Timer;
+import 'dart:async' show Timer;
import 'package:cake_wallet/.secrets.g.dart' as secrets;
import 'package:cake_wallet/anonpay/anonpay_api.dart';
@@ -47,7 +48,7 @@ import 'package:cake_wallet/entities/transaction_description.dart';
import 'package:cake_wallet/entities/wallet_edit_page_arguments.dart';
import 'package:cake_wallet/entities/wallet_manager.dart';
import 'package:cake_wallet/exchange/exchange_template.dart';
-import 'package:cake_wallet/exchange/provider/trocador_exchange_provider.dart';
+import 'package:cake_wallet/exchange/provider/trocador/trocador_exchange_provider.dart';
import 'package:cake_wallet/exchange/trade.dart';
import 'package:cake_wallet/haven/cw_haven.dart';
import 'package:cake_wallet/monero/monero.dart';
@@ -72,7 +73,17 @@ import 'package:cake_wallet/new-ui/pages/receive_page.dart';
import "package:cake_wallet/new-ui/pages/seed/pre_seed_page.dart";
import "package:cake_wallet/new-ui/pages/seed/show_keys_disclaimer_page.dart";
import 'package:cake_wallet/new-ui/viewmodels/charts/charts_bloc.dart';
+import "package:cake_wallet/new-ui/services/transaction_service.dart";
+import "package:cake_wallet/new-ui/services/wallet_switch_service.dart";
import 'package:cake_wallet/new-ui/viewmodels/lightning_username/lightning_username_bloc.dart';
+import "package:cake_wallet/new-ui/viewmodels/swap/currency_provider.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/provider_registry.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/rates/rate_cubit.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/bloc/swap_bloc.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/swap_address_resolver.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/trade_creator.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/fees_helper.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/swap_amount.dart";
import 'package:cake_wallet/new-ui/widgets/addresses_page/address_label_input.dart';
import 'package:cake_wallet/new-ui/widgets/buy_sell/buy_sell_selector_modal.dart';
import 'package:cake_wallet/new-ui/widgets/coins_page/assets_history/transaction_details_modal.dart';
@@ -157,8 +168,6 @@ import 'package:cake_wallet/src/screens/wallet_list/wallet_list_page.dart';
import 'package:cake_wallet/src/screens/wallet_unlock/wallet_unlock_arguments.dart';
import 'package:cake_wallet/src/screens/wallet_unlock/wallet_unlock_page.dart';
import 'package:cake_wallet/src/screens/welcome/welcome_page.dart';
-import 'package:cake_wallet/src/widgets/bottom_sheet/swap_confirmation_bottom_sheet.dart';
-import 'package:cake_wallet/src/widgets/bottom_sheet/swap_details_bottom_sheet.dart';
import 'package:cake_wallet/store/anonpay/anonpay_transactions_store.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/store/authentication_store.dart';
@@ -206,8 +215,6 @@ import 'package:cake_wallet/view_model/dev/secure_preferences.dart';
import 'package:cake_wallet/view_model/dev/shared_preferences.dart';
import 'package:cake_wallet/view_model/dev/socket_health_logs_view_model.dart';
import 'package:cake_wallet/view_model/edit_backup_password_view_model.dart';
-import 'package:cake_wallet/view_model/exchange/exchange_trade_view_model.dart';
-import 'package:cake_wallet/view_model/exchange/exchange_view_model.dart';
import 'package:cake_wallet/view_model/hardware_wallet/bitbox_view_model.dart';
import 'package:cake_wallet/view_model/hardware_wallet/hardware_wallet_view_model.dart';
import 'package:cake_wallet/view_model/hardware_wallet/ledger_view_model.dart';
@@ -295,7 +302,6 @@ import 'buy/meld/meld_buy_provider.dart';
import 'dogecoin/dogecoin.dart';
import 'new-ui/viewmodels/card_customizer/card_customizer_bloc.dart';
import 'new-ui/widgets/addresses_page/address_info.dart';
-import 'src/screens/buy/buy_sell_page.dart';
final getIt = GetIt.instance;
@@ -373,7 +379,7 @@ Future<void> setup({
getIt.registerSingleton<TradeFilterStore>(TradeFilterStore());
getIt.registerSingleton<OrderFilterStore>(OrderFilterStore());
getIt.registerSingleton<TransactionFilterStore>(TransactionFilterStore(getIt.get<AppStore>()));
- getIt.registerSingleton<FiatConversionStore>(FiatConversionStore());
+ getIt.registerSingleton<FiatConversionStore>(FiatConversionStore(getIt.get<SettingsStore>()));
getIt.registerSingleton<AnonpayTransactionsStore>(
AnonpayTransactionsStore(anonpayInvoiceInfoSource: _anonpayInvoiceInfoSource));
getIt.registerSingleton<SeedSettingsStore>(SeedSettingsStore());
@@ -517,17 +523,46 @@ Future<void> setup({
settingsStore: getIt.get<SettingsStore>(),
fiatConversionStore: getIt.get<FiatConversionStore>()));
- getIt.registerFactory(
- () => ExchangeViewModel(
- getIt.get<AppStore>(),
- getIt.get<TradesStore>(),
- getIt.get<SharedPreferences>(),
- getIt.get<ContactListViewModel>(),
- getIt.get<UnspentCoinsListViewModel>(),
- getIt.get<FeesViewModel>(),
- getIt.get<FiatConversionStore>(),
- ),
- );
+ getIt.registerLazySingleton<ExchangeProviderRegistry>(() =>
+ ExchangeProviderRegistry(sharedPreferences: getIt.get<SharedPreferences>(), settingsStore: getIt.get<SettingsStore>()));
+
+ getIt.registerFactory<RateCubit>(() =>
+ RateCubit(registry: getIt.get<ExchangeProviderRegistry>()));
+
+ getIt.registerLazySingleton<SwapAmountFactory>(() =>
+ SwapAmountFactory(
+ fcs: getIt.get<FiatConversionStore>(), appStore: getIt.get<AppStore>()));
+
+ getIt.registerFactory<SwapCurrencyStore>(SwapCurrencyStore.new);
+
+ getIt.registerSingleton<WalletSwitchService>(WalletSwitchService(walletLoadingService: getIt.get<WalletLoadingService>(), appStore: getIt.get<AppStore>()));
+
+ getIt.registerSingleton<TransactionService>(TransactionService(appStore: getIt.get<AppStore>()));
+
+ getIt.registerSingleton<SwapAddressResolver>(SwapAddressResolver(appStore: getIt.get<AppStore>()));
+
+ getIt.registerSingleton<TradeCreator>(TradeCreator(
+ appStore: getIt.get<AppStore>(),
+ registry: getIt.get<ExchangeProviderRegistry>()));
+
+ getIt.registerSingleton<FeesHelper>(FeesHelper(appStore: getIt.get<AppStore>()));
+
+ getIt.registerFactory<SwapBloc>(() =>
+ SwapBloc(
+ feesHelper: getIt.get<FeesHelper>(),
+ addressResolver: getIt.get<SwapAddressResolver>(),
+ creator: getIt.get<TradeCreator>(),
+ addressResolverService: getIt.get<AddressResolverService>(),
+ transactionService: getIt.get<TransactionService>(),
+ tradeMonitor: getIt.get<TradeMonitor>(),
+ walletSwitchService: getIt.get<WalletSwitchService>(),
+ currencyStore: getIt.get<SwapCurrencyStore>(),
+ rateCubit: getIt.get<RateCubit>(),
+ amountFactory: getIt.get<SwapAmountFactory>(),
+ registry: getIt.get<ExchangeProviderRegistry>(),
+ appStore: getIt
+ .get<AppStore>(),
+ ));
getIt.registerSingleton(
TradeMonitor(
@@ -1172,56 +1207,23 @@ Future<void> setup({
),
);
- getIt.registerFactory(
- () => ExchangeTradeViewModel(
- wallet: getIt.get<AppStore>().wallet!,
- tradesStore: getIt.get<TradesStore>(),
- sendViewModel: getIt.get<SendViewModel>(),
- feesViewModel: getIt.get<FeesViewModel>(),
- fiatConversionStore: getIt.get<FiatConversionStore>(),
- ),
- );
-
getIt.registerFactoryParam<NewSwapPage, PaymentRequest?, CryptoCurrency?>(
(PaymentRequest? paymentRequest, CryptoCurrency? initialCurrency) {
return NewSwapPage(
- getIt.get<ExchangeViewModel>(),
+ getIt.get<SwapBloc>(),
getIt.get<AuthService>(),
- getIt.get<AddressResolverService>(),
paymentRequest,
- walletSwitcherViewModel: getIt.get<WalletSwitcherViewModel>(),
initialCurrency: initialCurrency,
);
});
-
getIt.registerFactory(() => BackgroundSyncPage(getIt.get<DashboardViewModel>()));
-
- getIt.registerFactoryParam<SwapConfirmationBottomSheet, PaymentFlowResult, void>(
- (paymentFlowResult, _) => SwapConfirmationBottomSheet(
- paymentFlowResult: paymentFlowResult,
- exchangeViewModel: getIt.get<ExchangeViewModel>(),
- authService: getIt.get<AuthService>(),
- ),
- );
-
- getIt.registerFactory<SwapDetailsBottomSheet>(
- () => SwapDetailsBottomSheet(
- exchangeTradeViewModel: getIt.get<ExchangeTradeViewModel>(),
- ),
- );
-
getIt.registerFactory(() => PaymentViewModel(
appStore: getIt.get<AppStore>(),
));
- getIt.registerFactory(() => WalletSwitchService(
- walletLoadingService: getIt.get<WalletLoadingService>(),
- appStore: getIt.get<AppStore>(),
- ));
-
getIt.registerFactory(() => AnyPayService(
appStore: getIt.get<AppStore>(),
walletSwitchService: getIt.get<WalletSwitchService>(),
### lib/entities/fiat_currency.dart
@@ -315,4 +315,7 @@ class FiatCurrency extends EnumerableItem<String> with Serializable<String> impl
@override
Money? tryParseAmount(String value) => Money.tryParse(value, this);
+
+ @override
+ String get serialized => "fiat^$symbol";
}
### lib/entities/fs_migration.dart
@@ -1,7 +1,9 @@
import 'dart:io';
import 'dart:convert';
import 'package:cake_wallet/core/secure_storage.dart';
+import "package:cake_wallet/exchange/trade_state.dart";
import 'package:collection/collection.dart';
+import "package:cw_core/amount/money.dart";
import 'package:cw_core/utils/print_verbose.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:hive/hive.dart';
@@ -399,11 +401,13 @@ Future<void> ios_migrate_trades_list() async {
await Trade(
id: tradeId,
provider: provider,
- from: from,
- to: to,
+ state: TradeState.expired,
+ fundingAddress: "",
+ refundAddress: "",
+ payoutAddress: "",
+ depositAmount: Money.zero(from),
+ payoutAmount: Money.zero(to),
createdAt: date,
- amount: '',
- receiveAmount: '',
).save();
}
### lib/exchange/exchange_provider_description.dart
@@ -1,140 +1,145 @@
-import 'package:cw_core/enumerable_item.dart';
+import "package:cw_core/enumerable_item.dart";
import "package:cw_core/exceptions/cake_exception.dart";
-class ExchangeProviderDescription extends EnumerableItem<int> with Serializable<int> {
- const ExchangeProviderDescription(
- {required String title,
- required int raw,
- required this.image,
- this.horizontalLogo = false,
- required this.isCentralized})
- : super(title: title, raw: raw);
+enum ExchangeProviderDescription implements EnumerableItem<int> {
+ xmrto(
+ title: "XMR.TO",
+ raw: 0,
+ image: "assets/new-ui/trade_providers/xmrto.svg",
+ isCentralized: true,
+ ),
+ changeNow(
+ title: "ChangeNOW",
+ raw: 1,
+ image: "assets/new-ui/trade_providers/changenow.svg",
+ isCentralized: true,
+ ),
+ morphToken(
+ title: "MorphToken",
+ raw: 2,
+ image: "assets/new-ui/trade_providers/morph.svg",
+ isCentralized: true,
+ ),
+ sideShift(
+ title: "SideShift",
+ raw: 3,
+ image: "assets/new-ui/trade_providers/sideshift.svg",
+ isCentralized: true,
+ ),
+ simpleSwap(
+ title: "SimpleSwap",
+ raw: 4,
+ image: "assets/new-ui/trade_providers/simpleswap.svg",
+ isCentralized: true,
+ ),
+ trocador(
+ title: "Trocador",
+ raw: 5,
+ image: "assets/new-ui/trade_providers/trocador.svg",
+ isCentralized: true,
+ ),
+ exolix(
+ title: "Exolix",
+ raw: 6,
+ image: "assets/new-ui/trade_providers/exolix.svg",
+ isCentralized: true,
+ ),
+ all(
+ title: "All trades",
+ raw: 7,
+ image: "",
+ isCentralized: true,
+ ),
+ thorChain(
+ title: "ThorChain",
+ raw: 8,
+ image: "assets/new-ui/trade_providers/thorchain.svg",
+ isCentralized: true,
+ ),
+ swapTrade(
+ title: "SwapTrade",
+ raw: 9,
+ image: "assets/new-ui/trade_providers/swaptrade.svg",
+ supportsMemoOrDestinationTag: false,
+ isCentralized: true,
+ ),
+ whyNot(
+ title: "WhyNot",
+ raw: 10,
+ image: "assets/new-ui/trade_providers/whynot.svg",
+ isCentralized: true,
+ ),
+ stealthEx(
+ title: "StealthEx",
+ raw: 11,
+ image: "assets/new-ui/trade_providers/stealthex.svg",
+ isCentralized: true,
+ ),
+ chainflip(
+ title: "Chainflip",
+ raw: 12,
+ image: "assets/new-ui/trade_providers/chainflip.svg",
+ supportsMemoOrDestinationTag: false,
+ isCentralized: false,
+ ),
+ xoSwap(
+ title: "XOSwap",
+ raw: 13,
+ image: "assets/new-ui/trade_providers/xoswap.svg",
+ isCentralized: true,
+ ),
+ swapsXyz(
+ title: "Swaps.XYZ",
+ raw: 14,
+ image: "assets/new-ui/trade_providers/swaps_xyz.svg",
+ supportsMemoOrDestinationTag: false,
+ supportsSwapAll: false,
+ isCentralized: true,
+ ),
+ nearIntents(
+ title: "Near Intents",
+ raw: 15,
+ image: "assets/new-ui/trade_providers/near-intents.svg",
+ supportsMemoOrDestinationTag: false,
+ supportsSwapAll: false,
+ isCentralized: false,
+ ),
+ jupiter(
+ title: "Jupiter",
+ raw: 16,
+ image: "assets/new-ui/trade_providers/jupiter.svg",
+ supportsMemoOrDestinationTag: false,
+ isCentralized: false,
+ );
+
+ const ExchangeProviderDescription({
+ required this.title,
+ required this.raw,
+ required this.image,
+ required this.isCentralized,
+ this.supportsSwapAll = true,
+ this.supportsMemoOrDestinationTag = true,
+ });
+
+ @override
+ final String title;
+
+ @override
+ final int raw;
- final bool horizontalLogo;
final String image;
final bool isCentralized;
-
- static const xmrto = ExchangeProviderDescription(
- title: 'XMR.TO',
- raw: 0,
- image: 'assets/new-ui/trade_providers/xmrto.svg',
- isCentralized: true);
- static const changeNow = ExchangeProviderDescription(
- title: 'ChangeNOW',
- raw: 1,
- image: 'assets/new-ui/trade_providers/changenow.svg',
- isCentralized: true);
- static const morphToken = ExchangeProviderDescription(
- title: 'MorphToken',
- raw: 2,
- image: 'assets/new-ui/trade_providers/morph.svg',
- isCentralized: true);
- static const sideShift = ExchangeProviderDescription(
- title: 'SideShift',
- raw: 3,
- image: 'assets/new-ui/trade_providers/sideshift.svg',
- isCentralized: true);
- static const simpleSwap = ExchangeProviderDescription(
- title: 'SimpleSwap',
- raw: 4,
- image: 'assets/new-ui/trade_providers/simpleswap.svg',
- isCentralized: true);
- static const trocador = ExchangeProviderDescription(
- title: 'Trocador',
- raw: 5,
- image: 'assets/new-ui/trade_providers/trocador.svg',
- isCentralized: true);
- static const exolix = ExchangeProviderDescription(
- title: 'Exolix',
- raw: 6,
- image: 'assets/new-ui/trade_providers/exolix.svg',
- isCentralized: true);
- static const all =
- ExchangeProviderDescription(title: 'All trades', raw: 7, image: '', isCentralized: true);
- static const thorChain = ExchangeProviderDescription(
- title: 'ThorChain',
- raw: 8,
- image: 'assets/new-ui/trade_providers/thorchain.svg',
- isCentralized: true);
- static const swapTrade = ExchangeProviderDescription(
- title: 'SwapTrade',
- raw: 9,
- image: 'assets/new-ui/trade_providers/swaptrade.svg',
- isCentralized: true);
- static const whyNot = ExchangeProviderDescription(
- title: 'WhyNot',
- raw: 10,
- image: 'assets/new-ui/trade_providers/whynot.svg',
- isCentralized: true);
- static const stealthEx = ExchangeProviderDescription(
- title: 'StealthEx',
- raw: 11,
- image: 'assets/new-ui/trade_providers/stealthex.svg',
- isCentralized: true);
- static const chainflip = ExchangeProviderDescription(
- title: 'Chainflip',
- raw: 12,
- image: 'assets/new-ui/trade_providers/chainflip.svg',
- isCentralized: false);
- static const xoSwap = ExchangeProviderDescription(
- title: 'XOSwap',
- raw: 13,
- image: 'assets/new-ui/trade_providers/xoswap.svg',
- isCentralized: true);
- static const swapsXyz = ExchangeProviderDescription(
- title: 'Swaps.XYZ',
- raw: 14,
- image: 'assets/new-ui/trade_providers/swaps_xyz.svg',
- isCentralized: true);
- static const nearIntents = ExchangeProviderDescription(
- title: 'Near Intents',
- raw: 15,
- image: 'assets/new-ui/trade_providers/near-intents.svg',
- isCentralized: false);
- static const jupiter = ExchangeProviderDescription(
- title: 'Jupiter',
- raw: 16,
- image: 'assets/new-ui/trade_providers/jupiter.svg',
- isCentralized: false);
+ final bool supportsSwapAll;
+ final bool supportsMemoOrDestinationTag;
static ExchangeProviderDescription deserialize({required int raw}) {
- switch (raw) {
- case 0:
- return xmrto;
- case 1:
- return changeNow;
- case 2:
- return morphToken;
- case 3:
- return sideShift;
- case 4:
- return simpleSwap;
- case 5:
- return trocador;
- case 6:
- return exolix;
- case 7:
- return all;
- case 8:
- return thorChain;
- case 9:
- return swapTrade;
- case 10:
- return whyNot;
- case 11:
- return stealthEx;
- case 12:
- return chainflip;
- case 13:
- return xoSwap;
- case 14:
- return swapsXyz;
- case 15:
- return nearIntents;
- case 16:
- return jupiter;
- default:
- throw DeserializeException('Unexpected token: $raw for ExchangeProviderDescription deserialize');
+ for (final provider in ExchangeProviderDescription.values) {
+ if (provider.raw == raw) {
+ return provider;
+ }
}
+ throw DeserializeException(
+ "Unexpected token: $raw for ExchangeProviderDescription deserialize",
+ );
}
-}
+}
\ No newline at end of file
### lib/exchange/provider/chainflip/chainflip_api_schema.dart
@@ -0,0 +1,981 @@
+// spec reference: https://chainflip-broker.io/docs/v1/docs.json
+
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/exchange/utils/json_converters.dart";
+import "package:cake_wallet/exchange/utils/provider_api.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:json_annotation/json_annotation.dart";
+
+part "chainflip_api_schema.g.dart";
+
+class ChainflipCurrencyConverter implements JsonConverter<CryptoCurrency, String> {
+ const ChainflipCurrencyConverter();
+
+ @override
+ String toJson(CryptoCurrency currency) {
+ if (currency == CryptoCurrency.trx) {
+ return "trx.tron";
+ }
+ if (currency == CryptoCurrency.usdttrc20) {
+ return "usdt.tron";
+ }
+
+ final tag = currency.tag?.toLowerCase();
+ final title = currency.title.toLowerCase();
+
+ if (tag == null) {
+ return "$title.$title";
+ }
+
+ return "$title.$tag";
+ }
+
+ @override
+ CryptoCurrency fromJson(String json) {
+ if (json == "trx.tron") {
+ return CryptoCurrency.trx;
+ }
+ if (json == "usdt.tron") {
+ return CryptoCurrency.usdttrc20;
+ }
+
+ final parts = json.split(".");
+ if (parts.length != 2) {
+ throw ArgumentError("bad currency input, should be title.tag");
+ }
+ final title = parts.first;
+ final tag = parts.last;
+ if (title == tag) {
+ return CryptoCurrency.fromString(title);
+ }
+ final currency = CryptoCurrency.safeParseCurrencyFromString(title, tag: tag);
+ if (currency == null) {
+ throw ArgumentError("unknown Chainflip asset: $json");
+ }
+ return currency;
+ }
+}
+
+@JsonSerializable()
+@ChainflipCurrencyConverter()
+class ChainflipFetchQuotesRequest extends ApiRequest<ChainflipFetchQuotesResponse> {
+ const ChainflipFetchQuotesRequest({
+ required this.apiKey,
+ required this.sourceAsset,
+ required this.destinationAsset,
+ required this.amount,
+ required this.commissionBps,
+ });
+
+ @JsonKey(name: "apiKey")
+ final String apiKey;
+ @JsonKey(name: "sourceAsset")
+ final CryptoCurrency sourceAsset;
+ @JsonKey(name: "destinationAsset")
+ final CryptoCurrency destinationAsset;
+ @JsonKey(name: "amount")
+ final BigInt amount;
+ @JsonKey(name: "commissionBps")
+ final String commissionBps;
+
+ @override
+ String path() => "/quotes-native";
+
+ @override
+ Map<String, dynamic> toJson() => _$ChainflipFetchQuotesRequestToJson(this);
+
+ @override
+ ChainflipFetchQuotesResponse decode(Object json) =>
+ ChainflipFetchQuotesResponse.fromJson(json as List<dynamic>);
+}
+
+enum ChainflipFeeType {
+ @JsonValue("egress")
+ egress,
+ @JsonValue("ingress")
+ ingress,
+ @JsonValue("network")
+ network,
+ @JsonValue("broker")
+ broker,
+ @JsonValue("liquidity")
+ liquidity,
+ @JsonValue("boost")
+ boost,
+ @JsonValue("refund")
+ refund,
+ unknown,
+}
+
+enum ChainflipQuoteType {
+ @JsonValue("regular")
+ regular,
+ @JsonValue("dca")
+ dca,
+ unknown,
+}
+
+enum ChainflipSwapState {
+ @JsonValue("waiting")
+ waiting,
+ @JsonValue("receiving")
+ receiving,
+ @JsonValue("swapping")
+ swapping,
+ @JsonValue("sending")
+ sending,
+ @JsonValue("sent")
+ sent,
+ @JsonValue("completed")
+ completed,
+ @JsonValue("failed")
+ failed,
+ unknown,
+}
+
+extension StatusToState on ChainflipSwapState {
+ TradeState get toState => switch (this) {
+ .waiting => .waiting,
+ .receiving => .processing,
+ .swapping => .processing,
+ .sending => .processing,
+ .sent => .processing,
+ .completed => .success,
+ .failed => .failed,
+ .unknown => .notFound,
+ };
+}
+
+@JsonSerializable(createToJson: false)
+@ChainflipCurrencyConverter()
+class ChainflipFeeData {
+ const ChainflipFeeData({required this.type, required this.asset, required this.amountNative});
+
+ factory ChainflipFeeData.fromJson(Map<String, dynamic> json) => _$ChainflipFeeDataFromJson(json);
+
+ @JsonKey(name: "type", unknownEnumValue: ChainflipFeeType.unknown)
+ final ChainflipFeeType type;
+ @JsonKey(name: "asset")
+ final CryptoCurrency asset;
+ @JsonKey(name: "amountNative")
+ final BigInt amountNative;
+}
+
+@JsonSerializable(createToJson: false)
+@ChainflipCurrencyConverter()
+class ChainflipPoolFee {
+ const ChainflipPoolFee({required this.asset, required this.amountNative});
+
+ factory ChainflipPoolFee.fromJson(Map<String, dynamic> json) => _$ChainflipPoolFeeFromJson(json);
+
+ @JsonKey(name: "asset")
+ final CryptoCurrency asset;
+ @JsonKey(name: "amountNative")
+ final BigInt amountNative;
+}
+
+@JsonSerializable(createToJson: false)
+@ChainflipCurrencyConverter()
+class ChainflipPoolInfo {
+ const ChainflipPoolInfo({required this.baseAsset, required this.quoteAsset, required this.fee});
+
+ factory ChainflipPoolInfo.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipPoolInfoFromJson(json);
+
+ @JsonKey(name: "baseAsset")
+ final CryptoCurrency baseAsset;
+ @JsonKey(name: "quoteAsset")
+ final CryptoCurrency quoteAsset;
+ @JsonKey(name: "fee")
+ final ChainflipPoolFee fee;
+}
+
+@JsonSerializable(createToJson: false)
+class ChainflipEstimatedDurations {
+ const ChainflipEstimatedDurations({
+ required this.deposit,
+ required this.swap,
+ required this.egress,
+ });
+
+ factory ChainflipEstimatedDurations.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipEstimatedDurationsFromJson(json);
+
+ @JsonKey(name: "deposit")
+ final double deposit;
+ @JsonKey(name: "swap")
+ final double swap;
+ @JsonKey(name: "egress")
+ final double egress;
+}
+
+@JsonSerializable(createToJson: false)
+@ChainflipCurrencyConverter()
+class ChainflipBoostQuote {
+ const ChainflipBoostQuote({
+ required this.ingressAsset,
+ required this.ingressAmountNative,
+ required this.egressAsset,
+ required this.egressAmountNative,
+ required this.includedFees,
+ required this.lowLiquidityWarning,
+ required this.poolInfo,
+ required this.estimatedDurationSeconds,
+ required this.estimatedDurationsSeconds,
+ required this.estimatedPrice,
+ required this.estimatedBoostFeeBps,
+ this.intermediateAsset,
+ this.intermediateAmountNative,
+ this.numberOfChunks,
+ this.chunkIntervalBlocks,
+ });
+
+ factory ChainflipBoostQuote.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipBoostQuoteFromJson(json);
+
+ @JsonKey(name: "ingressAsset")
+ final CryptoCurrency ingressAsset;
+ @JsonKey(name: "ingressAmountNative")
+ final BigInt ingressAmountNative;
+ @JsonKey(name: "intermediateAsset")
+ final CryptoCurrency? intermediateAsset;
+ @JsonKey(name: "intermediateAmountNative")
+ final BigInt? intermediateAmountNative;
+ @JsonKey(name: "egressAsset")
+ final CryptoCurrency egressAsset;
+ @JsonKey(name: "egressAmountNative")
+ final BigInt egressAmountNative;
+ @JsonKey(name: "includedFees")
+ final List<ChainflipFeeData> includedFees;
+ @JsonKey(name: "lowLiquidityWarning")
+ final bool lowLiquidityWarning;
+ @JsonKey(name: "poolInfo")
+ final List<ChainflipPoolInfo> poolInfo;
+ @JsonKey(name: "estimatedDurationSeconds")
+ final double estimatedDurationSeconds;
+ @JsonKey(name: "estimatedDurationsSeconds")
+ final ChainflipEstimatedDurations estimatedDurationsSeconds;
+ @JsonKey(name: "estimatedPrice")
+ final double estimatedPrice;
+ @JsonKey(name: "estimatedBoostFeeBps")
+ final double estimatedBoostFeeBps;
+ @JsonKey(name: "numberOfChunks")
+ final int? numberOfChunks;
+ @JsonKey(name: "chunkIntervalBlocks")
+ final int? chunkIntervalBlocks;
+}
+
+@JsonSerializable(createToJson: false)
+@ChainflipCurrencyConverter()
+class ChainflipQuote implements Comparable<ChainflipQuote> {
+ const ChainflipQuote({
+ required this.type,
+ required this.ingressAsset,
+ required this.ingressAmountNative,
+ required this.egressAsset,
+ required this.egressAmountNative,
+ required this.includedFees,
+ required this.recommendedSlippageTolerancePercent,
+ required this.lowLiquidityWarning,
+ required this.poolInfo,
+ required this.estimatedDurationSeconds,
+ required this.estimatedDurationsSeconds,
+ required this.estimatedPrice,
+ this.intermediateAsset,
+ this.intermediateAmountNative,
+ this.boostQuote,
+ this.numberOfChunks,
+ this.chunkIntervalBlocks,
+ this.platform,
+ });
+
+ factory ChainflipQuote.fromJson(Map<String, dynamic> json) => _$ChainflipQuoteFromJson(json);
+
+ @JsonKey(name: "type", unknownEnumValue: ChainflipQuoteType.unknown)
+ final ChainflipQuoteType type;
+ @JsonKey(name: "ingressAsset")
+ final CryptoCurrency ingressAsset;
+ @JsonKey(name: "ingressAmountNative")
+ final BigInt ingressAmountNative;
+ @JsonKey(name: "intermediateAsset")
+ final CryptoCurrency? intermediateAsset;
+ @JsonKey(name: "intermediateAmountNative")
+ final BigInt? intermediateAmountNative;
+ @JsonKey(name: "egressAsset")
+ final CryptoCurrency egressAsset;
+ @JsonKey(name: "egressAmountNative")
+ final BigInt egressAmountNative;
+ @JsonKey(name: "includedFees")
+ final List<ChainflipFeeData> includedFees;
+ @JsonKey(name: "recommendedSlippageTolerancePercent")
+ final double recommendedSlippageTolerancePercent;
+ @JsonKey(name: "lowLiquidityWarning")
+ final bool lowLiquidityWarning;
+ @JsonKey(name: "poolInfo")
+ final List<ChainflipPoolInfo> poolInfo;
+ @JsonKey(name: "estimatedDurationSeconds")
+ final double estimatedDurationSeconds;
+ @JsonKey(name: "estimatedDurationsSeconds")
+ final ChainflipEstimatedDurations estimatedDurationsSeconds;
+ @JsonKey(name: "estimatedPrice")
+ final double estimatedPrice;
+ @JsonKey(name: "boostQuote")
+ final ChainflipBoostQuote? boostQuote;
+ @JsonKey(name: "numberOfChunks")
+ final int? numberOfChunks;
+ @JsonKey(name: "chunkIntervalBlocks")
+ final int? chunkIntervalBlocks;
+ @JsonKey(name: "platform")
+ final String? platform;
+
+ @override
+ int compareTo(ChainflipQuote other) => egressAmountNative.compareTo(other.egressAmountNative);
+}
+
+class ChainflipFetchQuotesResponse {
+ const ChainflipFetchQuotesResponse({required this.quotes});
+
+ factory ChainflipFetchQuotesResponse.fromJson(List<dynamic> json) => ChainflipFetchQuotesResponse(
+ quotes: json.map((quote) => ChainflipQuote.fromJson(quote as Map<String, dynamic>)).toList(),
+ );
+
+ final List<ChainflipQuote> quotes;
+}
+
+enum ChainflipAssetDirection {
+ @JsonValue("both")
+ both,
+ @JsonValue("ingress")
+ ingress,
+ @JsonValue("egress")
+ egress,
+ unknown,
+}
+
+enum ChainflipNetwork {
+ @JsonValue("Bitcoin")
+ bitcoin,
+ @JsonValue("Ethereum")
+ ethereum,
+ @JsonValue("Arbitrum")
+ arbitrum,
+ @JsonValue("Solana")
+ solana,
+ @JsonValue("Tron")
+ tron,
+ @JsonValue("Assethub")
+ assethub,
+ unknown,
+}
+
+@JsonSerializable(createToJson: false)
+@ChainflipCurrencyConverter()
+class ChainflipAsset {
+ const ChainflipAsset({
+ required this.enabled,
+ required this.id,
+ required this.direction,
+ required this.ticker,
+ required this.name,
+ required this.network,
+ required this.networkLogo,
+ required this.assetLogo,
+ required this.decimals,
+ required this.minimalAmountNative,
+ required this.usdPriceNative,
+ required this.platforms,
+ this.contractAddress,
+ });
+
+ factory ChainflipAsset.fromJson(Map<String, dynamic> json) => _$ChainflipAssetFromJson(json);
+
+ @JsonKey(name: "enabled")
+ final bool enabled;
+ @JsonKey(name: "id")
+ final CryptoCurrency id;
+ @JsonKey(name: "direction", unknownEnumValue: ChainflipAssetDirection.unknown)
+ final ChainflipAssetDirection direction;
+ @JsonKey(name: "ticker")
+ final String ticker;
+ @JsonKey(name: "name")
+ final String name;
+ @JsonKey(name: "network", unknownEnumValue: ChainflipNetwork.unknown)
+ final ChainflipNetwork network;
+ @JsonKey(name: "contractAddress")
+ final String? contractAddress;
+ @JsonKey(name: "networkLogo")
+ final String networkLogo;
+ @JsonKey(name: "assetLogo")
+ final String assetLogo;
+ @JsonKey(name: "decimals")
+ final int decimals;
+ @JsonKey(name: "minimalAmountNative")
+ final BigInt minimalAmountNative;
+ @JsonKey(name: "usdPriceNative")
+ final BigInt usdPriceNative;
+ @JsonKey(name: "platforms")
+ final List<String> platforms;
+}
+
+class ChainflipAssetsRequest extends ApiRequest<ChainflipAssetsResponse> {
+ const ChainflipAssetsRequest();
+
+ @override
+ String path() => "/assets";
+
+ @override
+ Map<String, dynamic> toJson() => const {};
+
+ @override
+ ChainflipAssetsResponse decode(Object json) =>
+ ChainflipAssetsResponse.fromJson(json as Map<String, dynamic>);
+}
+
+class ChainflipAssetsResponse {
+ const ChainflipAssetsResponse({required this.assets});
+
+ factory ChainflipAssetsResponse.fromJson(Map<String, dynamic> json) {
+ final List<ChainflipAsset> assets = [];
+ for (final asset in json["assets"] as List<dynamic>) {
+ try {
+ assets.add(ChainflipAsset.fromJson(asset as Map<String, dynamic>));
+ } on ArgumentError {
+ // this is bound to happen because chainflip has assets unsupported by cake
+ // we just omit in the deserialization since we can't swap these anyway
+ }
+ }
+ return ChainflipAssetsResponse(assets: assets);
+ }
+
+ final List<ChainflipAsset> assets;
+}
+
+@JsonSerializable()
+@ChainflipCurrencyConverter()
+class ChainflipSwapRequest extends ApiRequest<ChainflipSwapResponse> {
+ const ChainflipSwapRequest({
+ required this.apiKey,
+ required this.sourceAsset,
+ required this.destinationAsset,
+ required this.destinationAddress,
+ required this.minimumPrice,
+ required this.refundAddress,
+ required this.retryDurationInBlocks,
+ required this.commissionBps,
+ this.boostFee,
+ this.numberOfChunks,
+ this.chunkIntervalBlocks,
+ });
+
+ @JsonKey(name: "apiKey")
+ final String apiKey;
+ @JsonKey(name: "sourceAsset")
+ final CryptoCurrency sourceAsset;
+ @JsonKey(name: "destinationAsset")
+ final CryptoCurrency destinationAsset;
+ @JsonKey(name: "destinationAddress")
+ final String destinationAddress;
+ @JsonKey(name: "commissionBps")
+ final String commissionBps;
+ @JsonKey(name: "boostFee", includeIfNull: false)
+ final String? boostFee;
+ @JsonKey(name: "minimumPrice")
+ final String minimumPrice;
+ @JsonKey(name: "refundAddress")
+ final String refundAddress;
+ @IntStringConverter()
+ @JsonKey(name: "retryDurationInBlocks")
+ final int retryDurationInBlocks;
+ @IntStringConverter()
+ @JsonKey(name: "numberOfChunks", includeIfNull: false)
+ final int? numberOfChunks;
+ @IntStringConverter()
+ @JsonKey(name: "chunkIntervalBlocks", includeIfNull: false)
+ final int? chunkIntervalBlocks;
+
+ @override
+ String path() => "/swap";
+
+ @override
+ Map<String, dynamic> toJson() => _$ChainflipSwapRequestToJson(this);
+
+ @override
+ ChainflipSwapResponse decode(Object json) =>
+ ChainflipSwapResponse.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+class ChainflipSwapResponse {
+ const ChainflipSwapResponse({
+ required this.address,
+ required this.issuedBlock,
+ required this.network,
+ required this.channelId,
+ required this.sourceExpiryBlock,
+ required this.explorerUrl,
+ required this.channelOpeningFeeNative,
+ this.id,
+ });
+
+ factory ChainflipSwapResponse.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipSwapResponseFromJson(json);
+
+ @JsonKey(name: "id")
+ final int? id;
+ @JsonKey(name: "address")
+ final String address;
+ @JsonKey(name: "issuedBlock")
+ final int issuedBlock;
+ @JsonKey(name: "network", unknownEnumValue: ChainflipNetwork.unknown)
+ final ChainflipNetwork network;
+ @JsonKey(name: "channelId")
+ final int channelId;
+ @JsonKey(name: "sourceExpiryBlock")
+ final int sourceExpiryBlock;
+ @JsonKey(name: "explorerUrl")
+ final String explorerUrl;
+ @JsonKey(name: "channelOpeningFeeNative")
+ final BigInt channelOpeningFeeNative;
+}
+
+@IntStringConverter()
+@JsonSerializable()
+class ChainflipStatusRequest extends ApiRequest<ChainflipStatusResponse> {
+ const ChainflipStatusRequest({
+ required this.apiKey,
+ required this.issuedBlock,
+ required this.network,
+ required this.channelId,
+ });
+
+ @JsonKey(name: "apiKey")
+ final String apiKey;
+ @JsonKey(name: "issuedBlock")
+ final int issuedBlock;
+ @JsonKey(name: "network")
+ final ChainflipNetwork network;
+ @JsonKey(name: "channelId")
+ final int channelId;
+
+ @override
+ String path() => "/status-by-deposit-channel";
+
+ @override
+ Map<String, dynamic> toJson() => _$ChainflipStatusRequestToJson(this);
+
+ @override
+ ChainflipStatusResponse decode(Object json) =>
+ ChainflipStatusResponse.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+class ChainflipStatusReason {
+ const ChainflipStatusReason({required this.code, required this.message});
+
+ factory ChainflipStatusReason.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipStatusReasonFromJson(json);
+
+ @JsonKey(name: "code")
+ final String code;
+ @JsonKey(name: "message")
+ final String message;
+}
+
+@JsonSerializable(createToJson: false)
+@MillisDateTimeConverter()
+class ChainflipStatusFailure {
+ const ChainflipStatusFailure({
+ required this.failedAt,
+ required this.failedBlockIndex,
+ required this.mode,
+ this.reason,
+ });
+
+ factory ChainflipStatusFailure.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipStatusFailureFromJson(json);
+
+ @JsonKey(name: "failedAt")
+ final DateTime failedAt;
+ @JsonKey(name: "failedBlockIndex")
+ final String failedBlockIndex;
+ @JsonKey(name: "mode")
+ final String mode;
+ @JsonKey(name: "reason")
+ final ChainflipStatusReason? reason;
+}
+
+@JsonSerializable(createToJson: false)
+@MillisDateTimeConverter()
+class ChainflipStatusChunkInfo {
+ const ChainflipStatusChunkInfo({
+ required this.inputAmountNative,
+ required this.scheduledAt,
+ required this.scheduledBlockIndex,
+ required this.retryCount,
+ this.intermediateAmountNative,
+ this.outputAmountNative,
+ this.executedAt,
+ this.executedBlockIndex,
+ });
+
+ factory ChainflipStatusChunkInfo.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipStatusChunkInfoFromJson(json);
+
+ @JsonKey(name: "inputAmountNative")
+ final BigInt inputAmountNative;
+ @JsonKey(name: "intermediateAmountNative")
+ final BigInt? intermediateAmountNative;
+ @JsonKey(name: "outputAmountNative")
+ final BigInt? outputAmountNative;
+ @JsonKey(name: "scheduledAt")
+ final DateTime scheduledAt;
+ @JsonKey(name: "scheduledBlockIndex")
+ final String scheduledBlockIndex;
+ @JsonKey(name: "executedAt")
+ final DateTime? executedAt;
+ @JsonKey(name: "executedBlockIndex")
+ final String? executedBlockIndex;
+ @JsonKey(name: "retryCount")
+ final int retryCount;
+}
+
+@JsonSerializable(createToJson: false)
+class ChainflipStatusDca {
+ const ChainflipStatusDca({
+ required this.executedChunks,
+ required this.remainingChunks,
+ this.lastExecutedChunk,
+ this.currentChunk,
+ });
+
+ factory ChainflipStatusDca.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipStatusDcaFromJson(json);
+
+ @JsonKey(name: "lastExecutedChunk")
+ final ChainflipStatusChunkInfo? lastExecutedChunk;
+ @JsonKey(name: "currentChunk")
+ final ChainflipStatusChunkInfo? currentChunk;
+ @JsonKey(name: "executedChunks")
+ final int executedChunks;
+ @JsonKey(name: "remainingChunks")
+ final int remainingChunks;
+}
+
+@JsonSerializable(createToJson: false)
+class ChainflipStatusAffiliateBroker {
+ const ChainflipStatusAffiliateBroker({required this.account, required this.commissionBps});
+
+ factory ChainflipStatusAffiliateBroker.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipStatusAffiliateBrokerFromJson(json);
+
+ @JsonKey(name: "account")
+ final String account;
+ @JsonKey(name: "commissionBps")
+ final int commissionBps;
+}
+
+@JsonSerializable(createToJson: false)
+class ChainflipStatusFillOrKillParams {
+ const ChainflipStatusFillOrKillParams({
+ required this.retryDurationBlocks,
+ required this.refundAddress,
+ required this.minimumPrice,
+ });
+
+ factory ChainflipStatusFillOrKillParams.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipStatusFillOrKillParamsFromJson(json);
+
+ @JsonKey(name: "retryDurationBlocks")
+ final int retryDurationBlocks;
+ @JsonKey(name: "refundAddress")
+ final String refundAddress;
+
+ // U256 fixed-point encoded price string, not a decimal number.
+ @JsonKey(name: "minimumPrice")
+ final String minimumPrice;
+}
+
+@JsonSerializable(createToJson: false)
+class ChainflipStatusDcaParams {
+ const ChainflipStatusDcaParams({required this.numberOfChunks, required this.chunkIntervalBlocks});
+
+ factory ChainflipStatusDcaParams.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipStatusDcaParamsFromJson(json);
+
+ @JsonKey(name: "numberOfChunks")
+ final int numberOfChunks;
+ @JsonKey(name: "chunkIntervalBlocks")
+ final int chunkIntervalBlocks;
+}
+
+@JsonSerializable(createToJson: false)
+class ChainflipStatusCcmParams {
+ const ChainflipStatusCcmParams({
+ required this.gasBudget,
+ required this.message,
+ this.cfParameters,
+ });
+
+ factory ChainflipStatusCcmParams.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipStatusCcmParamsFromJson(json);
+
+ @JsonKey(name: "gasBudget")
+ final String gasBudget;
+ @JsonKey(name: "message")
+ final String message;
+ @JsonKey(name: "cfParameters")
+ final String? cfParameters;
+}
+
+@JsonSerializable(createToJson: false)
+@MillisDateTimeConverter()
+class ChainflipStatusBoost {
+ const ChainflipStatusBoost({
+ required this.maximumBoostFeeBps,
+ this.effectiveBoostFeeBps,
+ this.boostedAt,
+ this.boostedBlockIndex,
+ this.skippedAt,
+ this.skippedBlockIndex,
+ });
+
+ factory ChainflipStatusBoost.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipStatusBoostFromJson(json);
+
+ @JsonKey(name: "maximumBoostFeeBps")
+ final int maximumBoostFeeBps;
+ @JsonKey(name: "effectiveBoostFeeBps")
+ final int? effectiveBoostFeeBps;
+ @JsonKey(name: "boostedAt")
+ final DateTime? boostedAt;
+ @JsonKey(name: "boostedBlockIndex")
+ final String? boostedBlockIndex;
+ @JsonKey(name: "skippedAt")
+ final DateTime? skippedAt;
+ @JsonKey(name: "skippedBlockIndex")
+ final String? skippedBlockIndex;
+}
+
+@JsonSerializable(createToJson: false)
+@MillisDateTimeConverter()
+class ChainflipStatusDeposit {
+ const ChainflipStatusDeposit({
+ required this.amountNative,
+ this.transactionReference,
+ this.transactionConfirmations,
+ this.witnessedAt,
+ this.witnessedBlockIndex,
+ this.failure,
+ this.failedAt,
+ this.failedBlockIndex,
+ });
+
+ factory ChainflipStatusDeposit.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipStatusDepositFromJson(json);
+
+ @JsonKey(name: "amountNative")
+ final BigInt amountNative;
+ @JsonKey(name: "transactionReference")
+ final String? transactionReference;
+ @JsonKey(name: "transactionConfirmations")
+ final int? transactionConfirmations;
+ @JsonKey(name: "witnessedAt")
+ final DateTime? witnessedAt;
+ @JsonKey(name: "witnessedBlockIndex")
+ final String? witnessedBlockIndex;
+ @JsonKey(name: "failure")
+ final ChainflipStatusFailure? failure;
+ @JsonKey(name: "failedAt")
+ final DateTime? failedAt;
+ @JsonKey(name: "failedBlockIndex")
+ final String? failedBlockIndex;
+}
+
+@JsonSerializable(createToJson: false)
+@MillisDateTimeConverter()
+class ChainflipStatusEgress {
+ const ChainflipStatusEgress({
+ required this.amountNative,
+ this.scheduledAt,
+ this.scheduledBlockIndex,
+ this.transactionReference,
+ this.witnessedAt,
+ this.witnessedBlockIndex,
+ this.failure,
+ this.failedAt,
+ this.failedBlockIndex,
+ });
+
+ factory ChainflipStatusEgress.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipStatusEgressFromJson(json);
+
+ @JsonKey(name: "amountNative")
+ final BigInt amountNative;
+ @JsonKey(name: "scheduledAt")
+ final DateTime? scheduledAt;
+ @JsonKey(name: "scheduledBlockIndex")
+ final String? scheduledBlockIndex;
+ @JsonKey(name: "transactionReference")
+ final String? transactionReference;
+ @JsonKey(name: "witnessedAt")
+ final DateTime? witnessedAt;
+ @JsonKey(name: "witnessedBlockIndex")
+ final String? witnessedBlockIndex;
+ @JsonKey(name: "failure")
+ final ChainflipStatusFailure? failure;
+ @JsonKey(name: "failedAt")
+ final DateTime? failedAt;
+ @JsonKey(name: "failedBlockIndex")
+ final String? failedBlockIndex;
+}
+
+@JsonSerializable(createToJson: false)
+class ChainflipStatusSwap {
+ const ChainflipStatusSwap({
+ required this.originalInputAmountNative,
+ required this.remainingInputAmountNative,
+ required this.swappedInputAmountNative,
+ required this.swappedIntermediateAmountNative,
+ required this.swappedOutputAmountNative,
+ this.regular,
+ this.dca,
+ });
+
+ factory ChainflipStatusSwap.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipStatusSwapFromJson(json);
+
+ @JsonKey(name: "originalInputAmountNative")
+ final BigInt originalInputAmountNative;
+ @JsonKey(name: "remainingInputAmountNative")
+ final BigInt remainingInputAmountNative;
+ @JsonKey(name: "swappedInputAmountNative")
+ final BigInt swappedInputAmountNative;
+ @JsonKey(name: "swappedIntermediateAmountNative")
+ final BigInt swappedIntermediateAmountNative;
+ @JsonKey(name: "swappedOutputAmountNative")
+ final BigInt swappedOutputAmountNative;
+ @JsonKey(name: "regular")
+ final ChainflipStatusChunkInfo? regular;
+ @JsonKey(name: "dca")
+ final ChainflipStatusDca? dca;
+}
+
+@JsonSerializable(createToJson: false)
+@MillisDateTimeConverter()
+class ChainflipStatusDepositChannel {
+ const ChainflipStatusDepositChannel({
+ required this.id,
+ required this.createdAt,
+ required this.brokerCommissionBps,
+ required this.depositAddress,
+ required this.sourceChainExpiryBlock,
+ required this.estimatedExpiryTime,
+ required this.isExpired,
+ required this.openedThroughBackend,
+ this.expectedDepositAmountNative,
+ this.affiliateBrokers,
+ this.fillOrKillParams,
+ this.dcaParams,
+ });
+
+ factory ChainflipStatusDepositChannel.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipStatusDepositChannelFromJson(json);
+
+ @JsonKey(name: "id")
+ final String id;
+ @JsonKey(name: "createdAt")
+ final DateTime createdAt;
+ @JsonKey(name: "brokerCommissionBps")
+ final int brokerCommissionBps;
+ @JsonKey(name: "depositAddress")
+ final String depositAddress;
+ @JsonKey(name: "sourceChainExpiryBlock")
+ final BigInt sourceChainExpiryBlock;
+ @JsonKey(name: "estimatedExpiryTime")
+ final DateTime estimatedExpiryTime;
+ @JsonKey(name: "expectedDepositAmountNative")
+ final BigInt? expectedDepositAmountNative;
+ @JsonKey(name: "isExpired")
+ final bool isExpired;
+ @JsonKey(name: "openedThroughBackend")
+ final bool openedThroughBackend;
+ @JsonKey(name: "affiliateBrokers")
+ final List<ChainflipStatusAffiliateBroker>? affiliateBrokers;
+ @JsonKey(name: "fillOrKillParams")
+ final ChainflipStatusFillOrKillParams? fillOrKillParams;
+ @JsonKey(name: "dcaParams")
+ final ChainflipStatusDcaParams? dcaParams;
+}
+
+@JsonSerializable(createToJson: false)
+@ChainflipCurrencyConverter()
+@MillisDateTimeConverter()
+class ChainflipStatusData {
+ const ChainflipStatusData({
+ required this.state,
+ required this.sourceAsset,
+ required this.destinationAsset,
+ required this.destinationAddress,
+ this.swapId,
+ this.depositChannel,
+ this.ccmParams,
+ this.boost,
+ this.estimatedDurationSeconds,
+ this.sourceChainRequiredBlockConfirmations,
+ this.fees,
+ this.deposit,
+ this.swap,
+ this.swapEgress,
+ this.refundEgress,
+ this.lastStateChainUpdateAt,
+ });
+
+ factory ChainflipStatusData.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipStatusDataFromJson(json);
+
+ @JsonKey(name: "state", unknownEnumValue: ChainflipSwapState.unknown)
+ final ChainflipSwapState state;
+ @JsonKey(name: "swapId")
+ final String? swapId;
+ @JsonKey(name: "sourceAsset")
+ final CryptoCurrency sourceAsset;
+ @JsonKey(name: "destinationAsset")
+ final CryptoCurrency destinationAsset;
+ @JsonKey(name: "destinationAddress")
+ final String destinationAddress;
+ @JsonKey(name: "depositChannel")
+ final ChainflipStatusDepositChannel? depositChannel;
+ @JsonKey(name: "ccmParams")
+ final ChainflipStatusCcmParams? ccmParams;
+ @JsonKey(name: "boost")
+ final ChainflipStatusBoost? boost;
+ @JsonKey(name: "estimatedDurationSeconds")
+ final double? estimatedDurationSeconds;
+ @JsonKey(name: "sourceChainRequiredBlockConfirmations")
+ final int? sourceChainRequiredBlockConfirmations;
+ @JsonKey(name: "fees")
+ final List<ChainflipFeeData>? fees;
+ @JsonKey(name: "deposit")
+ final ChainflipStatusDeposit? deposit;
+ @JsonKey(name: "swap")
+ final ChainflipStatusSwap? swap;
+ @JsonKey(name: "swapEgress")
+ final ChainflipStatusEgress? swapEgress;
+ @JsonKey(name: "refundEgress")
+ final ChainflipStatusEgress? refundEgress;
+ @JsonKey(name: "lastStateChainUpdateAt")
+ final DateTime? lastStateChainUpdateAt;
+}
+
+@JsonSerializable(createToJson: false)
+class ChainflipStatusResponse {
+ const ChainflipStatusResponse({required this.status, this.id});
+
+ factory ChainflipStatusResponse.fromJson(Map<String, dynamic> json) =>
+ _$ChainflipStatusResponseFromJson(json);
+
+ @JsonKey(name: "id")
+ final int? id;
+ @JsonKey(name: "status")
+ final ChainflipStatusData status;
+}
\ No newline at end of file
### lib/exchange/provider/chainflip/chainflip_exchange_provider.dart
@@ -0,0 +1,186 @@
+import "package:cake_wallet/.secrets.g.dart" as secrets;
+import "package:cake_wallet/exchange/exchange_provider_description.dart";
+import "package:cake_wallet/exchange/provider/chainflip/chainflip_api_schema.dart";
+import "package:cake_wallet/exchange/provider/exchange_provider.dart";
+import "package:cake_wallet/exchange/rate_request.dart";
+import "package:cake_wallet/exchange/trade.dart";
+import "package:cake_wallet/exchange/trade_request.dart";
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/exchange/utils/provider_api.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/exchange_limits.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/provider_rate.dart";
+import "package:cake_wallet/utils/list_extension.dart";
+import "package:cw_core/amount/exchange_rate.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/crypto_currency.dart";
+
+class ChainflipExchangeProvider extends LimitsCacheExchangeProvider {
+ ChainflipExchangeProvider({super.proxyWrapper});
+
+ 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,
+ CryptoCurrency.trx,
+ CryptoCurrency.usdttrc20,
+ CryptoCurrency.cbbtc,
+ CryptoCurrency.bnb,
+ CryptoCurrency.usdtbsc,
+ ];
+
+ static const _baseURL = "chainflip-broker.io";
+ static const _affiliateBps = secrets.chainflipAffiliateFee;
+ static const _affiliateKey = secrets.chainflipApiKey;
+
+ late final _api = ProviderApi(
+ proxyWrapper,
+ authority: _baseURL,
+ errorMessage: (json) => (json["detail"] ?? json["title"])?.toString(),
+ );
+
+ @override
+ bool get supportsFixedRate => false;
+
+ @override
+ ExchangeProviderDescription get description => ExchangeProviderDescription.chainflip;
+
+ @override
+ Future<ExchangeLimits> fetchLimits({
+ required CryptoCurrency from,
+ required CryptoCurrency to,
+ required bool isFixedRateMode,
+ }) async {
+ if (!_supported.contains(from) || !_supported.contains(to)) {
+ throw Exception("No rates found for $from to $to");
+ }
+
+ final assetsResponse = await _api.send(const ChainflipAssetsRequest());
+
+ final asset = assetsResponse.assets.firstWhere((item) => item.id == from);
+ final minAmount = Money(asset.minimalAmountNative, from);
+
+ if (minAmount.isZero) {
+ throw Exception("No rates found for $from to $to");
+ }
+
+ return ExchangeLimits(min: minAmount);
+ }
+
+ @override
+ Future<ProviderRate> fetchRate(RateRequest request) async {
+ if (request is! FloatingRateRequest) {
+ throw Exception("fixed rate unsupported");
+ }
+
+ if (!_supported.contains(request.depositCurrency) || !_supported.contains(request.payoutCurrency)) {
+ throw Exception("unsupported");
+ }
+
+ final quoteParams = ChainflipFetchQuotesRequest(
+ apiKey: _affiliateKey,
+ sourceAsset: request.depositCurrency,
+ destinationAsset: request.payoutCurrency,
+ amount: request.depositAmount.amount,
+ commissionBps: _affiliateBps,
+ );
+
+ final bestQuote = (await _api.send(quoteParams)).quotes.max;
+
+ return ProviderRate(
+ provider: description,
+ rate: ExchangeRate.fromAmounts(
+ request.depositAmount,
+ Money(bestQuote.egressAmountNative, request.payoutCurrency),
+ ),
+ limits: await getLimits(
+ from: request.depositCurrency,
+ to: request.payoutCurrency,
+ isFixedRateMode: false,
+ ),
+ );
+ }
+
+ @override
+ Future<Trade> createTrade({required TradeRequest request}) async {
+ const maxSlippage = 2;
+
+ final quoteParams = ChainflipFetchQuotesRequest(
+ apiKey: _affiliateKey,
+ sourceAsset: request.depositCurrency,
+ destinationAsset: request.payoutCurrency,
+ amount: request.depositAmount.amount,
+ commissionBps: _affiliateBps,
+ );
+
+ final quote = (await _api.send(quoteParams)).quotes.max;
+ final estimatedPrice = quote.estimatedPrice;
+ final minimumPrice = estimatedPrice * (100 - maxSlippage) / 100;
+
+ final swapParams = ChainflipSwapRequest(
+ apiKey: _affiliateKey,
+ sourceAsset: request.depositCurrency,
+ destinationAsset: request.payoutCurrency,
+ destinationAddress: request.payoutAddress,
+ minimumPrice: minimumPrice.toString(),
+ refundAddress: request.refundAddress,
+ retryDurationInBlocks: 150,
+ commissionBps: _affiliateBps,
+ numberOfChunks: quote.numberOfChunks,
+ chunkIntervalBlocks: quote.chunkIntervalBlocks,
+ );
+
+ final swapResponse = await _api.send(swapParams);
+
+ return Trade(
+ id: "${swapResponse.issuedBlock}-${swapResponse.network.name}-${swapResponse.channelId}",
+ provider: description,
+ createdAt: DateTime.now(),
+ state: TradeState.waiting,
+ depositAmount: request.depositAmount,
+ payoutAmount: request.payoutAmount,
+ fundingAddress: swapResponse.address,
+ payoutAddress: request.payoutAddress,
+ refundAddress: request.refundAddress,
+ );
+ }
+
+ @override
+ Future<Trade> updateTrade(Trade trade) async {
+ final channelParts = trade.id.split("-");
+ final network = channelParts[1];
+ final normalizedNetwork = network.toLowerCase();
+
+ final statusParams = ChainflipStatusRequest(
+ apiKey: _affiliateKey,
+ issuedBlock: int.parse(channelParts[0]),
+ network: ChainflipNetwork.values.byName(normalizedNetwork),
+ channelId: int.parse(channelParts[2]),
+ );
+
+ final statusResponse = await _api.send(
+ statusParams,
+ mapError: (e) => switch (e.statusCode) {
+ 404 => Exception("Trade not found for id: ${trade.id}"),
+ _ => null,
+ },
+ );
+
+ return trade.copyWith(
+ state: statusResponse.status.state.toState,
+ outputTransaction: statusResponse.status.swapEgress?.transactionReference,
+ isRefund: statusResponse.status.refundEgress != null,
+ fundingAddress: statusResponse.status.depositChannel?.depositAddress,
+ payoutAddress: statusResponse.status.destinationAddress,
+ );
+
+ }
+}
### lib/exchange/provider/chainflip_exchange_provider.dart
@@ -1,456 +0,0 @@
-import 'dart:convert';
-import 'dart:math';
-
-import 'package:cake_wallet/.secrets.g.dart' as secrets;
-import "package:cake_wallet/exchange/exchange_exceptions.dart";
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/limits.dart';
-import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
-import 'package:cake_wallet/exchange/trade.dart';
-import 'package:cake_wallet/exchange/trade_request.dart';
-import 'package:cake_wallet/exchange/trade_state.dart';
-import 'package:cw_core/amount_converter.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:cake_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,
- CryptoCurrency.trx,
- CryptoCurrency.usdttrc20,
- CryptoCurrency.cbbtc,
- CryptoCurrency.bnb,
- CryptoCurrency.usdtbsc,
- ];
-
- 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
- bool get supportsMemoOrDestinationTag => 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 RateNotFoundException(from, to, provider: description);
- }
-
- 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 RateNotFoundException(from, to, provider: description);
-
- return Limits(min: _amountFromNative(minAmount.toString(), from));
- } on ExchangeProviderResponseException {
- rethrow;
- } catch (e) {
- printV(e.toString());
- throw ExchangeProviderResponseException('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(_amountString(amount, from), 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(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 TradeNotFoundException(id, provider: description);
-
- 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) {
- // Chainflip uses 'tron' as the network slug, but Cake uses tag 'TRX' (and null
- // for native TRX), so these can't go through the generic title.tag logic below.
- if (currency == CryptoCurrency.trx) return 'trx.tron';
- if (currency == CryptoCurrency.usdttrc20) return 'usdt.tron';
-
- 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',
- 'TRON' => 'Tron',
- _ => 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,
- 'cbbtc.eth' => CryptoCurrency.cbbtc,
- 'sol.sol' => CryptoCurrency.sol,
- 'usdc.sol' => CryptoCurrency.usdcsol,
- 'usdt.sol' => CryptoCurrency.usdtSol,
- 'eth.arb' => CryptoCurrency.arbEth,
- 'usdc.arb' => CryptoCurrency.usdcArb,
- 'usdt.arb' => CryptoCurrency.usdtArb,
- 'trx.tron' => CryptoCurrency.trx,
- 'usdt.tron' => CryptoCurrency.usdttrc20,
- 'bnb.bsc' => CryptoCurrency.bnb,
- 'usdt.bsc' => CryptoCurrency.usdtbsc,
- _ => null
- };
-
- return currency;
- }
-
- String _amountToNative(String amount, CryptoCurrency currency) =>
- AmountConverter.toBaseUnits(amount, currency.decimals);
-
- String _amountString(double amount, CryptoCurrency currency) {
- final text = amount.toString();
- return text.contains('e') || text.contains('E')
- ? amount.toStringAsFixed(currency.decimals)
- : text;
- }
-
- 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 ExchangeProviderResponseException('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 ExchangeProviderResponseCodeException('Unexpected response: ${response.statusCode} / ${uri.toString()} / ${response.body}', response.statusCode);
- }
-
- 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 ExchangeProviderResponseCodeException('Unexpected response: ${response.statusCode} / ${uri.toString()} / ${response.body}', response.statusCode);
- }
-
- 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;
- }
-}
### lib/exchange/provider/changenow/changenow_api_schema.dart
@@ -0,0 +1,504 @@
+// spec reference: https://documenter.getpostman.com/view/8180765/SVfTPnM8?version=latest
+
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/exchange/utils/json_converters.dart";
+import "package:cake_wallet/exchange/utils/provider_api.dart";
+import "package:json_annotation/json_annotation.dart";
+
+part "changenow_api_schema.g.dart";
+
+enum ChangeNowFlow {
+ @JsonValue("standard")
+ standard,
+ @JsonValue("fixed-rate")
+ fixedRate,
+ unknown,
+}
+
+enum ChangeNowExchangeType {
+ @JsonValue("direct")
+ direct,
+ @JsonValue("reverse")
+ reverse,
+ unknown,
+}
+
+
+@JsonSerializable()
+class ChangeNowErrorResponse {
+ const ChangeNowErrorResponse({required this.error, required this.message});
+
+ factory ChangeNowErrorResponse.fromJson(Map<String, dynamic> json) =>
+ _$ChangeNowErrorResponseFromJson(json);
+
+ @JsonKey(name: "error")
+ final String error;
+
+ @JsonKey(name: "message")
+ final String message;
+}
+
+
+@JsonSerializable()
+class ChangeNowRangeRequest extends ApiRequest<ChangeNowRangeResponse> {
+ const ChangeNowRangeRequest({
+ required this.fromCurrency,
+ required this.toCurrency,
+ required this.fromNetwork,
+ required this.toNetwork,
+ required this.flow,
+ });
+
+ @JsonKey(name: "fromCurrency")
+ final String fromCurrency;
+ @JsonKey(name: "toCurrency")
+ final String toCurrency;
+ @JsonKey(name: "fromNetwork")
+ final String fromNetwork;
+ @JsonKey(name: "toNetwork")
+ final String toNetwork;
+ @JsonKey(name: "flow")
+ final ChangeNowFlow flow;
+
+ @override
+ String path() => "/v2/exchange/range";
+
+ @override
+ Map<String, dynamic> toJson() => _$ChangeNowRangeRequestToJson(this);
+
+ @override
+ ChangeNowRangeResponse decode(Object json) =>
+ ChangeNowRangeResponse.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+class ChangeNowRangeResponse {
+ const ChangeNowRangeResponse({
+ required this.fromCurrency,
+ required this.fromNetwork,
+ required this.toCurrency,
+ required this.toNetwork,
+ required this.flow,
+ this.minAmount,
+ this.maxAmount,
+ });
+
+ factory ChangeNowRangeResponse.fromJson(Map<String, dynamic> json) =>
+ _$ChangeNowRangeResponseFromJson(json);
+
+ @JsonKey(name: "fromCurrency")
+ final String fromCurrency;
+ @JsonKey(name: "fromNetwork")
+ final String fromNetwork;
+ @JsonKey(name: "toCurrency")
+ final String toCurrency;
+ @JsonKey(name: "toNetwork")
+ final String toNetwork;
+ @JsonKey(name: "flow", unknownEnumValue: ChangeNowFlow.unknown)
+ final ChangeNowFlow flow;
+ @JsonKey(name: "minAmount")
+ final double? minAmount;
+ @JsonKey(name: "maxAmount")
+ final double? maxAmount;
+}
+
+
+@JsonSerializable()
+class ChangeNowEstimatedAmountRequest extends ApiRequest<ChangeNowEstimatedAmountResponse> {
+ const ChangeNowEstimatedAmountRequest({
+ required this.fromCurrency,
+ required this.toCurrency,
+ required this.fromNetwork,
+ required this.toNetwork,
+ required this.flow,
+ required this.type,
+ this.fromAmount,
+ this.toAmount,
+ this.useRateId,
+ });
+
+ @JsonKey(name: "fromCurrency")
+ final String fromCurrency;
+ @JsonKey(name: "toCurrency")
+ final String toCurrency;
+ @JsonKey(name: "fromNetwork")
+ final String fromNetwork;
+ @JsonKey(name: "toNetwork")
+ final String toNetwork;
+ @JsonKey(name: "flow")
+ final ChangeNowFlow flow;
+ @JsonKey(name: "type")
+ final ChangeNowExchangeType type;
+ @JsonKey(name: "fromAmount", includeIfNull: false)
+ final String? fromAmount;
+ @JsonKey(name: "toAmount", includeIfNull: false)
+ final String? toAmount;
+ @JsonKey(name: "useRateId", includeIfNull: false)
+ final String? useRateId;
+
+ @override
+ String path() => "/v2/exchange/estimated-amount";
+
+ @override
+ Map<String, dynamic> toJson() => _$ChangeNowEstimatedAmountRequestToJson(this);
+
+ @override
+ ChangeNowEstimatedAmountResponse decode(Object json) =>
+ ChangeNowEstimatedAmountResponse.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+class ChangeNowEstimatedAmountResponse {
+ const ChangeNowEstimatedAmountResponse({
+ required this.fromCurrency,
+ required this.fromNetwork,
+ required this.toCurrency,
+ required this.toNetwork,
+ required this.flow,
+ required this.type,
+ required this.fromAmount,
+ required this.toAmount,
+ this.rateId,
+ this.validUntil,
+ this.transactionSpeedForecast,
+ this.warningMessage,
+ this.depositFee,
+ this.withdrawalFee,
+ this.userId,
+ });
+
+ factory ChangeNowEstimatedAmountResponse.fromJson(Map<String, dynamic> json) =>
+ _$ChangeNowEstimatedAmountResponseFromJson(json);
+
+ @JsonKey(name: "fromCurrency")
+ final String? fromCurrency;
+ @JsonKey(name: "fromNetwork")
+ final String? fromNetwork;
+ @JsonKey(name: "toCurrency")
+ final String? toCurrency;
+ @JsonKey(name: "toNetwork")
+ final String? toNetwork;
+ @JsonKey(name: "flow", unknownEnumValue: ChangeNowFlow.unknown)
+ final ChangeNowFlow? flow;
+ @JsonKey(name: "type", unknownEnumValue: ChangeNowExchangeType.unknown)
+ final ChangeNowExchangeType? type;
+ @JsonKey(name: "rateId")
+ final String? rateId;
+ @JsonKey(name: "validUntil")
+ final DateTime? validUntil;
+ @JsonKey(name: "transactionSpeedForecast")
+ final String? transactionSpeedForecast;
+ @JsonKey(name: "warningMessage")
+ final String? warningMessage;
+ @JsonKey(name: "depositFee")
+ final double? depositFee;
+ @JsonKey(name: "withdrawalFee")
+ final double? withdrawalFee;
+ @JsonKey(name: "userId")
+ final String? userId;
+ @JsonKey(name: "fromAmount")
+ final double fromAmount;
+ @JsonKey(name: "toAmount")
+ final double toAmount;
+}
+
+@JsonSerializable()
+class ChangeNowCreateExchangePayload {
+ const ChangeNowCreateExchangePayload({
+ required this.app,
+ required this.device,
+ required this.distribution,
+ required this.version,
+ });
+
+ factory ChangeNowCreateExchangePayload.fromJson(Map<String, dynamic> json) =>
+ _$ChangeNowCreateExchangePayloadFromJson(json);
+
+ @JsonKey(name: "app")
+ final String app;
+ @JsonKey(name: "device")
+ final String device;
+ @JsonKey(name: "distribution")
+ final String distribution;
+ @JsonKey(name: "version")
+ final int version;
+
+ Map<String, dynamic> toJson() => _$ChangeNowCreateExchangePayloadToJson(this);
+}
+
+@JsonSerializable(explicitToJson: true)
+class ChangeNowCreateExchangeRequest extends ApiRequest<ChangeNowCreateExchangeResponse> {
+ const ChangeNowCreateExchangeRequest({
+ required this.fromCurrency,
+ required this.toCurrency,
+ required this.fromNetwork,
+ required this.toNetwork,
+ required this.address,
+ required this.flow,
+ required this.type,
+ this.fromAmount,
+ this.toAmount,
+ this.extraId,
+ this.refundAddress,
+ this.refundExtraId,
+ this.userId,
+ this.payload,
+ this.contactEmail,
+ this.source,
+ this.rateId,
+ }) : super.post();
+
+ @JsonKey(name: "fromCurrency")
+ final String fromCurrency;
+ @JsonKey(name: "toCurrency")
+ final String toCurrency;
+ @JsonKey(name: "fromNetwork")
+ final String fromNetwork;
+ @JsonKey(name: "toNetwork")
+ final String toNetwork;
+ @JsonKey(name: "address")
+ final String address;
+ @JsonKey(name: "flow")
+ final ChangeNowFlow flow;
+ @JsonKey(name: "type")
+ final ChangeNowExchangeType type;
+ @JsonKey(name: "fromAmount", includeIfNull: false)
+ final String? fromAmount;
+ @JsonKey(name: "toAmount", includeIfNull: false)
+ final String? toAmount;
+ @JsonKey(name: "extraId", includeIfNull: false)
+ final String? extraId;
+ @JsonKey(name: "refundAddress", includeIfNull: false)
+ final String? refundAddress;
+ @JsonKey(name: "refundExtraId", includeIfNull: false)
+ final String? refundExtraId;
+ @JsonKey(name: "userId", includeIfNull: false)
+ final String? userId;
+ @JsonKey(name: "payload", includeIfNull: false)
+ final ChangeNowCreateExchangePayload? payload;
+ @JsonKey(name: "contactEmail", includeIfNull: false)
+ final String? contactEmail;
+ @JsonKey(name: "source", includeIfNull: false)
+ final String? source;
+ @JsonKey(name: "rateId", includeIfNull: false)
+ final String? rateId;
+
+ @override
+ String path() => "/v2/exchange";
+
+ @override
+ Map<String, dynamic> toJson() => _$ChangeNowCreateExchangeRequestToJson(this);
+
+ @override
+ ChangeNowCreateExchangeResponse decode(Object json) =>
+ ChangeNowCreateExchangeResponse.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+class ChangeNowCreateExchangeResponse {
+ const ChangeNowCreateExchangeResponse({
+ required this.fromAmount,
+ required this.toAmount,
+ required this.flow,
+ required this.type,
+ required this.payinAddress,
+ required this.payoutAddress,
+ required this.fromCurrency,
+ required this.toCurrency,
+ required this.id,
+ required this.fromNetwork,
+ required this.toNetwork,
+ this.refundAddress,
+ this.payinExtraId,
+ this.payoutExtraId,
+ this.validUntil,
+ });
+
+ factory ChangeNowCreateExchangeResponse.fromJson(Map<String, dynamic> json) =>
+ _$ChangeNowCreateExchangeResponseFromJson(json);
+
+ @JsonKey(name: "fromAmount")
+ final double fromAmount;
+ @JsonKey(name: "toAmount")
+ final double toAmount;
+ @JsonKey(name: "flow", unknownEnumValue: ChangeNowFlow.unknown)
+ final ChangeNowFlow flow;
+ @JsonKey(name: "type", unknownEnumValue: ChangeNowExchangeType.unknown)
+ final ChangeNowExchangeType type;
+ @JsonKey(name: "payinAddress")
+ final String payinAddress;
+ @JsonKey(name: "payoutAddress")
+ final String payoutAddress;
+ @JsonKey(name: "fromCurrency")
+ final String fromCurrency;
+ @JsonKey(name: "toCurrency")
+ final String toCurrency;
+ @JsonKey(name: "refundAddress")
+ final String? refundAddress;
+ @JsonKey(name: "id")
+ final String id;
+ @JsonKey(name: "fromNetwork")
+ final String fromNetwork;
+ @JsonKey(name: "toNetwork")
+ final String toNetwork;
+ @JsonKey(name: "payinExtraId")
+ final String? payinExtraId;
+ @JsonKey(name: "payoutExtraId")
+ final String? payoutExtraId;
+ @JsonKey(name: "validUntil")
+ final DateTime? validUntil;
+}
+
+
+@JsonSerializable()
+class ChangeNowByIdRequest extends ApiRequest<ChangeNowTransactionResponse> {
+ const ChangeNowByIdRequest({required this.id});
+
+ @JsonKey(name: "id")
+ final String id;
+
+ @override
+ String path() => "/v2/exchange/by-id";
+
+ @override
+ Map<String, dynamic> toJson() => _$ChangeNowByIdRequestToJson(this);
+
+ @override
+ ChangeNowTransactionResponse decode(Object json) =>
+ ChangeNowTransactionResponse.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+@TradeStateConverter()
+class ChangeNowRelatedExchangeInfo {
+ const ChangeNowRelatedExchangeInfo({
+ required this.id,
+ required this.status,
+ required this.createdAt,
+ this.fromCurrency,
+ this.fromNetwork,
+ this.amountFrom,
+ this.amountTo,
+ });
+
+ factory ChangeNowRelatedExchangeInfo.fromJson(Map<String, dynamic> json) =>
+ _$ChangeNowRelatedExchangeInfoFromJson(json);
+
+ @JsonKey(name: "id")
+ final String id;
+ @JsonKey(name: "status")
+ final TradeState status;
+ @JsonKey(name: "createdAt")
+ final DateTime createdAt;
+ @JsonKey(name: "fromCurrency")
+ final String? fromCurrency;
+ @JsonKey(name: "fromNetwork")
+ final String? fromNetwork;
+ @JsonKey(name: "amountFrom")
+ final double? amountFrom;
+ @JsonKey(name: "amountTo")
+ final double? amountTo;
+}
+
+@JsonSerializable(createToJson: false)
+@TradeStateConverter()
+class ChangeNowTransactionResponse {
+ const ChangeNowTransactionResponse({
+ required this.id,
+ required this.status,
+ required this.fromCurrency,
+ required this.toCurrency,
+ required this.payinAddress,
+ required this.payoutAddress,
+ required this.createdAt,
+ this.actionsAvailable,
+ this.fromNetwork,
+ this.toNetwork,
+ this.expectedAmountFrom,
+ this.expectedAmountTo,
+ this.amountFrom,
+ this.amountTo,
+ this.payinExtraId,
+ this.payoutExtraId,
+ this.refundAddress,
+ this.refundExtraId,
+ this.updatedAt,
+ this.validUntil,
+ this.depositReceivedAt,
+ this.payinHash,
+ this.payoutHash,
+ this.fromLegacyTicker,
+ this.toLegacyTicker,
+ this.refundHash,
+ this.refundAmount,
+ this.userId,
+ });
+
+ factory ChangeNowTransactionResponse.fromJson(Map<String, dynamic> json) =>
+ _$ChangeNowTransactionResponseFromJson(json);
+
+ @JsonKey(name: "id")
+ final String id;
+ @JsonKey(name: "status")
+ final TradeState status;
+ @JsonKey(name: "actionsAvailable")
+ final bool? actionsAvailable;
+ @JsonKey(name: "fromCurrency")
+ final String fromCurrency;
+ @JsonKey(name: "fromNetwork")
+ final String? fromNetwork;
+ @JsonKey(name: "toCurrency")
+ final String toCurrency;
+ @JsonKey(name: "toNetwork")
+ final String? toNetwork;
+ @JsonKey(name: "expectedAmountFrom")
+ final double? expectedAmountFrom;
+ @JsonKey(name: "expectedAmountTo")
+ final double? expectedAmountTo;
+ @JsonKey(name: "amountFrom")
+ final double? amountFrom;
+ @JsonKey(name: "amountTo")
+ final double? amountTo;
+ @JsonKey(name: "payinAddress")
+ final String payinAddress;
+ @JsonKey(name: "payoutAddress")
+ final String payoutAddress;
+ @JsonKey(name: "payinExtraId")
+ final String? payinExtraId;
+ @JsonKey(name: "payoutExtraId")
+ final String? payoutExtraId;
+ @JsonKey(name: "refundAddress")
+ final String? refundAddress;
+ @JsonKey(name: "refundExtraId")
+ final String? refundExtraId;
+ @JsonKey(name: "createdAt")
+ final DateTime createdAt;
+ @JsonKey(name: "updatedAt")
+ final DateTime? updatedAt;
+ @JsonKey(name: "validUntil")
+ final DateTime? validUntil;
+ @JsonKey(name: "depositReceivedAt")
+ final DateTime? depositReceivedAt;
+ @JsonKey(name: "payinHash")
+ final String? payinHash;
+ @JsonKey(name: "payoutHash")
+ final String? payoutHash;
+ @JsonKey(name: "fromLegacyTicker")
+ final String? fromLegacyTicker;
+ @JsonKey(name: "toLegacyTicker")
+ final String? toLegacyTicker;
+ @JsonKey(name: "refundHash")
+ final String? refundHash;
+ @JsonKey(name: "refundAmount")
+ final double? refundAmount;
+ @JsonKey(name: "userId")
+ final String? userId;
+ // these are present in the schema but in the examples they're null
+ // we don't use them anyway so i don't care
+ // @JsonKey(name: "originalExchangeInfo")
+ // final ChangeNowRelatedExchangeInfo? originalExchangeInfo;
+ // @JsonKey(name: "relatedExchangesInfo")
+ // final List<ChangeNowRelatedExchangeInfo>? relatedExchangesInfo;
+ // @JsonKey(name: "repeatedExchangesInfo")
+ // final List<ChangeNowRelatedExchangeInfo>? repeatedExchangesInfo;
+}
### lib/exchange/provider/changenow/changenow_exchange_provider.dart
@@ -0,0 +1,219 @@
+import "dart:io";
+
+import "package:cake_wallet/.secrets.g.dart" as secrets;
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
+import "package:cake_wallet/exchange/exchange_provider_description.dart";
+import "package:cake_wallet/exchange/provider/changenow/changenow_api_schema.dart";
+import "package:cake_wallet/exchange/provider/exchange_provider.dart";
+import "package:cake_wallet/exchange/rate_request.dart";
+import "package:cake_wallet/exchange/trade.dart";
+import "package:cake_wallet/exchange/trade_request.dart";
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/exchange/utils/provider_api.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/exchange_limits.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/provider_rate.dart";
+import "package:cake_wallet/store/settings_store.dart";
+import "package:cake_wallet/utils/distribution_info.dart";
+import "package:cake_wallet/wallet_type_utils.dart";
+import "package:cw_core/amount/exchange_rate.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/amount/money_double.dart";
+import "package:cw_core/crypto_currency.dart";
+
+class ChangeNowExchangeProvider extends LimitsCacheExchangeProvider {
+ ChangeNowExchangeProvider({required SettingsStore settingsStore, super.proxyWrapper})
+ : _settingsStore = settingsStore,
+ _lastUsedRateId = "";
+
+ static final apiKey = isMoneroOnly
+ ? secrets.changeNowMoneroApiKey
+ : secrets.changeNowCakeWalletApiKey;
+ static const apiAuthority = "api.changenow.io";
+ static const apiHeaderKey = "x-changenow-api-key";
+
+ final SettingsStore _settingsStore;
+ String _lastUsedRateId;
+
+ late final _api = ProviderApi(
+ proxyWrapper,
+ authority: apiAuthority,
+ headers: {apiHeaderKey: apiKey},
+ errorMessage: (json) => json["message"]?.toString(),
+ );
+
+ @override
+ bool get supportsFixedRate => true;
+
+ @override
+ ExchangeProviderDescription get description => ExchangeProviderDescription.changeNow;
+
+ @override
+ Future<ExchangeLimits> fetchLimits({
+ required CryptoCurrency from,
+ required CryptoCurrency to,
+ required bool isFixedRateMode,
+ }) async {
+ if (from.title == "USDC" && from.tag == "POLY") {
+ throw Exception("Only Bridged USDC (USDC.e) is allowed in ChangeNow");
+ }
+
+ final responseData = await _api.send(
+ ChangeNowRangeRequest(
+ fromCurrency: _normalizeCurrency(from),
+ toCurrency: _normalizeCurrency(to),
+ fromNetwork: _networkFor(from),
+ toNetwork: _networkFor(to),
+ flow: isFixedRateMode ? ChangeNowFlow.fixedRate : ChangeNowFlow.standard,
+ ),
+ );
+ if (responseData.maxAmount == 0) {
+ return ExchangeLimits();
+ }
+ return ExchangeLimits(
+ min: Money.trySafeParse(responseData.minAmount, from),
+ max: Money.trySafeParse(responseData.maxAmount, from),
+ );
+ }
+
+ @override
+ Future<ProviderRate> fetchRate(RateRequest request) async {
+ if (request.amount.isZero) {
+ throw Exception("cannot fetch rate with zero amount");
+ }
+
+ final (fromAmount, toAmount) = switch (request) {
+ FloatingRateRequest(:final depositAmount) => (depositAmount.toString(), null),
+ FixedRateRequest(:final payoutAmount) => (null, payoutAmount.toString()),
+ };
+
+ final responseData = await _api.send(
+ ChangeNowEstimatedAmountRequest(
+ fromCurrency: _normalizeCurrency(request.depositCurrency),
+ toCurrency: _normalizeCurrency(request.payoutCurrency),
+ fromAmount: fromAmount,
+ toAmount: toAmount,
+ fromNetwork: _networkFor(request.depositCurrency),
+ toNetwork: _networkFor(request.payoutCurrency),
+ flow: request is FixedRateRequest ? ChangeNowFlow.fixedRate : ChangeNowFlow.standard,
+ type: request is FixedRateRequest ? ChangeNowExchangeType.reverse : ChangeNowExchangeType.direct,
+ useRateId: request is FixedRateRequest ? "true" : null,
+ ),
+ );
+
+ if (responseData.rateId?.isNotEmpty ?? false) {
+ _lastUsedRateId = responseData.rateId!;
+ }
+
+ return ProviderRate(
+ provider: description,
+ rate: ExchangeRate.fromAmounts(
+ responseData.fromAmount.toMoney(request.depositCurrency),
+ responseData.toAmount.toMoney(request.payoutCurrency),
+ ),
+ limits: await getLimits(
+ from: request.depositCurrency,
+ to: request.payoutCurrency,
+ isFixedRateMode: request is FixedRateRequest,
+ ),
+ );
+ }
+
+ @override
+ Future<Trade> createTrade({required TradeRequest request}) async {
+ final distributionPath = await DistributionInfo.instance.getDistributionPath();
+ final formattedAppVersion = int.tryParse(_settingsStore.appVersion.replaceAll(".", "")) ?? 0;
+ final payload = ChangeNowCreateExchangePayload(
+ app: isMoneroOnly ? "monerocom" : "cakewallet",
+ device: Platform.operatingSystem,
+ distribution: distributionPath,
+ version: formattedAppVersion,
+ );
+
+ if (request.isFixedRate) {
+ // 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(request.rateRequest);
+ }
+ final responseJSON = await _api.send(ChangeNowCreateExchangeRequest(
+ fromCurrency: _normalizeCurrency(request.depositCurrency),
+ toCurrency: _normalizeCurrency(request.payoutCurrency),
+ fromNetwork: _networkFor(request.depositCurrency),
+ toNetwork: _networkFor(request.payoutCurrency),
+ fromAmount: request.isFixedRate ? null : request.depositAmount.toString(),
+ toAmount: request.isFixedRate ? request.payoutAmount.toString() : null,
+ address: request.payoutInvoice ?? request.payoutAddress,
+ refundAddress: request.refundInvoice ?? request.refundAddress,
+ extraId: request.toAddressExtraId,
+ flow: request.isFixedRate ? ChangeNowFlow.fixedRate : ChangeNowFlow.standard,
+ type: request.isFixedRate ? ChangeNowExchangeType.reverse : ChangeNowExchangeType.direct,
+ payload: payload,
+ rateId: request.isFixedRate ? _lastUsedRateId : null,
+ ));
+
+ return Trade(
+ id: responseJSON.id,
+ provider: description,
+ fundingAddress: responseJSON.payinAddress,
+ refundAddress: request.refundAddress,
+ extraId: responseJSON.payinExtraId,
+ createdAt: DateTime.now(),
+ state: TradeState.created,
+ toAddressExtraId: request.toAddressExtraId,
+ depositAmount: responseJSON.fromAmount.toMoney(request.depositCurrency),
+ payoutAmount: responseJSON.toAmount.toMoney(request.payoutCurrency),
+ payoutAddress: request.payoutAddress,
+ );
+ }
+
+ @override
+ Future<Trade> updateTrade(Trade trade) async {
+ final responseJSON = await _api.send(
+ ChangeNowByIdRequest(id: trade.id),
+ mapError: (e) => switch (e.statusCode) {
+ 404 => TradeNotFoundException(trade.id, provider: description),
+ 400 => TradeNotFoundException(trade.id, provider: description, description: e.message),
+ _ => null,
+ },
+ );
+
+ return trade.copyWith(
+ state: responseJSON.status,
+ createdAt: responseJSON.createdAt,
+ expiredAt: responseJSON.validUntil,
+ extraId: responseJSON.payinExtraId,
+ outputTransaction: responseJSON.payoutHash,
+ depositAmount: responseJSON.amountFrom == null ? null : Money.safeParse(responseJSON.amountFrom, trade.depositCurrency),
+ payoutAmount: responseJSON.amountTo == null ? null : Money.safeParse(responseJSON.amountTo, trade.payoutCurrency)
+ );
+ }
+
+ String _networkFor(CryptoCurrency currency) =>
+ currency.tag != null ? _normalizeTag(currency.tag!) : _normalizeTitleToNetwork(currency.title);
+
+ String _normalizeTitleToNetwork(String title) => switch (title.toUpperCase()) {
+ "XNO" => "nano",
+ "ARB" => "arbitrum",
+ _ => title.toLowerCase(),
+ };
+
+ String _normalizeCurrency(CryptoCurrency currency) =>
+ currency == CryptoCurrency.maticpoly ? "matic" : currency.title;
+
+ String _normalizeTag(String tag) {
+ switch (tag) {
+ case "POLY":
+ case "POL":
+ return "matic";
+ case "LN":
+ return "lightning";
+ case "AVAXC":
+ return "cchain";
+ case "ARB":
+ return "arbitrum";
+ case "ROB":
+ return "hood";
+ default:
+ return tag.toLowerCase();
+ }
+ }
+}
### lib/exchange/provider/changenow_exchange_provider.dart
@@ -1,376 +0,0 @@
-import 'dart:convert';
-import 'dart:io';
-
-import 'package:cake_wallet/.secrets.g.dart' as secrets;
-import "package:cake_wallet/exchange/exchange_exceptions.dart";
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/limits.dart';
-import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
-import 'package:cake_wallet/exchange/trade.dart';
-import 'package:cake_wallet/exchange/trade_not_found_exception.dart';
-import 'package:cake_wallet/exchange/trade_request.dart';
-import 'package:cake_wallet/exchange/trade_state.dart';
-import 'package:cake_wallet/store/settings_store.dart';
-import 'package:cake_wallet/utils/distribution_info.dart';
-import 'package:cw_core/utils/proxy_wrapper.dart';
-import 'package:cake_wallet/wallet_type_utils.dart';
-import 'package:cw_core/crypto_currency.dart';
-import 'package:cw_core/utils/print_verbose.dart';
-import 'package:cake_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 ExchangeProviderResponseCodeException('${error}\n$message', response.statusCode);
- }
-
- if (response.statusCode != 200)
- throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', 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,
- if (request.toAddressExtraId.isNotEmpty) 'extraId': request.toAddressExtraId,
- '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 ExchangeProviderResponseCodeException('${error}\n$message', response.statusCode);
- }
-
- if (response.statusCode != 200)
- throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', 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,
- toAddressExtraId: request.toAddressExtraId,
- );
- }
-
- @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 ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', 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';
- case CryptoCurrency.nano:
- return 'nano';
- 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';
- case CryptoCurrency.maticpoly:
- return 'matic';
- default:
- return currency.title.toLowerCase();
- }
- }
-
- String _normalizeTag(String tag) {
- switch (tag) {
- case 'POL':
- return 'matic';
- case 'LN':
- return 'lightning';
- case 'AVAXC':
- return 'cchain';
- case 'ARB':
- return 'arbitrum';
- case "ROB":
- return "hood";
- default:
- return tag.toLowerCase();
- }
- }
-
- String _normalizeNetworkType(String network) {
- return switch (network.toUpperCase()) {
- 'POLY' => 'MATIC',
- 'AVAXC' => 'CCHAIN',
- 'ARBITRUM' => 'ARB',
- "HOOD" => "ROB",
- _ => network,
- };
- }
-}
### lib/exchange/provider/exchange_provider.dart
@@ -1,43 +1,76 @@
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/limits.dart';
-import 'package:cake_wallet/exchange/trade.dart';
-import 'package:cake_wallet/exchange/trade_request.dart';
-import 'package:cw_core/crypto_currency.dart';
+import "package:cake_wallet/exchange/exchange_provider_description.dart";
+import "package:cake_wallet/exchange/limits.dart";
+import "package:cake_wallet/exchange/rate_request.dart";
+import "package:cake_wallet/exchange/trade.dart";
+import "package:cake_wallet/exchange/trade_request.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/exchange_limits.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/provider_rate.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/pending_transaction.dart";
+import "package:cw_core/utils/proxy_wrapper.dart";
+import "package:cw_core/wallet_base.dart";
abstract class ExchangeProvider {
- ExchangeProvider();
+ ExchangeProvider({ProxyWrapper? proxyWrapper}) : proxyWrapper = proxyWrapper ?? ProxyWrapper();
- String get title;
+ final ProxyWrapper proxyWrapper;
ExchangeProviderDescription get description;
- bool get isAvailable;
-
- bool get isEnabled;
+ String get title => description.title;
bool get supportsFixedRate;
bool get supportsOnionAddress => false;
- bool get supportsMemoOrDestinationTag => true;
-
@override
String toString() => title;
- Future<Limits?> fetchLimits(
- {required CryptoCurrency from, required CryptoCurrency to, required bool isFixedRateMode});
+ Future<ExchangeLimits> fetchLimits(
+ {required CryptoCurrency from, required CryptoCurrency to, required bool isFixedRateMode,});
Future<Trade> createTrade(
- {required TradeRequest request, required bool isFixedRateMode, required bool isSendAll});
+ {required TradeRequest request,});
+
+ Future<Trade> updateTrade(Trade trade);
+
+ Future<ProviderRate> fetchRate(RateRequest request);
+}
+
+abstract class LimitsCacheExchangeProvider extends ExchangeProvider {
+ LimitsCacheExchangeProvider({super.proxyWrapper});
- Future<Trade> findTradeById({required String id});
+ static const _limitsLifetime = Duration(minutes: 10);
- Future<double> fetchRate(
- {required CryptoCurrency from,
- required CryptoCurrency to,
- required double amount,
- required bool isFixedRateMode,
- required bool isReceiveAmount});
+ final Map<(CryptoCurrency, CryptoCurrency, bool), (ExchangeLimits, DateTime)> _limitsCache = {};
- Future<bool> checkIsAvailable();
+ @override
+ Future<ExchangeLimits> fetchLimits({
+ required CryptoCurrency from,
+ required CryptoCurrency to,
+ required bool isFixedRateMode,
+ });
+
+ Future<ExchangeLimits> getLimits({
+ required CryptoCurrency from,
+ required CryptoCurrency to,
+ required bool isFixedRateMode,
+ }) async {
+ if (_limitsCache[(from, to, isFixedRateMode)] case (final limits, final fetchedAt)
+ when DateTime.now().difference(fetchedAt) < _limitsLifetime) {
+ return limits;
+ }
+
+ final limits = await fetchLimits(from: from, to: to, isFixedRateMode: isFixedRateMode);
+ _limitsCache[(from, to, isFixedRateMode)] = (limits, DateTime.now());
+ return limits;
+ }
}
+
+abstract interface class TransactionCreationExchangeProvider {
+ Future<PendingTransaction?> createTransaction(WalletBase wallet, Trade trade);
+}
+
+abstract interface class TransactionRegistrationExchangeProvider {
+ Future<Trade> registerTransaction(Trade trade, String txHash);
+}
\ No newline at end of file
### lib/exchange/provider/exolix/exolix_api_schema.dart
@@ -0,0 +1,251 @@
+// spec reference: https://exolix.com/developers
+
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/exchange/utils/json_converters.dart";
+import "package:json_annotation/json_annotation.dart";
+
+part "exolix_api_schema.g.dart";
+
+enum ExolixRateType {
+ @JsonValue("float")
+ float,
+ @JsonValue("fixed")
+ fixed,
+ unknown,
+}
+
+enum ExolixTransactionSource {
+ @JsonValue("api")
+ api,
+ @JsonValue("referral")
+ referral,
+ unknown,
+}
+
+
+@JsonSerializable()
+class ExolixRateRequest {
+ const ExolixRateRequest({
+ required this.coinFrom,
+ required this.coinTo,
+ required this.networkFrom,
+ required this.networkTo,
+ required this.rateType,
+ required this.apiToken,
+ this.amount,
+ this.withdrawalAmount,
+ });
+
+ @JsonKey(name: "coinFrom")
+ final String coinFrom;
+ @JsonKey(name: "coinTo")
+ final String coinTo;
+ @JsonKey(name: "networkFrom")
+ final String networkFrom;
+ @JsonKey(name: "networkTo")
+ final String networkTo;
+ @JsonKey(name: "rateType")
+ final ExolixRateType rateType;
+ @JsonKey(name: "amount", includeIfNull: false)
+ final String? amount;
+ @JsonKey(name: "withdrawalAmount", includeIfNull: false)
+ final String? withdrawalAmount;
+ @JsonKey(name: "apiToken")
+ final String apiToken;
+
+ Map<String, dynamic> toJson() => _$ExolixRateRequestToJson(this);
+}
+
+@JsonSerializable(createToJson: false)
+class ExolixRateResponse {
+ const ExolixRateResponse({
+ required this.fromAmount,
+ required this.toAmount,
+ this.rate,
+ this.message,
+ this.minAmount,
+ this.withdrawMin,
+ this.maxAmount,
+ });
+
+ factory ExolixRateResponse.fromJson(Map<String, dynamic> json) =>
+ _$ExolixRateResponseFromJson(json);
+
+ @JsonKey(name: "fromAmount")
+ final double fromAmount;
+ @JsonKey(name: "toAmount")
+ final double toAmount;
+ @JsonKey(name: "rate")
+ final double? rate;
+ @JsonKey(name: "message")
+ final String? message;
+ @JsonKey(name: "minAmount")
+ final double? minAmount;
+ @JsonKey(name: "withdrawMin")
+ final double? withdrawMin;
+ @JsonKey(name: "maxAmount")
+ final double? maxAmount;
+}
+
+
+@JsonSerializable(createToJson: false)
+class ExolixCoin {
+ const ExolixCoin({
+ required this.coinCode,
+ required this.coinName,
+ required this.network,
+ required this.networkName,
+ required this.icon,
+ this.networkShortName,
+ this.memoName,
+ this.contract,
+ });
+
+ factory ExolixCoin.fromJson(Map<String, dynamic> json) => _$ExolixCoinFromJson(json);
+
+ @JsonKey(name: "coinCode")
+ final String coinCode;
+ @JsonKey(name: "coinName")
+ final String coinName;
+ @JsonKey(name: "network")
+ final String network;
+ @JsonKey(name: "networkName")
+ final String networkName;
+ @JsonKey(name: "networkShortName")
+ final String? networkShortName;
+ @JsonKey(name: "icon")
+ final String icon;
+ @JsonKey(name: "memoName")
+ final String? memoName;
+ @JsonKey(name: "contract")
+ final String? contract;
+}
+
+@JsonSerializable(createToJson: false)
+class ExolixHash {
+ const ExolixHash({this.hash, this.link});
+
+ factory ExolixHash.fromJson(Map<String, dynamic> json) => _$ExolixHashFromJson(json);
+
+ @JsonKey(name: "hash")
+ final String? hash;
+ @JsonKey(name: "link")
+ final String? link;
+}
+
+@JsonSerializable()
+class ExolixCreateTransactionRequest {
+ const ExolixCreateTransactionRequest({
+ required this.coinFrom,
+ required this.coinTo,
+ required this.networkFrom,
+ required this.networkTo,
+ required this.withdrawalAddress,
+ required this.rateType,
+ required this.apiToken,
+ this.amount,
+ this.withdrawalAmount,
+ this.withdrawalExtraId,
+ this.refundAddress,
+ this.refundExtraId,
+ this.slippage,
+ });
+
+ @JsonKey(name: "coinFrom")
+ final String coinFrom;
+ @JsonKey(name: "coinTo")
+ final String coinTo;
+ @JsonKey(name: "networkFrom")
+ final String networkFrom;
+ @JsonKey(name: "networkTo")
+ final String networkTo;
+ @JsonKey(name: "withdrawalAddress")
+ final String withdrawalAddress;
+ @JsonKey(name: "rateType")
+ final ExolixRateType rateType;
+ @JsonKey(name: "amount", includeIfNull: false)
+ final String? amount;
+ @JsonKey(name: "withdrawalAmount", includeIfNull: false)
+ final String? withdrawalAmount;
+ @JsonKey(name: "withdrawalExtraId", includeIfNull: false)
+ final String? withdrawalExtraId;
+ @JsonKey(name: "refundAddress", includeIfNull: false)
+ final String? refundAddress;
+ @JsonKey(name: "refundExtraId", includeIfNull: false)
+ final String? refundExtraId;
+ @JsonKey(name: "slippage", includeIfNull: false)
+ final double? slippage;
+ @JsonKey(name: "apiToken")
+ final String apiToken;
+
+ Map<String, dynamic> toJson() => _$ExolixCreateTransactionRequestToJson(this);
+}
+
+
+@JsonSerializable(createToJson: false)
+@TradeStateConverter()
+class ExolixTransactionResponse {
+ const ExolixTransactionResponse({
+ required this.id,
+ required this.amount,
+ required this.coinFrom,
+ required this.coinTo,
+ required this.createdAt,
+ required this.depositAddress,
+ required this.withdrawalAddress,
+ required this.hashIn,
+ required this.hashOut,
+ required this.rate,
+ required this.rateType,
+ required this.status,
+ this.amountTo,
+ this.comment,
+ this.depositExtraId,
+ this.withdrawalExtraId,
+ this.refundAddress,
+ this.refundExtraId,
+ this.source,
+ });
+
+ factory ExolixTransactionResponse.fromJson(Map<String, dynamic> json) =>
+ _$ExolixTransactionResponseFromJson(json);
+
+ @JsonKey(name: "id")
+ final String id;
+ @JsonKey(name: "amount")
+ final double amount;
+ @JsonKey(name: "amountTo")
+ final double? amountTo;
+ @JsonKey(name: "coinFrom")
+ final ExolixCoin coinFrom;
+ @JsonKey(name: "coinTo")
+ final ExolixCoin coinTo;
+ @JsonKey(name: "comment")
+ final String? comment;
+ @JsonKey(name: "createdAt")
+ final DateTime createdAt;
+ @JsonKey(name: "depositAddress")
+ final String depositAddress;
+ @JsonKey(name: "depositExtraId")
+ final String? depositExtraId;
+ @JsonKey(name: "withdrawalAddress")
+ final String withdrawalAddress;
+ @JsonKey(name: "withdrawalExtraId")
+ final String? withdrawalExtraId;
+ @JsonKey(name: "hashIn")
+ final ExolixHash hashIn;
+ @JsonKey(name: "hashOut")
+ final ExolixHash hashOut;
+ @JsonKey(name: "rate")
+ final double rate;
+ @JsonKey(name: "rateType", unknownEnumValue: ExolixRateType.unknown)
+ final ExolixRateType rateType;
+ @JsonKey(name: "refundAddress")
+ final String? refundAddress;
+ @JsonKey(name: "refundExtraId")
+ final String? refundExtraId;
+ @JsonKey(name: "status")
+ final TradeState status;
+ @JsonKey(name: "source", unknownEnumValue: ExolixTransactionSource.unknown)
+ final ExolixTransactionSource? source;
+}
### lib/exchange/provider/exolix/exolix_exchange_provider.dart
@@ -0,0 +1,273 @@
+import "dart:convert";
+
+import "package:cake_wallet/.secrets.g.dart" as secrets;
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
+import "package:cake_wallet/exchange/exchange_provider_description.dart";
+import "package:cake_wallet/exchange/provider/exchange_provider.dart";
+import "package:cake_wallet/exchange/provider/exolix/exolix_api_schema.dart";
+import "package:cake_wallet/exchange/rate_request.dart";
+import "package:cake_wallet/exchange/trade.dart";
+import "package:cake_wallet/exchange/trade_request.dart";
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/exchange_limits.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/provider_rate.dart";
+import "package:cake_wallet/wallet_type_utils.dart";
+import "package:cw_core/amount/exchange_rate.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/crypto_currency.dart";
+
+class ExolixExchangeProvider extends ExchangeProvider {
+ ExolixExchangeProvider({super.proxyWrapper});
+
+ 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
+ bool get supportsFixedRate => false;
+
+ @override
+ ExchangeProviderDescription get description => ExchangeProviderDescription.exolix;
+
+ @override
+ Future<ExchangeLimits> fetchLimits({
+ required CryptoCurrency from,
+ required CryptoCurrency to,
+ required bool isFixedRateMode,
+ }) async {
+ final params = ExolixRateRequest(
+ coinFrom: _normalizeCurrency(isFixedRateMode ? to : from),
+ coinTo: _normalizeCurrency(isFixedRateMode ? from : to),
+ networkFrom: _networkFor(isFixedRateMode ? to : from),
+ amount: "1",
+ networkTo: _networkFor(isFixedRateMode ? from : to),
+ rateType: isFixedRateMode ? .fixed : .float,
+ apiToken: apiKey,
+ );
+
+ final uri = Uri.https(apiBaseUrl, ratePath, params.toJson());
+ final response = await proxyWrapper.get(clearnetUri: uri);
+
+ if (response.statusCode == 200) {
+ final responseData = ExolixRateResponse.fromJson(
+ json.decode(response.body) as Map<String, dynamic>,
+ );
+ return ExchangeLimits(
+ min: Money.safeParse(responseData.minAmount, isFixedRateMode ? to : from),
+ max: Money.safeParse(responseData.maxAmount, isFixedRateMode ? to : from),
+ );
+ } else if (response.statusCode == 422) {
+ // HACK: exolix provides limits only if we ourselves supply an amount higher than minAmount.
+ // i found no better workaround
+ final errorResponse = json.decode(response.body) as Map<String, dynamic>;
+
+ if (errorResponse.containsKey("minAmount")) {
+ final paramsWithMin = ExolixRateRequest(
+ coinFrom: params.coinFrom,
+ coinTo: params.coinTo,
+ networkFrom: params.networkFrom,
+ networkTo: params.networkTo,
+ rateType: params.rateType,
+ amount: errorResponse["minAmount"].toString(),
+ apiToken: apiKey,
+ );
+
+ final uri = Uri.https(apiBaseUrl, ratePath, paramsWithMin.toJson());
+ final response = await proxyWrapper.get(clearnetUri: uri);
+
+ if (response.statusCode == 200) {
+ final responseData = ExolixRateResponse.fromJson(
+ json.decode(response.body) as Map<String, dynamic>,
+ );
+ return ExchangeLimits(
+ min: Money.safeParse(responseData.minAmount, isFixedRateMode ? to : from),
+ max: Money.safeParse(responseData.maxAmount, isFixedRateMode ? to : from),
+ );
+ }
+ }
+ throw Exception('Error 422: ${errorResponse['message'] ?? 'Unknown error'}');
+ } else {
+ throw Exception("Unexpected HTTP status: ${response.statusCode}");
+ }
+ }
+
+ @override
+ Future<ProviderRate> fetchRate(RateRequest request) async {
+
+ final params = ExolixRateRequest(
+ coinFrom: _normalizeCurrency(_overrideFromCryptoCurrency(request.depositCurrency)),
+ coinTo: _normalizeCurrency(request.payoutCurrency),
+ networkFrom: _networkFor(request.depositCurrency),
+ networkTo: _networkFor(request.payoutCurrency),
+ rateType: ExolixRateType.float,
+ amount: (request as FloatingRateRequest).depositAmount.toString(),
+ apiToken: apiKey,
+ );
+
+ final uri = Uri.https(apiBaseUrl, ratePath, params.toJson());
+ 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"] ?? responseJSON["error"];
+
+ throw Exception(message?.toString() ?? response.body);
+ }
+
+ final responseData = ExolixRateResponse.fromJson(responseJSON);
+
+ return ProviderRate(
+ provider: description,
+ rate: ExchangeRate.fromAmounts(
+ Money.safeParse(responseData.fromAmount, request.depositCurrency),
+ Money.safeParse(responseData.toAmount, request.payoutCurrency),
+ ),
+ limits: ExchangeLimits(
+ min: Money.safeParse(responseData.minAmount, request.depositCurrency),
+ max: Money.safeParse(responseData.maxAmount, request.depositCurrency),
+ ),
+ );
+ }
+
+ @override
+ Future<Trade> createTrade({required TradeRequest request}) async {
+ final headers = {"Content-Type": "application/json"};
+
+ final body = ExolixCreateTransactionRequest(
+ coinFrom: _normalizeCurrency(_overrideFromCryptoCurrency(request.depositCurrency)),
+ coinTo: _normalizeCurrency(
+ _overrideToCryptoCurrency(request.payoutCurrency, request.payoutAddress),
+ ),
+ networkFrom: _networkFor(request.depositCurrency),
+ networkTo: _networkFor(request.payoutCurrency),
+ refundAddress: request.refundInvoice ?? request.refundAddress,
+ withdrawalExtraId: request.toAddressExtraId,
+ withdrawalAddress: _normalizeAddress(request.payoutInvoice ?? request.payoutAddress),
+ withdrawalAmount: request.isFixedRate ? request.payoutAmount.toString() : null,
+ amount: request.isFixedRate ? null : request.depositAmount.toString(),
+ rateType: request.isFixedRate ? ExolixRateType.fixed : ExolixRateType.float,
+ apiToken: apiKey,
+ );
+
+ 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>;
+ throw Exception(responseJSON["error"].toString());
+ }
+
+ if (response.statusCode != 200 && response.statusCode != 201) {
+ throw Exception("Unexpected http status: ${response.statusCode}");
+ }
+
+ final responseJSON = json.decode(response.body) as Map<String, dynamic>;
+ final responseData = ExolixTransactionResponse.fromJson(responseJSON);
+
+ return Trade(
+ id: responseData.id,
+ provider: description,
+ extraId: responseData.depositExtraId,
+ createdAt: DateTime.now(),
+ state: TradeState.created,
+ toAddressExtraId: request.toAddressExtraId,
+ depositAmount: Money.safeParse(responseData.amount, request.depositAmount.currency),
+ payoutAmount: Money.safeParse(responseData.amountTo, request.payoutAmount.currency),
+ fundingAddress: responseData.depositAddress,
+ payoutAddress: responseData.withdrawalAddress,
+ refundAddress: responseData.refundAddress ?? "",
+ );
+ }
+
+ @override
+ Future<Trade> updateTrade(Trade trade) async {
+ final findTradeByIdPath = "$transactionsPath/${trade.id}";
+ final uri = Uri.https(apiBaseUrl, findTradeByIdPath);
+ final response = await proxyWrapper.get(clearnetUri: uri);
+
+ if (response.statusCode == 404) {
+ throw TradeNotFoundException(trade.id, provider: description);
+ }
+
+ if (response.statusCode == 400) {
+ final responseJSON = json.decode(response.body) as Map<String, dynamic>;
+ final errors = responseJSON["errors"] as Map<String, dynamic>?;
+ final errorMessage = errors?.values.join(", ") ?? response.body;
+
+ throw TradeNotFoundException(trade.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>;
+ final responseData = ExolixTransactionResponse.fromJson(responseJSON);
+
+ return trade.copyWith(
+ state: responseData.status,
+ extraId: responseData.depositExtraId,
+ outputTransaction: responseData.hashOut.hash,
+ payoutAddress: responseData.withdrawalAddress,
+ depositAmount: Money.safeParse(responseData.amount, trade.depositCurrency),
+ payoutAmount: Money.safeParse(responseData.amountTo, trade.payoutCurrency),
+ fundingAddress: responseData.depositAddress,
+ refundAddress: responseData.refundAddress,
+ );
+ }
+
+ 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;
+ }
+ }
+
+
+ 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) {
+ CryptoCurrency.nano => "XNO",
+ CryptoCurrency.bttc => "BTT",
+ CryptoCurrency.zec => "ZEC",
+ CryptoCurrency.zaddr => "ZEC-SHIELDED",
+ _ => currency.title,
+ };
+
+ String _normalizeTag(String tag) {
+ switch (tag) {
+ case "POLY":
+ return "Polygon";
+ case "ARB":
+ return "Arbitrum";
+ default:
+ return tag;
+ }
+ }
+
+ String _normalizeAddress(String address) => address.startsWith("bitcoincash:")
+ ? address.replaceFirst("bitcoincash:", "")
+ : address;
+}
### lib/exchange/provider/exolix_exchange_provider.dart
@@ -1,467 +0,0 @@
-import 'dart:convert';
-
-import 'package:cake_wallet/.secrets.g.dart' as secrets;
-import 'package:cake_wallet/core/lightning_invoice_service.dart';
-import "package:cake_wallet/exchange/exchange_exceptions.dart";
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/limits.dart';
-import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
-import 'package:cake_wallet/exchange/trade.dart';
-import 'package:cake_wallet/exchange/trade_not_found_exception.dart';
-import 'package:cake_wallet/exchange/trade_request.dart';
-import 'package:cake_wallet/exchange/trade_state.dart';
-import 'package:cake_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:cake_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 => false;
-
- @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 ExchangeProviderResponseCodeException('Error 422: ${errorResponse['message'] ?? 'Unknown error'}', response.statusCode);
- } else {
- throw ExchangeProviderResponseCodeException('Unexpected HTTP status: ${response.statusCode}', response.statusCode);
- }
- }
-
- throw ExchangeProviderResponseException('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 ExchangeProviderResponseCodeException(message??"", response.statusCode);
- }
-
- 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),
- if (request.toAddressExtraId.isNotEmpty) 'withdrawalExtraId': request.toAddressExtraId,
- '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 ExchangeProviderResponseCodeException(errorMessage??"", response.statusCode);
- }
-
- 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 ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', 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,
- toAddressExtraId: request.toAddressExtraId,
- );
- }
-
- @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 ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', 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;
- }
-}
### lib/exchange/provider/jupiter/jupiter_api_schema.dart
@@ -0,0 +1,397 @@
+// spec reference: https://developers.jup.ag/docs/ultra-api
+
+import "package:cake_wallet/exchange/utils/provider_api.dart";
+import "package:json_annotation/json_annotation.dart";
+
+part "jupiter_api_schema.g.dart";
+
+// base unit amounts come back as strings, but the execute response fields aren't documented
+class JupiterBaseUnitConverter implements JsonConverter<BigInt, Object> {
+ const JupiterBaseUnitConverter();
+
+ @override
+ BigInt fromJson(Object json) {
+ if (json is String) {
+ return BigInt.parse(json);
+ }
+ if (json is num) {
+ return BigInt.from(json);
+ }
+ throw ArgumentError("unexpected Jupiter amount: $json");
+ }
+
+ @override
+ Object toJson(BigInt value) => value.toString();
+}
+
+// the docs don't say whether slot and code are numbers or strings
+class JupiterLooseIntConverter implements JsonConverter<int, Object> {
+ const JupiterLooseIntConverter();
+
+ @override
+ int fromJson(Object json) {
+ if (json is num) {
+ return json.toInt();
+ }
+ if (json is String) {
+ return int.parse(json);
+ }
+ throw ArgumentError("unexpected Jupiter integer: $json");
+ }
+
+ @override
+ Object toJson(int value) => value;
+}
+
+enum JupiterSwapMode {
+ @JsonValue("ExactIn")
+ exactIn,
+ @JsonValue("ExactOut")
+ exactOut,
+ unknown,
+}
+
+enum JupiterSwapType {
+ @JsonValue("aggregator")
+ aggregator,
+ @JsonValue("rfq")
+ rfq,
+ unknown,
+}
+
+@JsonSerializable(createToJson: false)
+class JupiterErrorResponse {
+ const JupiterErrorResponse({this.requestId, this.error});
+
+ factory JupiterErrorResponse.fromJson(Map<String, dynamic> json) =>
+ _$JupiterErrorResponseFromJson(json);
+
+ @JsonKey(name: "requestId")
+ final String? requestId;
+ @JsonKey(name: "error")
+ final String? error;
+}
+
+
+@JsonSerializable()
+class JupiterOrderRequest extends ApiRequest<JupiterOrder> {
+ const JupiterOrderRequest({
+ required this.inputMint,
+ required this.outputMint,
+ required this.amount,
+ this.taker,
+ this.receiver,
+ this.referralAccount,
+ this.referralFee,
+ });
+
+ @JsonKey(name: "inputMint")
+ final String inputMint;
+ @JsonKey(name: "outputMint")
+ final String outputMint;
+
+ @JsonKey(name: "amount")
+ final BigInt amount;
+
+ @JsonKey(name: "taker", includeIfNull: false)
+ final String? taker;
+
+ @JsonKey(name: "receiver", includeIfNull: false)
+ final String? receiver;
+ @JsonKey(name: "referralAccount", includeIfNull: false)
+ final String? referralAccount;
+
+ @JsonKey(name: "referralFee", includeIfNull: false)
+ final String? referralFee;
+
+ @override
+ String path() => "/ultra/v1/order";
+
+ @override
+ Map<String, dynamic> toJson() => _$JupiterOrderRequestToJson(this);
+
+ @override
+ JupiterOrder decode(Object json) => JupiterOrder.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+@JupiterBaseUnitConverter()
+class JupiterSwapInfo {
+ const JupiterSwapInfo({
+ required this.inputMint,
+ required this.outputMint,
+ required this.inAmount,
+ required this.outAmount,
+ this.ammKey,
+ this.label,
+ });
+
+ factory JupiterSwapInfo.fromJson(Map<String, dynamic> json) => _$JupiterSwapInfoFromJson(json);
+
+ @JsonKey(name: "ammKey")
+ final String? ammKey;
+
+ @JsonKey(name: "label")
+ final String? label;
+ @JsonKey(name: "inputMint")
+ final String inputMint;
+ @JsonKey(name: "outputMint")
+ final String outputMint;
+ @JsonKey(name: "inAmount")
+ final BigInt inAmount;
+ @JsonKey(name: "outAmount")
+ final BigInt outAmount;
+}
+
+@JsonSerializable(createToJson: false)
+class JupiterRoutePlanStep {
+ const JupiterRoutePlanStep({required this.swapInfo, this.percent, this.bps, this.usdValue});
+
+ factory JupiterRoutePlanStep.fromJson(Map<String, dynamic> json) =>
+ _$JupiterRoutePlanStepFromJson(json);
+
+ @JsonKey(name: "percent")
+ final int? percent;
+ @JsonKey(name: "bps")
+ final int? bps;
+ @JsonKey(name: "usdValue")
+ final double? usdValue;
+ @JsonKey(name: "swapInfo")
+ final JupiterSwapInfo swapInfo;
+}
+
+@JsonSerializable(createToJson: false)
+class JupiterPlatformFee {
+ const JupiterPlatformFee({this.feeBps, this.feeMint});
+
+ factory JupiterPlatformFee.fromJson(Map<String, dynamic> json) =>
+ _$JupiterPlatformFeeFromJson(json);
+
+ @JsonKey(name: "feeBps")
+ final int? feeBps;
+ @JsonKey(name: "feeMint")
+ final String? feeMint;
+}
+
+@JsonSerializable(createToJson: false)
+@JupiterBaseUnitConverter()
+class JupiterOrder {
+ const JupiterOrder({
+ required this.requestId,
+ required this.inputMint,
+ required this.outputMint,
+ required this.inAmount,
+ required this.outAmount,
+ required this.swapType,
+ required this.swapMode,
+ this.otherAmountThreshold,
+ this.slippageBps,
+ this.priceImpactPct,
+ this.priceImpact,
+ this.routePlan,
+ this.transaction,
+ this.integratorFeeLamports,
+ this.taker,
+ this.router,
+ this.mode,
+ this.gasless,
+ this.jitOptimized,
+ this.guaranteedPrice,
+ this.feeMint,
+ this.feeBps,
+ this.platformFee,
+ this.signatureFeeLamports,
+ this.signatureFeePayer,
+ this.prioritizationFeeLamports,
+ this.prioritizationFeePayer,
+ this.rentFeeLamports,
+ this.rentFeePayer,
+ this.inUsdValue,
+ this.outUsdValue,
+ this.swapUsdValue,
+ this.totalTime,
+ this.errorCode,
+ this.errorMessage,
+ this.error,
+ });
+
+ factory JupiterOrder.fromJson(Map<String, dynamic> json) => _$JupiterOrderFromJson(json);
+
+ @JsonKey(name: "requestId")
+ final String requestId;
+
+ @JsonKey(name: "transaction")
+ final String? transaction;
+ @JsonKey(name: "inputMint")
+ final String inputMint;
+ @JsonKey(name: "outputMint")
+ final String outputMint;
+ @JsonKey(name: "inAmount")
+ final BigInt inAmount;
+ @JsonKey(name: "outAmount")
+ final BigInt outAmount;
+
+ @JsonKey(name: "otherAmountThreshold")
+ final BigInt? otherAmountThreshold;
+ @JsonKey(name: "swapType", unknownEnumValue: JupiterSwapType.unknown)
+ final JupiterSwapType swapType;
+ @JsonKey(name: "swapMode", unknownEnumValue: JupiterSwapMode.unknown)
+ final JupiterSwapMode swapMode;
+
+ @JsonKey(name: "slippageBps")
+ final int? slippageBps;
+ @JsonKey(name: "priceImpactPct")
+ final String? priceImpactPct;
+ @JsonKey(name: "priceImpact")
+ final double? priceImpact;
+ @JsonKey(name: "routePlan")
+ final List<JupiterRoutePlanStep>? routePlan;
+ @JsonKey(name: "taker")
+ final String? taker;
+
+ @JsonKey(name: "router")
+ final String? router;
+ @JsonKey(name: "mode")
+ final String? mode;
+ @JsonKey(name: "gasless")
+ final bool? gasless;
+ @JsonKey(name: "jitOptimized")
+ final bool? jitOptimized;
+ @JsonKey(name: "guaranteedPrice")
+ final bool? guaranteedPrice;
+
+ @JsonKey(name: "feeMint")
+ final String? feeMint;
+ @JsonKey(name: "feeBps")
+ final int? feeBps;
+ @JsonKey(name: "platformFee")
+ final JupiterPlatformFee? platformFee;
+
+ @JsonKey(name: "signatureFeeLamports")
+ final int? signatureFeeLamports;
+ // api does not document this but we use it? idk brah
+ @JsonKey(name: "integratorFeeLamports")
+ final int? integratorFeeLamports;
+ @JsonKey(name: "signatureFeePayer")
+ final String? signatureFeePayer;
+ @JsonKey(name: "prioritizationFeeLamports")
+ final int? prioritizationFeeLamports;
+ @JsonKey(name: "prioritizationFeePayer")
+ final String? prioritizationFeePayer;
+ @JsonKey(name: "rentFeeLamports")
+ final int? rentFeeLamports;
+ @JsonKey(name: "rentFeePayer")
+ final String? rentFeePayer;
+ @JsonKey(name: "inUsdValue")
+ final double? inUsdValue;
+ @JsonKey(name: "outUsdValue")
+ final double? outUsdValue;
+ @JsonKey(name: "swapUsdValue")
+ final double? swapUsdValue;
+
+ @JsonKey(name: "totalTime")
+ final int? totalTime;
+ @JsonKey(name: "errorCode")
+ final int? errorCode;
+ @JsonKey(name: "errorMessage")
+ final String? errorMessage;
+ @JsonKey(name: "error")
+ final String? error;
+
+ int get totalFee =>
+ (signatureFeeLamports ?? 0) +
+ (integratorFeeLamports ?? 0) +
+ (prioritizationFeeLamports ?? 0) +
+ (rentFeeLamports ?? 0);
+}
+
+
+@JsonSerializable()
+class JupiterExecuteRequest extends ApiRequest<JupiterExecuteResponse> {
+ const JupiterExecuteRequest({required this.signedTransaction, required this.requestId})
+ : super.post();
+
+ @JsonKey(name: "signedTransaction")
+ final String signedTransaction;
+ @JsonKey(name: "requestId")
+ final String requestId;
+
+ @override
+ String path() => "/ultra/v1/execute";
+
+ @override
+ Map<String, dynamic> toJson() => _$JupiterExecuteRequestToJson(this);
+
+ @override
+ JupiterExecuteResponse decode(Object json) =>
+ JupiterExecuteResponse.fromJson(json as Map<String, dynamic>);
+}
+
+enum JupiterExecuteStatus {
+ @JsonValue("Success")
+ success,
+ @JsonValue("Failed")
+ failed,
+ @JsonValue("Pending")
+ pending,
+ @JsonValue("Processing")
+ processing,
+ unknown,
+}
+
+@JsonSerializable(createToJson: false)
+@JupiterBaseUnitConverter()
+class JupiterSwapEvent {
+ const JupiterSwapEvent({this.inputMint, this.inputAmount, this.outputMint, this.outputAmount});
+
+ factory JupiterSwapEvent.fromJson(Map<String, dynamic> json) => _$JupiterSwapEventFromJson(json);
+
+ @JsonKey(name: "inputMint")
+ final String? inputMint;
+ @JsonKey(name: "inputAmount")
+ final BigInt? inputAmount;
+ @JsonKey(name: "outputMint")
+ final String? outputMint;
+ @JsonKey(name: "outputAmount")
+ final BigInt? outputAmount;
+}
+
+@JsonSerializable(createToJson: false)
+@JupiterBaseUnitConverter()
+class JupiterExecuteResponse {
+ const JupiterExecuteResponse({
+ required this.status,
+ this.signature,
+ this.slot,
+ this.code,
+ this.error,
+ this.inputAmountResult,
+ this.outputAmountResult,
+ this.swapEvents,
+ });
+
+ factory JupiterExecuteResponse.fromJson(Map<String, dynamic> json) =>
+ _$JupiterExecuteResponseFromJson(json);
+
+ @JsonKey(name: "status", unknownEnumValue: JupiterExecuteStatus.unknown)
+ final JupiterExecuteStatus status;
+
+ @JsonKey(name: "signature")
+ final String? signature;
+ @JsonKey(name: "slot")
+ @JupiterLooseIntConverter()
+ final int? slot;
+
+ @JsonKey(name: "code")
+ @JupiterLooseIntConverter()
+ final int? code;
+ @JsonKey(name: "error")
+ final String? error;
+
+ @JsonKey(name: "inputAmountResult")
+ final BigInt? inputAmountResult;
+ @JsonKey(name: "outputAmountResult")
+ final BigInt? outputAmountResult;
+ @JsonKey(name: "swapEvents")
+ final List<JupiterSwapEvent>? swapEvents;
+}
### lib/exchange/provider/jupiter/jupiter_exchange_provider.dart
@@ -0,0 +1,240 @@
+import "package:cake_wallet/.secrets.g.dart" as secrets;
+import "package:cake_wallet/exchange/exchange_provider_description.dart";
+import "package:cake_wallet/exchange/provider/exchange_provider.dart";
+import "package:cake_wallet/exchange/provider/jupiter/jupiter_api_schema.dart";
+import "package:cake_wallet/exchange/rate_request.dart";
+import "package:cake_wallet/exchange/trade.dart";
+import "package:cake_wallet/exchange/trade_not_created_exception.dart";
+import "package:cake_wallet/exchange/trade_request.dart";
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/exchange/utils/provider_api.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/exchange_limits.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/provider_rate.dart";
+import "package:cake_wallet/solana/solana.dart";
+import "package:cake_wallet/utils/exchange_provider_logger.dart";
+import "package:cw_core/amount/exchange_rate.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/pending_transaction.dart";
+import "package:cw_core/wallet_base.dart";
+
+class JupiterTrade extends RoutableTrade {
+ JupiterTrade({
+ required this.fee,
+ required super.state,
+ required super.depositAmount,
+ required super.payoutAmount,
+ required super.id,
+ required super.provider,
+ required super.payoutAddress,
+ required super.refundAddress,
+
+ required super.routerData,
+ required super.routerValue,
+ super.router,
+ super.createdAt,
+ super.expiredAt,
+ super.extraId,
+ super.outputTransaction,
+ super.walletId,
+ super.toAddressExtraId,
+ super.password,
+ super.providerId,
+ super.memo,
+ super.txId,
+ super.isRefund,
+ }) : super(fundingAddress: "");
+
+ final Money fee;
+}
+
+class JupiterExchangeProvider extends ExchangeProvider
+ implements TransactionCreationExchangeProvider {
+ JupiterExchangeProvider({super.proxyWrapper});
+
+ // Jupiter only supports Solana native SOL and Solana tokens
+ bool _isSolanaCurrency(CryptoCurrency currency) =>
+ currency == CryptoCurrency.sol || currency.tag == "SOL";
+
+ static const _baseUrl = "api.jup.ag";
+ static const _referralFee = secrets.jupiterReferralFeeBps;
+ static const _referralAccount = secrets.jupiterReferralAccount;
+ static final _hasReferral = _referralFee.isNotEmpty && _referralAccount.isNotEmpty;
+
+ late final _api = ProviderApi(
+ proxyWrapper,
+ authority: _baseUrl,
+ headers: {"x-api-key": secrets.jupiterApiKey},
+ errorMessage: (json) => json["error"]?.toString(),
+ );
+
+ // Wrapped SOL address (native SOL)
+ static const _nativeSolMint = "So11111111111111111111111111111111111111112";
+
+ @override
+ bool get supportsFixedRate => false;
+
+ @override
+ ExchangeProviderDescription get description => ExchangeProviderDescription.jupiter;
+
+ String _getTokenMint(CryptoCurrency currency) {
+ if (currency == CryptoCurrency.sol) {
+ return _nativeSolMint;
+ }
+
+ if (currency.tag != "SOL") {
+ throw Exception("Unsupported currency: ${currency.title} (not a Solana token)");
+ }
+
+ return solana!.getTokenAddress(currency);
+ }
+
+ @override
+ Future<ExchangeLimits> fetchLimits({
+ required CryptoCurrency from,
+ required CryptoCurrency to,
+ required bool isFixedRateMode,
+ }) async {
+ // The Ultra Swap API doesn't have a dedicated limits endpoint
+ // The /order endpoint validates amounts and returns error codes:
+ // - errorCode 1: Insufficient funds
+ // - errorCode 2: Top up SOL for gas
+ // - errorCode 3: Minimum amount for gasless
+
+ // only return null for supported currencies
+ if (_isSolanaCurrency(from) && _isSolanaCurrency(to)) {
+ return ExchangeLimits();
+ } else {
+ throw Exception("not supported");
+ }
+ }
+
+ @override
+ Future<ProviderRate> fetchRate(RateRequest request) async {
+ if (request is! FloatingRateRequest) {
+ throw Exception("fixed rate unsupported");
+ }
+
+ // must support both
+ if (!_isSolanaCurrency(request.depositCurrency) || !_isSolanaCurrency(request.payoutCurrency)) {
+ throw Exception("unsupported");
+ }
+ final inputMint = _getTokenMint(request.depositCurrency);
+ final outputMint = _getTokenMint(request.payoutCurrency);
+
+ final orderData = await _api.send(
+ JupiterOrderRequest(
+ inputMint: inputMint,
+ outputMint: outputMint,
+ amount: request.depositAmount.amount,
+ ),
+ );
+ final outAmount = orderData.outAmount;
+
+ return ProviderRate(
+ provider: description,
+ rate: ExchangeRate.fromAmounts(
+ request.depositAmount,
+ Money(outAmount, request.payoutCurrency),
+ ),
+ limits: ExchangeLimits(),
+ );
+ }
+
+ @override
+ Future<Trade> createTrade({required TradeRequest request}) async {
+ // must support both
+ if (!_isSolanaCurrency(request.depositCurrency) || !_isSolanaCurrency(request.payoutCurrency)) {
+ throw Exception("not supported currencies");
+ }
+
+ final inputMint = _getTokenMint(request.depositCurrency);
+ final outputMint = _getTokenMint(request.payoutCurrency);
+
+ final isInternalTransfer = request.refundAddress == request.payoutAddress;
+
+ final orderData = await _api.send(
+ JupiterOrderRequest(
+ inputMint: inputMint,
+ outputMint: outputMint,
+ amount: request.depositAmount.amount,
+ taker: request.refundAddress,
+ receiver: isInternalTransfer ? null : request.payoutAddress,
+ referralFee: _hasReferral ? _referralFee : null,
+ referralAccount: _hasReferral ? _referralAccount : null,
+ ),
+ mapError: (e) => TradeNotCreatedException(description, description: e.message),
+ );
+
+ if (orderData.errorCode != null || orderData.errorMessage != null) {
+ throw TradeNotCreatedException(
+ description,
+ description: "error code: ${orderData.errorCode}, error message: ${orderData.errorMessage}",
+ );
+ }
+
+ return JupiterTrade(
+ id: orderData.requestId,
+ provider: description,
+ refundAddress: request.refundAddress,
+ state: TradeState.created,
+ createdAt: DateTime.now(),
+ payoutAddress: request.payoutAddress,
+ routerData: orderData.transaction!,
+ routerValue: orderData.requestId,
+ fee: Money.fromInt(orderData.totalFee, CryptoCurrency.sol),
+ depositAmount: Money(orderData.inAmount, request.depositCurrency),
+ payoutAmount: Money(orderData.outAmount, request.payoutCurrency),
+ );
+ }
+
+ /// Executes a signed Jupiter swap transaction via Jupiter's /execute endpoint
+ Future<JupiterExecuteResponse> executeSwap({
+ required String signedTransaction,
+ required String requestId,
+ }) => _api.send(
+ JupiterExecuteRequest(signedTransaction: signedTransaction, requestId: requestId),
+ mapError: (e) => Exception("Failed to execute swap: ${e.message}"),
+ );
+
+ // the order's transaction carries a recent blockhash, so it can't land once that expires
+ // (~150 slots). an order that still has no signature by then was never executed
+ static const _orderTtl = Duration(minutes: 5);
+
+ @override
+ Future<Trade> updateTrade(Trade trade) async {
+ final txId = trade.txId;
+
+ if (txId == null || txId.isEmpty) {
+ final createdAt = trade.createdAt;
+ final isStale = createdAt == null || DateTime.now().difference(createdAt) > _orderTtl;
+ return isStale ? trade.copyWith(state: TradeState.expired) : trade;
+ }
+
+ if (trade.state == TradeState.completed || trade.state == TradeState.failed) {
+ return trade;
+ }
+
+ return trade.copyWith(
+ state: switch (await solana!.getTransactionResult(txId)) {
+ true => TradeState.completed,
+ false => TradeState.failed,
+ null => TradeState.processing,
+ },
+ );
+ }
+
+ @override
+ Future<PendingTransaction> createTransaction(WalletBase wallet, Trade trade) {
+ trade as JupiterTrade;
+
+ return solana!.signAndPrepareJupiterSwapTransaction(
+ wallet,
+ trade.routerData,
+ trade.routerValue,
+ trade.payoutAddress,
+ trade.depositAmount,
+ trade.fee,
+ );
+ }
+}
### lib/exchange/provider/jupiter_exchange_provider.dart
@@ -1,492 +0,0 @@
-import 'dart:convert';
-
-import 'package:cake_wallet/.secrets.g.dart' as secrets;
-import "package:cake_wallet/exchange/exchange_exceptions.dart";
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/limits.dart';
-import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
-import 'package:cake_wallet/exchange/trade.dart';
-import 'package:cake_wallet/exchange/trade_not_created_exception.dart';
-import 'package:cake_wallet/exchange/trade_request.dart';
-import 'package:cake_wallet/exchange/trade_state.dart';
-import 'package:cake_wallet/solana/solana.dart';
-import 'package:cake_wallet/utils/exchange_provider_logger.dart';
-import 'package:cw_core/amount_converter.dart';
-import 'package:cw_core/crypto_currency.dart';
-import "package:cw_core/exceptions/cake_exception.dart";
-import 'package:cw_core/utils/print_verbose.dart';
-import 'package:cw_core/utils/proxy_wrapper.dart';
-
-class JupiterExchangeProvider extends ExchangeProvider {
- JupiterExchangeProvider();
-
- // Jupiter only supports Solana native SOL and Solana tokens
- bool _isSolanaCurrency(CryptoCurrency currency) =>
- currency == CryptoCurrency.sol || currency.tag == 'SOL';
-
- static const _baseUrl = 'api.jup.ag';
- static const _orderPath = '/ultra/v1/order';
- static const _executePath = '/ultra/v1/execute';
-
- // Wrapped SOL address (native SOL)
- static const _nativeSolMint = 'So11111111111111111111111111111111111111112';
-
- @override
- String get title => 'Jupiter';
-
- @override
- bool get isAvailable => true;
-
- @override
- bool get isEnabled => true;
-
- @override
- bool get supportsFixedRate => false; // Jupiter doesn't support fixed rate
-
- @override
- bool get supportsMemoOrDestinationTag => false;
-
- @override
- ExchangeProviderDescription get description => ExchangeProviderDescription.jupiter;
-
- @override
- Future<bool> checkIsAvailable() async => true;
-
- String _getTokenMint(CryptoCurrency currency) {
- // Handle native SOL
- if (currency == CryptoCurrency.sol) return _nativeSolMint;
-
- // Check if currency tag is SOL (indicating it's a Solana token)
- if (currency.tag != 'SOL') {
- throw BadCurrencyException('Unsupported currency: ${currency.title} (not a Solana token)', currency);
- }
-
- // Use solana proxy to get token address
- // The proxy will handle both SPLToken instances and CryptoCurrency
- // by searching through default tokens
- if (solana != null) {
- try {
- return solana!.getTokenAddress(currency);
- } catch (e) {
- printV('Error getting token address: $e');
- throw BadCurrencyException('Unsupported currency: ${currency.title} (mint address not found: $e)', currency);
- }
- }
-
- throw BadCurrencyException('Unsupported currency: ${currency.title} (Solana proxy not available)', currency);
- }
-
- @override
- Future<Limits?> fetchLimits({
- required CryptoCurrency from,
- required CryptoCurrency to,
- required bool isFixedRateMode,
- }) async {
- // The Ultra Swap API doesn't have a dedicated limits endpoint
- // The /order endpoint validates amounts and returns error codes:
- // - errorCode 1: Insufficient funds
- // - errorCode 2: Top up SOL for gas
- // - errorCode 3: Minimum amount for gasless
-
- // only return null for supported currencies
- if (_isSolanaCurrency(from) && _isSolanaCurrency(to)) {
- return Limits(min: null, max: null);
- } else {
- throw BadCurrencyPairException('not supported', from, to);
- }
- }
-
- Map<String, String> _getHeaders() {
- final headers = <String, String>{};
- final apiKey = secrets.jupiterApiKey;
- if (apiKey.isNotEmpty) {
- headers['x-api-key'] = apiKey;
- }
-
- return headers;
- }
-
- Map<String, String>? _getReferralFeeConfig() {
- try {
- final referralFeeBpsStr = secrets.jupiterReferralFeeBps;
- final referralFeeBps = int.tryParse(referralFeeBpsStr) ?? 0;
-
- final referralAccount = secrets.jupiterReferralAccount;
-
- // Only enable if both are configured and valid
- if (referralFeeBps <= 0 || referralFeeBps > 10000 || referralAccount.isEmpty) {
- return null;
- }
-
- return {
- 'referralFee': referralFeeBps.toString(),
- 'referralAccount': referralAccount,
- };
- } catch (e) {
- return null;
- }
- }
-
- @override
- Future<double> fetchRate({
- required CryptoCurrency from,
- required CryptoCurrency to,
- required double amount,
- required bool isFixedRateMode,
- required bool isReceiveAmount,
- }) async {
- try {
- // must support both
- if (!_isSolanaCurrency(from) || !_isSolanaCurrency(to)) {
- return 0.0;
- }
-
- if (amount <= 0) {
- return 0.0;
- }
- final inputMint = _getTokenMint(from);
- final outputMint = _getTokenMint(to);
-
- final amountInBaseUnits = AmountConverter.toBaseUnits(amount.toString(), from.decimals);
-
- final params = {
- 'inputMint': inputMint,
- 'outputMint': outputMint,
- 'amount': amountInBaseUnits,
- // Note: taker is optional for quote-only requests
- };
-
- final uri = Uri.https(_baseUrl, _orderPath, params);
- final headers = _getHeaders();
-
- final response = await ProxyWrapper().get(
- clearnetUri: uri,
- headers: headers,
- );
-
- if (response.statusCode != 200) {
- ExchangeProviderLogger.logError(
- provider: description,
- function: 'fetchRate',
- error: Exception('Failed to fetch quote: ${response.statusCode}'),
- stackTrace: StackTrace.current,
- requestData: {
- 'from': from.title,
- 'to': to.title,
- 'amount': amount,
- 'isFixedRateMode': isFixedRateMode,
- 'isReceiveAmount': isReceiveAmount,
- },
- );
- return 0.0;
- }
-
- final orderData = json.decode(response.body) as Map<String, dynamic>;
- final outAmount = BigInt.parse(orderData['outAmount'] as String);
-
- final outputAmount = AmountConverter.fromBaseUnits(outAmount.toString(), to.decimals);
-
- final rate = double.parse(outputAmount) / amount;
-
- ExchangeProviderLogger.logSuccess(
- provider: description,
- function: 'fetchRate',
- requestData: {
- 'from': from.title,
- 'to': to.title,
- 'amount': amount,
- 'isFixedRateMode': isFixedRateMode,
- 'isReceiveAmount': isReceiveAmount,
- },
- responseData: {
- 'rate': rate,
- 'outputAmount': outputAmount,
- },
- );
-
- 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('fetchRate error: $e');
- return 0.0;
- }
- }
-
- @override
- Future<Trade> createTrade({
- required TradeRequest request,
- required bool isFixedRateMode,
- required bool isSendAll,
- }) async {
- try {
- // must support both
- if (!_isSolanaCurrency(request.fromCurrency) || !_isSolanaCurrency(request.toCurrency)) {
- throw 'not supported currencies';
- }
-
- final inputMint = _getTokenMint(request.fromCurrency);
- final outputMint = _getTokenMint(request.toCurrency);
-
- final amountInBaseUnits =
- AmountConverter.toBaseUnits(request.fromAmount, request.fromCurrency.decimals);
-
- final isInternalTransfer = request.refundAddress == request.toAddress;
-
- final orderParams = <String, String>{
- 'inputMint': inputMint,
- 'outputMint': outputMint,
- 'amount': amountInBaseUnits,
- 'taker': request.refundAddress,
- if (!isInternalTransfer) 'receiver': request.toAddress,
- };
-
- final referralFeeConfig = _getReferralFeeConfig();
- if (referralFeeConfig != null) {
- orderParams['referralFee'] = referralFeeConfig['referralFee']!;
- orderParams['referralAccount'] = referralFeeConfig['referralAccount']!;
- }
-
- final orderUri = Uri.https(_baseUrl, _orderPath, orderParams);
- final headers = _getHeaders();
-
- final orderResponse = await ProxyWrapper().get(clearnetUri: orderUri, headers: headers);
-
- if (orderResponse.statusCode != 200) {
- final errorBody = orderResponse.body;
- ExchangeProviderLogger.logError(
- provider: description,
- function: 'createTrade',
- error: Exception('Failed to get order: ${orderResponse.statusCode} $errorBody'),
- 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,
- },
- );
- throw TradeNotCreatedException(description);
- }
-
- final orderData = json.decode(orderResponse.body) as Map<String, dynamic>;
-
- // Check for errors in response
- if (orderData.containsKey('errorCode') || orderData.containsKey('errorMessage')) {
- final errorCode = orderData['errorCode'];
- final errorMessage = orderData['errorMessage'] ?? 'Unknown error';
- ExchangeProviderLogger.logError(
- provider: description,
- function: 'createTrade',
- error: Exception('Order error: $errorCode - $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,
- },
- );
- throw TradeNotCreatedException(description);
- }
-
- // Extract response data
- final transaction = orderData['transaction'] as String?;
- final requestId = orderData['requestId'] as String?;
- final outAmount = orderData['outAmount'] as String? ?? '0.0';
-
- // Extract network fees from order response (in lamports)
- final signatureFeeLamports = (orderData['signatureFeeLamports'] as num?)?.toInt() ?? 0;
-
- final prioritizationFeeLamports =
- (orderData['prioritizationFeeLamports'] as num?)?.toInt() ?? 0;
-
- final rentFeeLamports = (orderData['rentFeeLamports'] as num?)?.toInt() ?? 0;
-
- final integratorFeeLamports = (orderData['integratorFeeLamports'] as num?)?.toInt() ?? 0;
-
- final networkFeeLamports = signatureFeeLamports + prioritizationFeeLamports + rentFeeLamports;
- final networkFeeInSol = networkFeeLamports / 1000000000.0;
-
- final integratorFeeInSol = integratorFeeLamports / 1000000000.0;
-
- final totalFeeInSol = networkFeeInSol + integratorFeeInSol;
-
- if (transaction == null || transaction.isEmpty) {
- throw TradeNotCreatedException( description, description: 'No transaction returned from Jupiter order endpoint', );
- }
-
- if (requestId == null || requestId.isEmpty) {
- throw TradeNotCreatedException( description,description: 'No requestId returned from Jupiter order endpoint');
- }
-
- final receiveAmount = AmountConverter.fromBaseUnits(outAmount, request.toCurrency.decimals);
-
- 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,
- },
- responseData: {
- 'tradeId': requestId,
- 'receiveAmount': receiveAmount,
- 'hasTransaction': transaction.isNotEmpty,
- 'requestId': requestId,
- },
- );
-
- return Trade(
- id: requestId,
- from: request.fromCurrency,
- to: request.toCurrency,
- provider: description,
- inputAddress: request.toAddress,
- refundAddress: request.refundAddress,
- state: TradeState.created,
- createdAt: DateTime.now(),
- amount: request.fromAmount,
- receiveAmount: receiveAmount,
- payoutAddress: request.toAddress,
- isSendAll: isSendAll,
- routerData: transaction,
- routerValue: requestId,
- fee: totalFeeInSol,
- );
- } 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('createTrade error: $e');
- if(e is! ExchangeProviderResponseException) throw TradeNotCreatedException(description, description: e.toString());
- rethrow;
- }
- }
-
- /// Executes a signed Jupiter swap transaction via Jupiter's /execute endpoint
- Future<Map<String, dynamic>> executeSwap({
- required String signedTransaction,
- required String requestId,
- }) async {
- try {
- final executeUri = Uri.https(_baseUrl, _executePath);
- final headers = _getHeaders();
- headers['Content-Type'] = 'application/json';
-
- final body = json.encode({
- 'signedTransaction': signedTransaction,
- 'requestId': requestId,
- });
-
- final response = await ProxyWrapper().post(
- clearnetUri: executeUri,
- headers: headers,
- body: body,
- );
-
- if (response.statusCode != 200) {
- final errorBody = response.body;
- ExchangeProviderLogger.logError(
- provider: description,
- function: 'executeSwap',
- error: TradeExecutionException('Failed to execute swap: ${response.statusCode} $errorBody'),
- stackTrace: StackTrace.current,
- requestData: {
- 'requestId': requestId,
- 'hasSignedTransaction': signedTransaction.isNotEmpty,
- },
- );
- throw TradeExecutionException('Failed to execute swap: ${response.statusCode} $errorBody');
- }
-
- final executeData = json.decode(response.body) as Map<String, dynamic>;
-
- ExchangeProviderLogger.logSuccess(
- provider: description,
- function: 'executeSwap',
- requestData: {
- 'requestId': requestId,
- 'hasSignedTransaction': signedTransaction.isNotEmpty,
- },
- responseData: executeData,
- );
-
- return executeData;
- } catch (e, s) {
- ExchangeProviderLogger.logError(
- provider: description,
- function: 'executeSwap',
- error: e,
- stackTrace: s,
- requestData: {
- 'requestId': requestId,
- 'hasSignedTransaction': signedTransaction.isNotEmpty,
- },
- );
- if(e is! ExchangeProviderResponseException) throw TradeExecutionException(e.toString());
- rethrow;
- }
- }
-
- @override
- Future<Trade> findTradeById({required String id}) async {
- // Jupiter Ultra Swap API doesn't track trades by our trade ID
- //
- // Status tracking options:
- // 1. Use /execute endpoint with requestId + signedTransaction (requires storing signed tx)
- // 2. Check on-chain via transaction signature (txId) after transaction is sent
- //
- // Current implementation: We track status on-chain via transaction signature
- // The txId field in Trade is set after the transaction is sent and can be
- // used to check transaction status via Solana RPC.
- //
- // Note: To use /execute endpoint for status polling, we would need to:
- // - Store the signed transaction (not currently stored)
- // - Use requestId from routerValue
- // - Poll /ultra/v1/execute with both signedTransaction and requestId
- //
- // For now, throw exception to indicate status must be checked on-chain
- throw ExchangeProviderResponseException(
- 'Jupiter trade status must be checked on-chain using transaction signature (txId). '
- 'After transaction is sent, txId will contain the signature for status checking.');
- }
-}
### lib/exchange/provider/near_Intents_exchange_provider.dart
@@ -1,627 +0,0 @@
-import 'dart:convert';
-
-import 'package:cake_wallet/.secrets.g.dart' as secrets;
-import 'package:cake_wallet/core/utilities.dart';
-import "package:cake_wallet/exchange/exchange_exceptions.dart";
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/limits.dart';
-import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
-import 'package:cake_wallet/exchange/trade.dart';
-import 'package:cake_wallet/exchange/trade_not_created_exception.dart';
-import 'package:cake_wallet/exchange/trade_request.dart';
-import 'package:cake_wallet/exchange/trade_state.dart';
-import 'package:cw_core/amount_converter.dart';
-import "package:cw_core/exceptions/cake_exception.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:cake_wallet/utils/exchange_provider_logger.dart';
-
-class NearIntentsExchangeProvider extends ExchangeProvider {
- NearIntentsExchangeProvider();
-
- static const apiKey = secrets.nearIntentsBearerToken;
- static const _baseUrl = '1click.chaindefuser.com';
- static const _versionPath = '/v0';
- static const _tokenPath = '/tokens';
- static const _quotePath = '/quote';
- static const _statusPath = '/status';
-
- static const _slippageTolerance = 100; // 1%
- static const _appFeesNearIntents = secrets.nearIntentsAppFee;
- static const _appFeeRecipientNearIntents = secrets.nearIntentsAppFeeRecipient;
-
- static const _memoRequiredCurrencies = <CryptoCurrency>[
- CryptoCurrency.xrp,
- CryptoCurrency.xlm,
- CryptoCurrency.ton,
- ];
-
- /// Use these only for quote/rate testing (dummy data).
- static const Map<String, String> kNearDummyAddresses = {
- // UTXO
- 'LTC': 'ltc1qhdwz74m3wuuhppv2mckagqk9e2e49z5j4kucnv',
- 'BTC': 'bc1qzwdt09dgr5nle2fkv7h5s6axgjqpdyp5g5tumz',
- 'DOGE': 'D9t7rGQ9mE3hJ2z1w8pGQxkGmKjYwYc8pQ',
- 'BCH': 'qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a',
-
- // EVM (same address works for all EVM chains)
- 'ETH': '0x1111111111111111111111111111111111111111',
- 'BSC': '0x1111111111111111111111111111111111111111',
- 'POL': '0x1111111111111111111111111111111111111111',
- 'AVAXC': '0x1111111111111111111111111111111111111111',
- 'ARB': '0x1111111111111111111111111111111111111111',
- 'BASE': '0x1111111111111111111111111111111111111111',
- "ROB": "0x1111111111111111111111111111111111111111",
-
- // Others
- 'SOL': '11111111111111111111111111111111',
- 'XRP': 'rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe',
- 'TRX': 'T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb',
- 'TON': 'UQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c',
- 'XLM': 'GA3D5O2W7YQZJQ3H4Y5QW6N7V8X9Z0A1B2C3D4E5F6G7H8I9J0',
- 'ADA': 'addr1vyc33hdv5vag52f3d8h0qsngu52vm27x28zkzru333jma9gaxd38v',
- 'ZEC': 't1VdfFUbyTT7ZSdeEaHuwB7veGD1NXoUhGS',
- };
-
- String getNearDummyAddress(CryptoCurrency currency) {
- final tag = (currency.tag ?? '').trim().toUpperCase();
- final title = currency.title.toUpperCase();
- final key = tag.isEmpty ? title : tag;
- return kNearDummyAddresses[key] ?? '';
- }
-
- static final Map<String, String> _headers = {
- 'Accept': 'application/json',
- 'Content-Type': 'application/json',
- 'Authorization': '$apiKey',
- };
-
- static final _supportedTokensList = <Token>[];
-
- @override
- String get title => 'Near Intents';
-
- @override
- bool get isAvailable => true;
-
- @override
- bool get isEnabled => true;
-
- @override
- bool get supportsFixedRate => true;
-
- @override
- bool get supportsMemoOrDestinationTag => false;
-
- @override
- ExchangeProviderDescription get description => ExchangeProviderDescription.nearIntents;
-
- @override
- Future<bool> checkIsAvailable() async => true;
-
- @override
- Future<Limits?> fetchLimits(
- {required CryptoCurrency from,
- required CryptoCurrency to,
- required bool isFixedRateMode}) async {
- final tokens = await _geSupportedTokens();
- final originToken = currencyToNearAssetId(from, tokens);
- final destinationToken = currencyToNearAssetId(to, tokens);
-
- if (originToken == null || destinationToken == null) {
- throw BadCurrencyPairException(
- 'fetchLimits: unsupported currency pair: ${from.title} ${from.tag ?? ''} to ${to.title} ${to.tag ?? ''}', from, to);
- }
-
- return Limits(min: null, max: null);
- }
-
- @override
- Future<double> fetchRate({
- required CryptoCurrency from,
- required CryptoCurrency to,
- required double amount,
- required bool isFixedRateMode,
- required bool isReceiveAmount,
- }) async {
- final tokens = await _geSupportedTokens();
- final originToken = currencyToNearAssetId(from, tokens);
- final destinationToken = currencyToNearAssetId(to, tokens);
-
- try {
- if (originToken == null || destinationToken == null) {
- throw BadCurrencyPairException('fetchRate: Unsupported currency pair', from, to);
- }
-
- final formattedAmount = AmountConverter.toBaseUnits(
- amount.toString(), isFixedRateMode ? destinationToken.decimals : originToken.decimals);
-
- final dummyAddrFrom = getNearDummyAddress(from);
- final dummyAddrTo = getNearDummyAddress(to);
-
- final depositMode = _memoRequiredCurrencies.contains(from) ? "MEMO" : "SIMPLE";
-
- final quote = await getSwapQuote(
- dry: true,
- isFixedRateMode: isFixedRateMode,
- originAsset: originToken.assetId,
- destinationAsset: destinationToken.assetId,
- amount: formattedAmount,
- depositMode: depositMode,
- refundTo: dummyAddrFrom,
- recipient: dummyAddrTo,
- );
-
- if (quote == null) {
- throw ExchangeProviderResponseException('fetchRate: Quote returned null');
- }
-
- final q = quote['quote'] as Map<String, dynamic>;
- final amountIn = double.tryParse(q['amountInFormatted']?.toString() ?? '0') ?? 0.0;
- final amountOut = double.tryParse(q['amountOutFormatted']?.toString() ?? '0') ?? 0.0;
-
- if (amountIn == 0) return 0.0;
-
- final rate = amountOut / amountIn;
-
- ExchangeProviderLogger.logSuccess(
- provider: description,
- function: 'fetchRate',
- requestData: {
- 'from': from.title,
- 'to': to.title,
- 'amount': amount,
- 'formattedAmount': formattedAmount,
- 'isFixedRateMode': isFixedRateMode,
- 'isReceiveAmount': isReceiveAmount,
- 'originAsset': originToken.assetId,
- 'destinationAsset': destinationToken.assetId,
- },
- responseData: {
- 'amountIn': amountIn,
- 'amountOut': amountOut,
- '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 {
- try {
- final tokens = await _geSupportedTokens();
- final originToken = currencyToNearAssetId(request.fromCurrency, tokens);
- final destinationToken = currencyToNearAssetId(request.toCurrency, tokens);
-
- if (originToken == null || destinationToken == null) {
- throw BadCurrencyPairException('Unsupported currency pair', request.fromCurrency, request.toCurrency);
- }
-
- final rawAmountStr = isFixedRateMode ? request.toAmount : request.fromAmount;
-
- final baseAmount = AmountConverter.toBaseUnits(
- rawAmountStr,
- isFixedRateMode ? request.toCurrency.decimals : request.fromCurrency.decimals,
- );
-
- final depositMode =
- _memoRequiredCurrencies.contains(request.fromCurrency) ? "MEMO" : "SIMPLE";
-
- final quote = await getSwapQuote(
- dry: false,
- isFixedRateMode: isFixedRateMode,
- originAsset: originToken.assetId,
- destinationAsset: destinationToken.assetId,
- depositMode: depositMode,
- amount: baseAmount,
- refundTo: request.refundAddress,
- recipient: request.toAddress,
- );
-
- if (quote == null) {
- throw ExchangeProviderResponseException('Quote request failed');
- }
-
- final quoteObj = quote['quote'] as Map<String, dynamic>;
- final depositAddress = quoteObj['depositAddress'] as String;
- final depositMemo = quoteObj['depositMemo'] as String?;
- final depositAmount = quoteObj['amountInFormatted'] as String?;
-
- if (depositAmount == null) {
- throw ExchangeProviderResponseException('Deposit amount is null in quote response');
- }
-
- final quoteRequest = quote['quoteRequest'] as Map<String, dynamic>;
- final fromAssetId = quoteRequest['originAsset'] as String;
- final toAssetId = quoteRequest['destinationAsset'] as String;
-
- final fromCurrency = _nearAssetIdToCurrency(fromAssetId, tokens);
- if (fromCurrency == null) {
- throw CurrencyParseException('Failed to parse from currency from assetId: $fromAssetId');
- }
-
- final toCurrency = _nearAssetIdToCurrency(toAssetId, tokens);
- if (toCurrency == null) {
- throw CurrencyParseException('Failed to parse to currency from assetId: $toAssetId');
- }
-
- final from =
- CryptoCurrency.safeParseCurrencyFromString(fromCurrency.$1, tag: fromCurrency.$2);
- final to = CryptoCurrency.safeParseCurrencyFromString(toCurrency.$1, tag: toCurrency.$2);
-
- final trade = Trade(
- id: depositAddress,
- // Using deposit address as trade ID
- from: request.fromCurrency,
- to: request.toCurrency,
- provider: description,
- providerName: title,
- state: TradeState.created,
- createdAt: DateTime.now(),
- inputAddress: depositAddress,
- payoutAddress: request.toAddress,
- refundAddress: request.refundAddress,
- amount: depositAmount,
- receiveAmount: quoteObj['amountOutFormatted']?.toString(),
- memo: depositMemo,
- isSendAll: isSendAll,
- );
-
- ExchangeProviderLogger.logSuccess(
- provider: description,
- function: 'createTrade',
- requestData: {
- 'from': request.fromCurrency.title,
- 'to': request.toCurrency.title,
- 'fromAmount': request.fromAmount,
- 'toAmount': request.toAmount,
- 'refundAddress': request.refundAddress,
- 'recipient': request.toAddress,
- 'isFixedRateMode': isFixedRateMode,
- 'isSendAll': isSendAll,
- 'originAsset': originToken.assetId,
- 'destinationAsset': destinationToken.assetId,
- },
- responseData: {
- 'correlationId': quote['correlationId'],
- 'depositAddress': depositAddress,
- 'depositMemo': depositMemo,
- 'quote': quoteObj,
- },
- );
-
- return trade;
- } 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,
- 'refundAddress': request.refundAddress,
- 'recipient': request.toAddress,
- 'isFixedRateMode': isFixedRateMode,
- 'isSendAll': isSendAll,
- },
- );
- throw TradeNotCreatedException(description, description: e.toString());
- }
- }
-
- @override
- Future<Trade> findTradeById({required String id}) async {
- final param = {'depositAddress': id};
- final uri = Uri.https(_baseUrl, '$_versionPath$_statusPath', param);
-
- final response = await ProxyWrapper().get(clearnetUri: uri, headers: _headers);
-
- if (response.statusCode != 200) {
- throw ExchangeProviderResponseCodeException(
- 'Near Intents fetch trade failed: ${response.statusCode} ${response.body}', response.statusCode
- );
- }
-
- final data = jsonDecode(response.body) as Map<String, dynamic>;
- final statusRaw = (data['status'] as String?) ?? 'UNKNOWN';
-
- final quoteResponse = data['quoteResponse'] as Map<String, dynamic>? ?? {};
- final quoteRequest = quoteResponse['quoteRequest'] as Map<String, dynamic>? ?? {};
-
- final refundTo = quoteRequest['refundTo'] as String? ?? '';
- final recipient = quoteRequest['recipient'] as String? ?? '';
-
- // Parsing 'from' currency
- final originAssetId = quoteRequest['originAsset'] as String? ?? '';
- final from = _nearAssetIdToCurrency(originAssetId, await _geSupportedTokens());
-
- CryptoCurrency? coinFrom;
- CryptoCurrency? coinTo;
-
- if (from != null) {
- coinFrom = CryptoCurrency.safeParseCurrencyFromString(from.$1, tag: from.$2);
- }
-
- // Parsing 'to' currency
- final destinationAssetId = quoteRequest['destinationAsset'] as String? ?? '';
-
- final to = _nearAssetIdToCurrency(destinationAssetId, await _geSupportedTokens());
-
- if (to != null) {
- coinTo = CryptoCurrency.safeParseCurrencyFromString(to.$1, tag: to.$2);
- }
-
- final quote = quoteResponse['quote'] as Map<String, dynamic>? ?? {};
- final swap = data['swapDetails'] as Map<String, dynamic>? ?? {};
-
- final depositAddress = quote['depositAddress'] as String?;
- final depositMemo = quote['depositMemo'] as String?;
-
- final depositAmount =
- swap['amountInFormatted']?.toString() ?? quote['amountInFormatted']?.toString() ?? '0';
-
- final receiveAmount =
- swap['amountOutFormatted']?.toString() ?? quote['amountOutFormatted']?.toString();
-
- final originTxHash = (swap['originChainTxHashes'] as List?)?.firstOrNull?['hash']?.toString();
-
- return Trade(
- id: id,
- from: coinFrom,
- to: coinTo,
- provider: description,
- inputAddress: depositAddress,
- payoutAddress: recipient,
- refundAddress: refundTo,
- amount: depositAmount,
- receiveAmount: receiveAmount,
- state: _normalizeStatusToTradeState(statusRaw),
- txId: originTxHash,
- extraId: depositMemo,
- isRefund: statusRaw == 'REFUNDED',
- );
- }
-
- // Load & cache supported tokens
- Future<List<Token>> _geSupportedTokens() async {
- if (_supportedTokensList.isNotEmpty) return _supportedTokensList;
-
- try {
- final uri = Uri.https(_baseUrl, '$_versionPath$_tokenPath');
-
- final response = await ProxyWrapper().get(clearnetUri: uri, headers: _headers);
- if (response.statusCode != 200) return [];
-
- final data = json.decode(response.body) as List<dynamic>;
- _supportedTokensList
- ..clear()
- ..addAll(data.map((e) => Token.fromJson(e as Map<String, dynamic>)));
- return _supportedTokensList;
- } catch (e) {
- printV(e);
- return [];
- }
- }
-
- Future<Map<String, dynamic>?> getSwapQuote({
- required bool dry,
- required bool isFixedRateMode,
- required String originAsset,
- required String destinationAsset,
- required String amount,
- required String refundTo,
- required String recipient,
- required String depositMode,
- List<String>? connectedWallets,
- String? sessionId,
- String? virtualChainRecipient,
- String? virtualChainRefundRecipient,
- String? customRecipientMsg,
- String? deadline,
- String? referral,
- int? quoteWaitingTimeMs,
- }) async {
- final swapType = isFixedRateMode ? 'EXACT_OUTPUT' : 'EXACT_INPUT';
- final _isoUtcDeadline = _buildDeadline();
- final appFees = [
- {
- "recipient": _appFeeRecipientNearIntents,
- "fee": _appFeesNearIntents,
- }
- ];
-
- final uri = Uri.https(_baseUrl, "$_versionPath$_quotePath");
-
- final payload = {
- "dry": dry,
- "depositMode": depositMode,
- "swapType": swapType,
- "slippageTolerance": _slippageTolerance,
- "originAsset": originAsset,
- "depositType": 'ORIGIN_CHAIN',
- "destinationAsset": destinationAsset,
- "amount": amount,
- "refundTo": refundTo,
- "refundType": 'ORIGIN_CHAIN',
- "recipient": recipient,
- "recipientType": 'DESTINATION_CHAIN',
- "deadline": _isoUtcDeadline,
- if (connectedWallets != null) "connectedWallets": connectedWallets,
- if (sessionId != null) "sessionId": sessionId,
- if (virtualChainRecipient != null) "virtualChainRecipient": virtualChainRecipient,
- if (virtualChainRefundRecipient != null)
- "virtualChainRefundRecipient": virtualChainRefundRecipient,
- if (customRecipientMsg != null) "customRecipientMsg": customRecipientMsg,
- if (deadline != null) "deadline": deadline,
- if (referral != null) "referral": referral,
- if (quoteWaitingTimeMs != null) "quoteWaitingTimeMs": quoteWaitingTimeMs,
- "appFees": appFees,
- };
-
- try {
- final response = await ProxyWrapper().post(
- clearnetUri: uri,
- headers: _headers,
- body: jsonEncode(payload),
- );
-
- if (response.statusCode != 201) {
- printV("Quote request failed with status: ${response.statusCode}");
- return null;
- }
-
- return jsonDecode(response.body) as Map<String, dynamic>;
- } catch (e) {
- printV("Quote error: $e");
- return null;
- }
- }
-
- TradeState _normalizeStatusToTradeState(String status) {
- return switch (status.toUpperCase()) {
- 'PENDING_DEPOSIT' => TradeState.pending,
- 'PROCESSING' => TradeState.processing,
- 'SUCCESS' => TradeState.success,
- 'INCOMPLETE_DEPOSIT' => TradeState.underpaid,
- 'REFUNDED' => TradeState.refunded,
- 'FAILED' => TradeState.failed,
- _ => TradeState.notFound,
- };
- }
-
- String? _normalizeTagToNearBlockchain(String? tag) {
- return switch (tag) {
- 'TRX' => 'tron',
- 'AVAXC' => 'avax',
- "ROB" => "hood",
- _ => tag?.toLowerCase(),
- };
- }
-
- String? _normalizeNearBlockchainToTag(String? blockchain) {
- return switch (blockchain) {
- 'tron' => 'TRX',
- 'avax' => 'AVAXC',
- "hood" => "ROB",
- _ => blockchain?.toUpperCase(),
- };
- }
-
- Token? currencyToNearAssetId(CryptoCurrency currency, List<Token> supported) {
- if (supported.isEmpty) return null;
-
- final symbol = currency.title.toUpperCase();
- final blockchain = _normalizeTagToNearBlockchain(currency.tag);
-
-// Use the native Bitcoin asset routed through Omni Bridge.
- if (currency == CryptoCurrency.btc) {
- return supported.firstWhereOrNull(
- (t) => t.assetId == '1cs_v1:btc:native:coin',
- );
- }
-
- // Native asset (no contract)
- final native = supported.firstWhereOrNull((t) =>
- t.symbol.toUpperCase() == symbol &&
- (blockchain == null || t.blockchain.toLowerCase() == blockchain) &&
- t.contractAddress == null);
-
- if (native != null) {
- return native;
- }
-
- final token = supported.firstWhereOrNull((t) =>
- t.symbol.toUpperCase() == symbol &&
- (blockchain == null || t.blockchain.toLowerCase() == blockchain));
-
- return token;
- }
-
- (String, String?)? _nearAssetIdToCurrency(String assetId, List<Token> supported) {
- if (supported.isEmpty) return null;
-
- final token = supported.firstWhereOrNull((t) => t.assetId == assetId);
-
- if (token == null) return null;
-
- final title = token.symbol.toUpperCase().replaceAll(RegExp(r'\s*\([^)]*\)'), '');
-
- final normalizedNetwork = _normalizeNearBlockchainToTag(token.blockchain);
-
- final isNativeAsset = assetId.contains(':native:coin');
-
- final tag = isNativeAsset || normalizedNetwork == title ? null : normalizedNetwork;
-
- return (title, tag);
- }
-
- String _buildDeadline() {
- return DateTime.now()
- .toUtc()
- .add(const Duration(hours: 1))
- .toIso8601String()
- .replaceFirst(RegExp(r'\.\d+Z$'), 'Z');
- }
-}
-
-class Token {
- final String assetId;
- final int decimals;
- final String blockchain;
- final String symbol;
- final double priceUsd;
- final String? priceUpdatedAt;
- final String? contractAddress;
-
- Token({
- required this.assetId,
- required this.decimals,
- required this.blockchain,
- required this.symbol,
- required this.priceUsd,
- required this.priceUpdatedAt,
- required this.contractAddress,
- });
-
- factory Token.fromJson(Map<String, dynamic> json) {
- final decimals = json['decimals'] as int?;
- if (decimals == null) {
- throw ExchangeProviderResponseException('Token decimals is null for assetId: ${json['assetId']}');
- }
- return Token(
- assetId: json['assetId'] as String,
- decimals: json['decimals'] as int,
- blockchain: json['blockchain'] as String,
- symbol: json['symbol'] as String,
- priceUsd: (json['price'] as num?)?.toDouble() ?? 0.0,
- priceUpdatedAt: json['priceUpdatedAt'] as String?,
- contractAddress: json['contractAddress'] as String?,
- );
- }
-}
### lib/exchange/provider/near_intents/near_intents_api_schema.dart
@@ -0,0 +1,523 @@
+// spec reference: https://1click.chaindefuser.com/docs/v0/openapi.yaml
+
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/exchange/utils/provider_api.dart";
+import "package:json_annotation/json_annotation.dart";
+
+part "near_intents_api_schema.g.dart";
+
+
+enum NearIntentsSwapType {
+ @JsonValue("EXACT_INPUT")
+ exactInput,
+ @JsonValue("EXACT_OUTPUT")
+ exactOutput,
+ @JsonValue("FLEX_INPUT")
+ flexInput,
+ @JsonValue("ANY_INPUT")
+ anyInput,
+ unknown,
+}
+
+enum NearIntentsDepositType {
+ @JsonValue("ORIGIN_CHAIN")
+ originChain,
+ @JsonValue("INTENTS")
+ intents,
+ @JsonValue("CONFIDENTIAL_INTENTS")
+ confidentialIntents,
+ unknown,
+}
+
+enum NearIntentsRecipientType {
+ @JsonValue("DESTINATION_CHAIN")
+ destinationChain,
+ @JsonValue("INTENTS")
+ intents,
+ @JsonValue("CONFIDENTIAL_INTENTS")
+ confidentialIntents,
+ unknown,
+}
+
+enum NearIntentsDepositMode {
+ @JsonValue("SIMPLE")
+ simple,
+ @JsonValue("MEMO")
+ memo,
+ unknown,
+}
+
+enum NearIntentsStatus {
+ @JsonValue("KNOWN_DEPOSIT_TX")
+ knownDepositTx,
+ @JsonValue("PENDING_DEPOSIT")
+ pendingDeposit,
+ @JsonValue("INCOMPLETE_DEPOSIT")
+ incompleteDeposit,
+ @JsonValue("PROCESSING")
+ processing,
+ @JsonValue("SUCCESS")
+ success,
+ @JsonValue("REFUNDED")
+ refunded,
+ @JsonValue("FAILED")
+ failed,
+ unknown,
+}
+
+extension StatusToState on NearIntentsStatus {
+ TradeState get toState => switch(this) {
+ .pendingDeposit => .pending,
+ .knownDepositTx => .pending,
+ .processing => .processing,
+ .success => .success,
+ .incompleteDeposit => .underpaid,
+ .refunded => .refunded,
+ .failed => .failed,
+ _ => .notFound,
+ };
+}
+
+@JsonSerializable(createToJson: false)
+class NearIntentsErrorResponse {
+ const NearIntentsErrorResponse({required this.message});
+
+ factory NearIntentsErrorResponse.fromJson(Map<String, dynamic> json) =>
+ _$NearIntentsErrorResponseFromJson(json);
+
+ @JsonKey(name: "message")
+ final String message;
+}
+
+
+class NearIntentsTokensRequest extends ApiRequest<List<NearIntentsToken>> {
+ const NearIntentsTokensRequest();
+
+ @override
+ String path() => "/v0/tokens";
+
+ @override
+ Map<String, dynamic> toJson() => const {};
+
+ @override
+ List<NearIntentsToken> decode(Object json) => (json as List<dynamic>)
+ .map((item) => NearIntentsToken.fromJson(item as Map<String, dynamic>))
+ .toList();
+}
+
+@JsonSerializable(createToJson: false)
+class NearIntentsToken {
+ const NearIntentsToken({
+ required this.assetId,
+ required this.decimals,
+ required this.blockchain,
+ required this.symbol,
+ required this.price,
+ required this.priceUpdatedAt,
+ this.contractAddress,
+ this.coingeckoId,
+ });
+
+ factory NearIntentsToken.fromJson(Map<String, dynamic> json) =>
+ _$NearIntentsTokenFromJson(json);
+
+ @JsonKey(name: "assetId")
+ final String assetId;
+ @JsonKey(name: "decimals")
+ final int decimals;
+
+ @JsonKey(name: "blockchain")
+ final String blockchain;
+ @JsonKey(name: "symbol")
+ final String symbol;
+
+ @JsonKey(name: "price")
+ final double price;
+ @JsonKey(name: "priceUpdatedAt")
+ final DateTime priceUpdatedAt;
+ @JsonKey(name: "contractAddress")
+ final String? contractAddress;
+ @JsonKey(name: "coingeckoId")
+ final String? coingeckoId;
+}
+
+
+@JsonSerializable()
+class NearIntentsAppFee {
+ const NearIntentsAppFee({required this.recipient, required this.fee});
+
+ factory NearIntentsAppFee.fromJson(Map<String, dynamic> json) =>
+ _$NearIntentsAppFeeFromJson(json);
+
+ @JsonKey(name: "recipient")
+ final String recipient;
+
+ @JsonKey(name: "fee")
+ final int fee;
+
+ Map<String, dynamic> toJson() => _$NearIntentsAppFeeToJson(this);
+}
+
+@JsonSerializable()
+class NearIntentsRebate {
+ const NearIntentsRebate({required this.recipient, required this.share});
+
+ factory NearIntentsRebate.fromJson(Map<String, dynamic> json) =>
+ _$NearIntentsRebateFromJson(json);
+
+ @JsonKey(name: "recipient")
+ final String recipient;
+
+ @JsonKey(name: "share")
+ final int share;
+
+ Map<String, dynamic> toJson() => _$NearIntentsRebateToJson(this);
+}
+
+@JsonSerializable(explicitToJson: true)
+class NearIntentsQuoteRequest extends ApiRequest<NearIntentsQuoteResponse> {
+ const NearIntentsQuoteRequest({
+ required this.dry,
+ required this.swapType,
+ required this.slippageTolerance,
+ required this.originAsset,
+ required this.depositType,
+ required this.destinationAsset,
+ required this.amount,
+ required this.refundTo,
+ required this.refundType,
+ required this.recipient,
+ required this.recipientType,
+ required this.deadline,
+ this.depositMode,
+ this.connectedWallets,
+ this.sessionId,
+ this.virtualChainRecipient,
+ this.virtualChainRefundRecipient,
+ this.customRecipientMsg,
+ this.confidentiality,
+ this.referral,
+ this.rebates,
+ this.quoteWaitingTimeMs,
+ this.appFees,
+ this.insured,
+ }) : super.post();
+
+ factory NearIntentsQuoteRequest.fromJson(Map<String, dynamic> json) =>
+ _$NearIntentsQuoteRequestFromJson(json);
+
+ @JsonKey(name: "dry")
+ final bool dry;
+ @JsonKey(name: "depositMode", includeIfNull: false)
+ final NearIntentsDepositMode? depositMode;
+ @JsonKey(name: "swapType")
+ final NearIntentsSwapType swapType;
+
+ @JsonKey(name: "slippageTolerance")
+ final int slippageTolerance;
+
+ @JsonKey(name: "originAsset")
+ final String originAsset;
+ @JsonKey(name: "destinationAsset")
+ final String destinationAsset;
+ @JsonKey(name: "depositType")
+ final NearIntentsDepositType depositType;
+
+ @JsonKey(name: "amount")
+ final BigInt amount;
+ @JsonKey(name: "refundTo")
+ final String refundTo;
+ @JsonKey(name: "refundType")
+ final NearIntentsDepositType refundType;
+ @JsonKey(name: "recipient")
+ final String recipient;
+ @JsonKey(name: "recipientType")
+ final NearIntentsRecipientType recipientType;
+
+ @JsonKey(name: "deadline")
+ final DateTime deadline;
+ @JsonKey(name: "connectedWallets", includeIfNull: false)
+ final List<String>? connectedWallets;
+ @JsonKey(name: "sessionId", includeIfNull: false)
+ final String? sessionId;
+ @JsonKey(name: "virtualChainRecipient", includeIfNull: false)
+ final String? virtualChainRecipient;
+ @JsonKey(name: "virtualChainRefundRecipient", includeIfNull: false)
+ final String? virtualChainRefundRecipient;
+ @JsonKey(name: "customRecipientMsg", includeIfNull: false)
+ final String? customRecipientMsg;
+
+ @JsonKey(name: "confidentiality", includeIfNull: false)
+ final String? confidentiality;
+ @JsonKey(name: "referral", includeIfNull: false)
+ final String? referral;
+ @JsonKey(name: "rebates", includeIfNull: false)
+ final List<NearIntentsRebate>? rebates;
+
+ @JsonKey(name: "quoteWaitingTimeMs", includeIfNull: false)
+ final int? quoteWaitingTimeMs;
+ @JsonKey(name: "appFees", includeIfNull: false)
+ final List<NearIntentsAppFee>? appFees;
+ @JsonKey(name: "insured", includeIfNull: false)
+ final bool? insured;
+
+ @override
+ String path() => "/v0/quote";
+
+ @override
+ Map<String, dynamic> toJson() => _$NearIntentsQuoteRequestToJson(this);
+
+ @override
+ NearIntentsQuoteResponse decode(Object json) =>
+ NearIntentsQuoteResponse.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+class NearIntentsChainDepositAddress {
+ const NearIntentsChainDepositAddress({
+ required this.blockchain,
+ required this.address,
+ this.memo,
+ });
+
+ factory NearIntentsChainDepositAddress.fromJson(Map<String, dynamic> json) =>
+ _$NearIntentsChainDepositAddressFromJson(json);
+
+ @JsonKey(name: "blockchain")
+ final String blockchain;
+ @JsonKey(name: "address")
+ final String address;
+ @JsonKey(name: "memo")
+ final String? memo;
+}
+
+@JsonSerializable(createToJson: false)
+class NearIntentsQuote {
+ const NearIntentsQuote({
+ required this.amountIn,
+ required this.amountInFormatted,
+ required this.amountInUsd,
+ required this.minAmountIn,
+ required this.amountOut,
+ required this.amountOutFormatted,
+ required this.amountOutUsd,
+ required this.minAmountOut,
+ required this.timeEstimate,
+ this.depositAddress,
+ this.depositMemo,
+ this.chainDepositAddresses,
+ this.deadline,
+ this.timeWhenInactive,
+ this.virtualChainRecipient,
+ this.virtualChainRefundRecipient,
+ this.customRecipientMsg,
+ this.refundFee,
+ this.withdrawFee,
+ });
+
+ factory NearIntentsQuote.fromJson(Map<String, dynamic> json) => _$NearIntentsQuoteFromJson(json);
+
+ @JsonKey(name: "depositAddress")
+ final String? depositAddress;
+
+ @JsonKey(name: "depositMemo")
+ final String? depositMemo;
+
+ @JsonKey(name: "chainDepositAddresses")
+ final List<NearIntentsChainDepositAddress>? chainDepositAddresses;
+ @JsonKey(name: "amountIn")
+ final BigInt amountIn;
+ @JsonKey(name: "amountInFormatted")
+ final String amountInFormatted;
+ @JsonKey(name: "amountInUsd")
+ final String amountInUsd;
+ @JsonKey(name: "minAmountIn")
+ final BigInt minAmountIn;
+ @JsonKey(name: "amountOut")
+ final BigInt amountOut;
+ @JsonKey(name: "amountOutFormatted")
+ final String amountOutFormatted;
+ @JsonKey(name: "amountOutUsd")
+ final String amountOutUsd;
+ @JsonKey(name: "minAmountOut")
+ final BigInt minAmountOut;
+ @JsonKey(name: "deadline")
+ final DateTime? deadline;
+
+ @JsonKey(name: "timeWhenInactive")
+ final DateTime? timeWhenInactive;
+
+ @JsonKey(name: "timeEstimate")
+ final int timeEstimate;
+ @JsonKey(name: "virtualChainRecipient")
+ final String? virtualChainRecipient;
+ @JsonKey(name: "virtualChainRefundRecipient")
+ final String? virtualChainRefundRecipient;
+ @JsonKey(name: "customRecipientMsg")
+ final String? customRecipientMsg;
+ @JsonKey(name: "refundFee")
+ final BigInt? refundFee;
+ @JsonKey(name: "withdrawFee")
+ final BigInt? withdrawFee;
+}
+
+@JsonSerializable(createToJson: false)
+class NearIntentsQuoteResponse {
+ const NearIntentsQuoteResponse({
+ this.correlationId,
+ required this.timestamp,
+ required this.signature,
+ required this.quoteRequest,
+ required this.quote,
+ });
+
+ factory NearIntentsQuoteResponse.fromJson(Map<String, dynamic> json) =>
+ _$NearIntentsQuoteResponseFromJson(json);
+
+ @JsonKey(name: "correlationId")
+ final String? correlationId;
+
+ @JsonKey(name: "timestamp")
+ final DateTime timestamp;
+
+ @JsonKey(name: "signature")
+ final String signature;
+ @JsonKey(name: "quoteRequest")
+ final NearIntentsQuoteRequest quoteRequest;
+ @JsonKey(name: "quote")
+ final NearIntentsQuote quote;
+}
+
+
+@JsonSerializable(createToJson: false)
+class NearIntentsTransactionDetails {
+ const NearIntentsTransactionDetails({required this.hash, required this.explorerUrl});
+
+ factory NearIntentsTransactionDetails.fromJson(Map<String, dynamic> json) =>
+ _$NearIntentsTransactionDetailsFromJson(json);
+
+ @JsonKey(name: "hash")
+ final String hash;
+ @JsonKey(name: "explorerUrl")
+ final String explorerUrl;
+}
+
+@JsonSerializable(createToJson: false)
+class NearIntentsSwapDetails {
+ const NearIntentsSwapDetails({
+ required this.intentHashes,
+ required this.nearTxHashes,
+ required this.originChainTxHashes,
+ required this.destinationChainTxHashes,
+ this.amountIn,
+ this.amountInFormatted,
+ this.amountInUsd,
+ this.amountOut,
+ this.amountOutFormatted,
+ this.amountOutUsd,
+ this.slippage,
+ this.refundedAmount,
+ this.refundedAmountFormatted,
+ this.refundedAmountUsd,
+ this.refundReason,
+ this.depositedAmount,
+ this.depositedAmountFormatted,
+ this.depositedAmountUsd,
+ this.withdrawFee,
+ this.referral,
+ });
+
+ factory NearIntentsSwapDetails.fromJson(Map<String, dynamic> json) =>
+ _$NearIntentsSwapDetailsFromJson(json);
+
+ @JsonKey(name: "intentHashes")
+ final List<String> intentHashes;
+ @JsonKey(name: "nearTxHashes")
+ final List<String> nearTxHashes;
+
+ @JsonKey(name: "originChainTxHashes")
+ final List<NearIntentsTransactionDetails> originChainTxHashes;
+
+ @JsonKey(name: "destinationChainTxHashes")
+ final List<NearIntentsTransactionDetails> destinationChainTxHashes;
+
+ @JsonKey(name: "amountIn")
+ final BigInt? amountIn;
+ @JsonKey(name: "amountInFormatted")
+ final String? amountInFormatted;
+ @JsonKey(name: "amountInUsd")
+ final String? amountInUsd;
+ @JsonKey(name: "amountOut")
+ final BigInt? amountOut;
+ @JsonKey(name: "amountOutFormatted")
+ final String? amountOutFormatted;
+ @JsonKey(name: "amountOutUsd")
+ final String? amountOutUsd;
+
+ @JsonKey(name: "slippage")
+ final int? slippage;
+
+ @JsonKey(name: "depositedAmount")
+ final BigInt? depositedAmount;
+ @JsonKey(name: "depositedAmountFormatted")
+ final String? depositedAmountFormatted;
+ @JsonKey(name: "depositedAmountUsd")
+ final String? depositedAmountUsd;
+ @JsonKey(name: "refundedAmount")
+ final BigInt? refundedAmount;
+ @JsonKey(name: "refundedAmountFormatted")
+ final String? refundedAmountFormatted;
+ @JsonKey(name: "refundedAmountUsd")
+ final String? refundedAmountUsd;
+
+ @JsonKey(name: "refundReason")
+ final String? refundReason;
+ @JsonKey(name: "withdrawFee")
+ final BigInt? withdrawFee;
+ @JsonKey(name: "referral")
+ final String? referral;
+}
+
+@JsonSerializable(createFactory: false)
+class NearIntentsStatusRequest extends ApiRequest<NearIntentsStatusResponse> {
+ const NearIntentsStatusRequest({required this.depositAddress});
+
+ @JsonKey(name: "depositAddress")
+ final String depositAddress;
+
+ @override
+ String path() => "/v0/status";
+
+ @override
+ Map<String, dynamic> toJson() => _$NearIntentsStatusRequestToJson(this);
+
+ @override
+ NearIntentsStatusResponse decode(Object json) =>
+ NearIntentsStatusResponse.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+class NearIntentsStatusResponse {
+ const NearIntentsStatusResponse({
+ required this.correlationId,
+ required this.status,
+ required this.updatedAt,
+ required this.quoteResponse,
+ required this.swapDetails,
+ });
+
+ factory NearIntentsStatusResponse.fromJson(Map<String, dynamic> json) =>
+ _$NearIntentsStatusResponseFromJson(json);
+
+ @JsonKey(name: "correlationId")
+ final String correlationId;
+ @JsonKey(name: "status", unknownEnumValue: NearIntentsStatus.unknown)
+ final NearIntentsStatus status;
+ @JsonKey(name: "updatedAt")
+ final DateTime updatedAt;
+
+ @JsonKey(name: "quoteResponse")
+ final NearIntentsQuoteResponse quoteResponse;
+ @JsonKey(name: "swapDetails")
+ final NearIntentsSwapDetails swapDetails;
+}
### lib/exchange/provider/near_intents/near_intents_exchange_provider.dart
@@ -0,0 +1,336 @@
+import "package:cake_wallet/.secrets.g.dart" as secrets;
+import "package:cake_wallet/core/utilities.dart";
+import "package:cake_wallet/exchange/exchange_provider_description.dart";
+import "package:cake_wallet/exchange/provider/exchange_provider.dart";
+import "package:cake_wallet/exchange/provider/near_intents/near_intents_api_schema.dart";
+import "package:cake_wallet/exchange/rate_request.dart";
+import "package:cake_wallet/exchange/trade.dart";
+import "package:cake_wallet/exchange/trade_request.dart";
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/exchange/utils/provider_api.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/exchange_limits.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/provider_rate.dart";
+import "package:cw_core/amount/exchange_rate.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/crypto_currency.dart";
+
+class NearIntentsExchangeProvider extends ExchangeProvider {
+ NearIntentsExchangeProvider({super.proxyWrapper});
+
+ static const apiKey = secrets.nearIntentsBearerToken;
+ static const _baseUrl = "1click.chaindefuser.com";
+
+ static const _slippageTolerance = 100; // 1%
+ static final _appFeesNearIntents = int.tryParse(secrets.nearIntentsAppFee.toString());
+ static const _appFeeRecipientNearIntents = secrets.nearIntentsAppFeeRecipient;
+
+ static const _memoRequiredCurrencies = <CryptoCurrency>[
+ CryptoCurrency.xrp,
+ CryptoCurrency.xlm,
+ CryptoCurrency.ton,
+ ];
+
+ /// Use these only for quote/rate testing (dummy data).
+ static const Map<String, String> kNearDummyAddresses = {
+ // UTXO
+ "LTC": "ltc1qhdwz74m3wuuhppv2mckagqk9e2e49z5j4kucnv",
+ "BTC": "bc1qzwdt09dgr5nle2fkv7h5s6axgjqpdyp5g5tumz",
+ "DOGE": "D9t7rGQ9mE3hJ2z1w8pGQxkGmKjYwYc8pQ",
+ "BCH": "qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a",
+
+ // EVM (same address works for all EVM chains)
+ "ETH": "0x1111111111111111111111111111111111111111",
+ "BSC": "0x1111111111111111111111111111111111111111",
+ "POL": "0x1111111111111111111111111111111111111111",
+ "AVAXC": "0x1111111111111111111111111111111111111111",
+ "ARB": "0x1111111111111111111111111111111111111111",
+ "BASE": "0x1111111111111111111111111111111111111111",
+ "ROB": "0x1111111111111111111111111111111111111111",
+
+ // Others
+ "SOL": "11111111111111111111111111111111",
+ "XRP": "rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe",
+ "TRX": "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb",
+ "TON": "UQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c",
+ "XLM": "GBN7JCM6IGGDHMUMSNCOXGFJSIMXAOR6J3S53GSCXJ57YMW2DTRCONUH",
+ "ADA": "addr1vyc33hdv5vag52f3d8h0qsngu52vm27x28zkzru333jma9gaxd38v",
+ "ZEC": "t1VdfFUbyTT7ZSdeEaHuwB7veGD1NXoUhGS",
+ };
+
+ String getNearDummyAddress(CryptoCurrency currency) {
+ final tag = (currency.tag ?? "").trim().toUpperCase();
+ final title = currency.title.toUpperCase();
+ final key = tag.isEmpty ? title : tag;
+ return kNearDummyAddresses[key] ?? "";
+ }
+
+ late final _api = ProviderApi(
+ proxyWrapper,
+ authority: _baseUrl,
+ headers: {"Accept": "application/json", "Authorization": apiKey},
+ errorMessage: (json) => json["message"]?.toString(),
+ );
+
+ static final _supportedTokensList = <NearIntentsToken>[];
+
+ @override
+ bool get supportsFixedRate => true;
+
+ @override
+ ExchangeProviderDescription get description => ExchangeProviderDescription.nearIntents;
+
+ @override
+ Future<ExchangeLimits> fetchLimits({
+ required CryptoCurrency from,
+ required CryptoCurrency to,
+ required bool isFixedRateMode,
+ }) async {
+ final tokens = await _getSupportedTokens();
+ final originToken = currencyToNearAssetId(from, tokens);
+ final destinationToken = currencyToNearAssetId(to, tokens);
+
+ if (originToken == null || destinationToken == null) {
+ throw Exception(
+ 'fetchLimits: unsupported currency pair: ${from.title} ${from.tag ?? ''} to ${to.title} ${to.tag ?? ''}',
+ );
+ }
+
+ return ExchangeLimits();
+ }
+
+ @override
+ Future<ProviderRate> fetchRate(RateRequest request) async {
+ final tokens = await _getSupportedTokens();
+ final originToken = currencyToNearAssetId(request.depositCurrency, tokens);
+ final destinationToken = currencyToNearAssetId(request.payoutCurrency, tokens);
+
+ if (originToken == null || destinationToken == null) {
+ throw Exception("fetchRate: Unsupported currency pair");
+ }
+
+ final NearIntentsDepositMode depositMode =
+ _memoRequiredCurrencies.contains(request.depositCurrency) ? .memo : .simple;
+
+ final quoteResp = await getSwapQuote(
+ dry: true,
+ isFixedRateMode: request is FixedRateRequest,
+ originAsset: originToken.assetId,
+ destinationAsset: destinationToken.assetId,
+ amount: switch (request) {
+ FloatingRateRequest(:final depositAmount) => _toChainUnits(depositAmount, originToken),
+ FixedRateRequest(:final payoutAmount) => _toChainUnits(payoutAmount, destinationToken),
+ },
+ depositMode: depositMode,
+ refundTo: getNearDummyAddress(request.depositCurrency),
+ recipient: getNearDummyAddress(request.payoutCurrency),
+ );
+
+ final quote = quoteResp.quote;
+
+ return ProviderRate(
+ provider: description,
+ rate: ExchangeRate.fromAmounts(
+ _fromChainUnits(quote.amountIn, request.depositCurrency, originToken),
+ _fromChainUnits(quote.amountOut, request.payoutCurrency, destinationToken),
+ ),
+ limits: ExchangeLimits(),
+ );
+ }
+
+ @override
+ Future<Trade> createTrade({required TradeRequest request}) async {
+ final tokens = await _getSupportedTokens();
+ final originToken = currencyToNearAssetId(request.depositCurrency, tokens);
+ final destinationToken = currencyToNearAssetId(request.payoutCurrency, tokens);
+
+ if (originToken == null || destinationToken == null) {
+ throw Exception("Unsupported currency pair");
+ }
+
+ final rawAmountStr = request.isFixedRate
+ ? _toChainUnits(request.payoutAmount, destinationToken)
+ : _toChainUnits(request.depositAmount, originToken);
+
+ final NearIntentsDepositMode depositMode =
+ _memoRequiredCurrencies.contains(request.depositCurrency) ? .memo : .simple;
+
+ final quoteResp = await getSwapQuote(
+ dry: false,
+ isFixedRateMode: request.isFixedRate,
+ originAsset: originToken.assetId,
+ destinationAsset: destinationToken.assetId,
+ depositMode: depositMode,
+ amount: rawAmountStr,
+ refundTo: request.refundAddress,
+ recipient: request.payoutAddress,
+ );
+
+ final quote = quoteResp.quote;
+
+ return Trade(
+ id: quote.depositAddress!,
+ // Using deposit address as trade ID
+ provider: description,
+ state: TradeState.created,
+ createdAt: DateTime.now(),
+ fundingAddress: quote.depositAddress!,
+ payoutAddress: request.payoutAddress,
+ refundAddress: request.refundAddress,
+ depositAmount: Money.safeParse(quote.amountInFormatted, request.depositCurrency),
+ payoutAmount: Money.safeParse(quote.amountOutFormatted, request.payoutCurrency),
+ memo: quote.depositMemo,
+ extraId: quote.depositMemo,
+ );
+ }
+
+ @override
+ Future<Trade> updateTrade(Trade trade) async {
+ final data = await _api.send(NearIntentsStatusRequest(depositAddress: trade.id));
+
+ final quoteResponse = data.quoteResponse;
+ final quoteRequest = quoteResponse.quoteRequest;
+ final quote = quoteResponse.quote;
+
+
+
+ return trade.copyWith(
+ fundingAddress: quote.depositAddress,
+ payoutAddress: quoteRequest.recipient,
+ refundAddress: quoteRequest.refundTo,
+ state: data.status.toState,
+ txId: data.swapDetails.originChainTxHashes.firstOrNull?.hash,
+ extraId: quote.depositMemo,
+ isRefund: data.status == .refunded,
+ depositAmount: Money.safeParse(data.swapDetails.amountInFormatted ?? quote.amountInFormatted, trade.depositCurrency),
+ payoutAmount: Money.safeParse(data.swapDetails.amountOutFormatted ?? quote.amountOutFormatted, trade.payoutCurrency),
+ );
+ }
+
+ // Load & cache supported tokens
+ Future<List<NearIntentsToken>> _getSupportedTokens() async {
+ if (_supportedTokensList.isNotEmpty) {
+ return _supportedTokensList;
+ }
+
+ final data = await _api.send(const NearIntentsTokensRequest());
+ _supportedTokensList
+ ..clear()
+ ..addAll(data);
+ return _supportedTokensList;
+ }
+
+ Future<NearIntentsQuoteResponse> getSwapQuote({
+ required bool dry,
+ required bool isFixedRateMode,
+ required String originAsset,
+ required String destinationAsset,
+ required BigInt amount,
+ required String refundTo,
+ required String recipient,
+ required NearIntentsDepositMode depositMode,
+ List<String>? connectedWallets,
+ String? sessionId,
+ String? virtualChainRecipient,
+ String? virtualChainRefundRecipient,
+ String? customRecipientMsg,
+ DateTime? deadline,
+ String? referral,
+ int? quoteWaitingTimeMs,
+ }) {
+ final NearIntentsSwapType swapType = isFixedRateMode ? .exactOutput : .exactInput;
+ final appFees = [
+ if (_appFeesNearIntents case final fee?)
+ NearIntentsAppFee(recipient: _appFeeRecipientNearIntents, fee: fee),
+ ];
+
+ return _api.send(NearIntentsQuoteRequest(
+ dry: dry,
+ swapType: swapType,
+ slippageTolerance: _slippageTolerance,
+ originAsset: originAsset,
+ depositType: .originChain,
+ destinationAsset: destinationAsset,
+ amount: amount,
+ refundTo: refundTo,
+ refundType: .originChain,
+ recipient: recipient,
+ recipientType: .destinationChain,
+ deadline: deadline ?? _buildDeadline(),
+ depositMode: depositMode,
+ connectedWallets: connectedWallets,
+ sessionId: sessionId,
+ virtualChainRecipient: virtualChainRecipient,
+ virtualChainRefundRecipient: virtualChainRefundRecipient,
+ customRecipientMsg: customRecipientMsg,
+ referral: referral,
+ quoteWaitingTimeMs: quoteWaitingTimeMs,
+ appFees: appFees,
+ ));
+ }
+
+ String _normalizeTagToNearBlockchain(String tag) => switch (tag) {
+ "TRX" => "tron",
+ "AVAXC" => "avax",
+ "ROB" => "hood",
+ "ADA" => "cardano",
+ "XLM" => "stellar",
+ _ => tag.toLowerCase(),
+ };
+
+ String _symbolFor(CryptoCurrency currency) =>
+ switch(currency) {
+ CryptoCurrency.usdtArb => "USDT0",
+ _ => currency.title.toUpperCase()
+ };
+
+
+ NearIntentsToken? currencyToNearAssetId(
+ CryptoCurrency currency,
+ List<NearIntentsToken> supported,
+ ) {
+ if (supported.isEmpty) {
+ return null;
+ }
+
+ // TODO(malik): check with original integration author if this fix makes sense
+ final symbol = _symbolFor(currency);
+ final blockchain = _normalizeTagToNearBlockchain(currency.tag ?? currency.title);
+
+ // Use the native Bitcoin asset routed through Omni Bridge.
+ if (currency == CryptoCurrency.btc) {
+ return supported.firstWhereOrNull(
+ (t) => t.assetId == "1cs_v1:btc:native:coin",
+ );
+ }
+
+ // Native asset (no contract)
+ final native = supported.firstWhereOrNull(
+ (t) =>
+ t.symbol.toUpperCase() == symbol &&
+ (t.blockchain.toLowerCase() == blockchain) &&
+ t.contractAddress == null,
+ );
+
+ if (native != null) {
+ return native;
+ }
+
+ final token = supported.firstWhereOrNull(
+ (t) => t.symbol.toUpperCase() == symbol && t.blockchain.toLowerCase() == blockchain,
+ );
+
+ return token;
+ }
+
+ DateTime _buildDeadline() => DateTime.now().toUtc().add(const Duration(hours: 2));
+
+ static BigInt _toChainUnits(Money amount, NearIntentsToken token) {
+ final shift = token.decimals - amount.decimals;
+ return shift >= 0
+ ? amount.amount * BigInt.from(10).pow(shift)
+ : amount.amount ~/ BigInt.from(10).pow(-shift);
+ }
+
+ static Money _fromChainUnits(BigInt amount, CryptoCurrency currency, NearIntentsToken token) =>
+ Money(amount, currency, token.decimals).copyWith(currency: currency);
+}
### lib/exchange/provider/sideshift_exchange_provider.dart
@@ -1,480 +0,0 @@
-import 'dart:convert';
-
-import 'package:cake_wallet/.secrets.g.dart' as secrets;
-import "package:cake_wallet/exchange/exchange_exceptions.dart";
-import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/limits.dart';
-import 'package:cake_wallet/exchange/trade.dart';
-import 'package:cake_wallet/exchange/trade_not_created_exception.dart';
-import 'package:cake_wallet/exchange/trade_not_found_exception.dart';
-import 'package:cake_wallet/exchange/trade_request.dart';
-import 'package:cake_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:cake_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 ExchangeProviderResponseCodeException('$error', response.statusCode);
- }
-
- 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 ExchangeProviderResponseCodeException('$error', response.statusCode);
- }
-
- if (response.statusCode != 200) {
- throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', 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 ExchangeProviderResponseCodeException('SideShift Internal Server Error: $error', response.statusCode);
- }
-
- 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 ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', 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,
- if (request.toAddressExtraId.isNotEmpty) 'settleMemo': request.toAddressExtraId,
- '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,
- toAddressExtraId: request.toAddressExtraId,
- );
- }
-
- @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 ExchangeProviderResponseCodeException(error, response.statusCode);
- }
-
- if (response.statusCode != 200) {
- throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', 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';
- case "ROB":
- return "robinhood";
- 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,
- };
- }
-}
### lib/exchange/provider/simpleswap_exchange_provider.dart
@@ -1,367 +0,0 @@
-import 'dart:convert';
-
-import 'package:cake_wallet/.secrets.g.dart' as secrets;
-import "package:cake_wallet/exchange/exchange_exceptions.dart";
-import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/limits.dart';
-import 'package:cake_wallet/exchange/trade.dart';
-import 'package:cake_wallet/exchange/trade_not_created_exception.dart';
-import 'package:cake_wallet/exchange/trade_not_found_exception.dart';
-import 'package:cake_wallet/exchange/trade_request.dart';
-import 'package:cake_wallet/exchange/trade_state.dart';
-import 'package:cake_wallet/utils/device_info.dart';
-import 'package:cw_core/utils/proxy_wrapper.dart';
-import 'package:cw_core/crypto_currency.dart';
-import 'package:cake_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 ExchangeProviderResponseCodeException('$error', response.statusCode);
- }
-
- if (response.statusCode != 200) {
- throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', 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),
- if (request.toAddressExtraId.isNotEmpty) "extra_id_to": request.toAddressExtraId,
- };
- 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,
- toAddressExtraId: request.toAddressExtraId,
- );
- }
-
- @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 ExchangeProviderResponseCodeException(error, response.statusCode);
- }
-
- if (response.statusCode != 200) {
- throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', 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;
-}
### lib/exchange/provider/stealth_ex_exchange_provider.dart
@@ -1,451 +0,0 @@
-import 'dart:convert';
-import 'dart:developer';
-
-import 'package:cake_wallet/.secrets.g.dart' as secrets;
-import "package:cake_wallet/exchange/exchange_exceptions.dart";
-import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/limits.dart';
-import 'package:cake_wallet/exchange/trade.dart';
-import 'package:cake_wallet/exchange/trade_not_created_exception.dart';
-import 'package:cake_wallet/exchange/trade_request.dart';
-import 'package:cake_wallet/exchange/trade_state.dart';
-import 'package:cw_core/utils/proxy_wrapper.dart';
-import 'package:cw_core/crypto_currency.dart';
-import 'package:cake_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 => false;
-
- @override
- bool get isEnabled => true;
-
- @override
- bool get supportsFixedRate => true;
-
- @override
- ExchangeProviderDescription get description => ExchangeProviderDescription.stealthEx;
-
- @override
- Future<bool> checkIsAvailable() async => false;
-
- @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 ExchangeProviderResponseCodeException('StealthEx fetch limits failed: ${response.body}', response.statusCode);
- }
- 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 ExchangeProviderResponseException('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),
- if (request.toAddressExtraId.isNotEmpty) 'extra_id': request.toAddressExtraId,
- '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 ExchangeProviderResponseCodeException('StealthEx create trade failed: ${response.body}', response.statusCode);
- }
- 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,
- toAddressExtraId: request.toAddressExtraId,
- );
- } 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 ExchangeProviderResponseCodeException('StealthEx fetch trade failed: ${response.body}', response.statusCode);
- }
- 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;
-}
### lib/exchange/provider/stealthex/stealthex_api_schema.dart
@@ -0,0 +1,330 @@
+// spec reference: https://api.stealthex.io/docs/openapi.json
+
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/exchange/utils/json_converters.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:json_annotation/json_annotation.dart";
+
+part "stealthex_api_schema.g.dart";
+
+enum StealthExEstimation {
+ @JsonValue("direct")
+ direct,
+ @JsonValue("reversed")
+ reversed,
+ unknown,
+}
+
+enum StealthExRateType {
+ @JsonValue("floating")
+ floating,
+ @JsonValue("fixed")
+ fixed,
+ unknown,
+}
+
+enum StealthExErrorKind {
+ @JsonValue("NoPair")
+ noPair,
+ @JsonValue("NotFound")
+ notFound,
+ @JsonValue("NotAllowed")
+ notAllowed,
+ @JsonValue("NoExchangeRoute")
+ noExchangeRoute,
+ @JsonValue("RouteIsDisabled")
+ routeIsDisabled,
+ @JsonValue("MarketUnavailable")
+ marketUnavailable,
+ @JsonValue("InvalidAmount")
+ invalidAmount,
+ @JsonValue("InvalidData")
+ invalidData,
+ @JsonValue("RateId")
+ rateId,
+ @JsonValue("ExtraId")
+ extraId,
+ @JsonValue("NoUserApiKey")
+ noUserApiKey,
+ @JsonValue("RoutesMismatch")
+ routesMismatch,
+ unknown,
+}
+
+@JsonSerializable(createToJson: false)
+class StealthExError {
+ const StealthExError({required this.kind, required this.details});
+
+ factory StealthExError.fromJson(Map<String, dynamic> json) => _$StealthExErrorFromJson(json);
+
+ @JsonKey(name: "kind", unknownEnumValue: StealthExErrorKind.unknown)
+ final StealthExErrorKind kind;
+ @JsonKey(name: "details")
+ final String details;
+}
+
+@JsonSerializable(createToJson: false)
+class StealthExErrorResponse {
+ const StealthExErrorResponse({required this.err});
+
+ factory StealthExErrorResponse.fromJson(Map<String, dynamic> json) =>
+ _$StealthExErrorResponseFromJson(json);
+
+ @JsonKey(name: "err")
+ final StealthExError err;
+}
+
+
+class StealthExCurrencyConverter implements JsonConverter<CryptoCurrency, Map<String, String>> {
+ const StealthExCurrencyConverter();
+
+ @override
+ Map<String, String> toJson(CryptoCurrency currency) => {
+ "symbol": _symbolFor(currency),
+ "network": _networkFor(currency),
+ };
+
+ @override
+ CryptoCurrency fromJson(Map<String, String> json) {
+ final network = json["network"];
+ final currency = CryptoCurrency.safeParseCurrencyFromString(
+ json["symbol"],
+ tag: network == "mainnet" ? null : network,
+ );
+ if (currency == null) {
+ throw ArgumentError("unknown StealthEx currency: $json");
+ }
+ return currency;
+ }
+
+ String _symbolFor(CryptoCurrency currency) =>
+ currency == CryptoCurrency.usdcEPoly ? "usdce" : currency.title.toLowerCase();
+
+ String _networkFor(CryptoCurrency currency) => switch (currency) {
+ _ when currency == CryptoCurrency.arb || currency.tag == "ARB" => "arbitrum",
+ _ when currency.tag == null => "mainnet",
+ _ when currency == CryptoCurrency.maticpoly => "mainnet",
+ _ when currency.tag == "POLY" => "matic",
+ _ => currency.tag!.toLowerCase(),
+ };
+}
+
+@JsonSerializable(explicitToJson: true)
+@StealthExCurrencyConverter()
+class StealthExRoute {
+ const StealthExRoute({required this.from, required this.to});
+
+ factory StealthExRoute.fromJson(Map<String, dynamic> json) => _$StealthExRouteFromJson(json);
+
+ @JsonKey(name: "from")
+ final CryptoCurrency from;
+ @JsonKey(name: "to")
+ final CryptoCurrency to;
+
+ Map<String, dynamic> toJson() => _$StealthExRouteToJson(this);
+}
+
+
+@JsonSerializable(explicitToJson: true)
+class StealthExRangeRequest {
+ const StealthExRangeRequest({
+ required this.route,
+ required this.estimation,
+ required this.rate,
+ this.additionalFeePercent,
+ });
+
+ @JsonKey(name: "route")
+ final StealthExRoute route;
+ @JsonKey(name: "estimation")
+ final StealthExEstimation estimation;
+ @JsonKey(name: "rate")
+ final StealthExRateType rate;
+
+ @JsonKey(name: "additional_fee_percent", includeIfNull: false)
+ final double? additionalFeePercent;
+
+ Map<String, dynamic> toJson() => _$StealthExRangeRequestToJson(this);
+}
+
+@JsonSerializable(createToJson: false)
+class StealthExRange {
+ const StealthExRange({required this.minAmount, this.maxAmount});
+
+ factory StealthExRange.fromJson(Map<String, dynamic> json) => _$StealthExRangeFromJson(json);
+
+ @JsonKey(name: "min_amount")
+ final double minAmount;
+
+ // null means there is no upper limit
+ @JsonKey(name: "max_amount")
+ final double? maxAmount;
+}
+
+
+@JsonSerializable(explicitToJson: true)
+class StealthExEstimateRequest {
+ const StealthExEstimateRequest({
+ required this.route,
+ required this.amount,
+ required this.estimation,
+ required this.rate,
+ this.additionalFeePercent,
+ });
+
+ @JsonKey(name: "route")
+ final StealthExRoute route;
+ @JsonKey(name: "amount")
+ final double amount;
+ @JsonKey(name: "estimation")
+ final StealthExEstimation estimation;
+ @JsonKey(name: "rate")
+ final StealthExRateType rate;
+ @JsonKey(name: "additional_fee_percent", includeIfNull: false)
+ final double? additionalFeePercent;
+
+ Map<String, dynamic> toJson() => _$StealthExEstimateRequestToJson(this);
+}
+
+@JsonSerializable(createToJson: false)
+class StealthExEstimateRate {
+ const StealthExEstimateRate({required this.id, required this.validUntil});
+
+ factory StealthExEstimateRate.fromJson(Map<String, dynamic> json) =>
+ _$StealthExEstimateRateFromJson(json);
+
+ @JsonKey(name: "id")
+ final String id;
+
+ @JsonKey(name: "valid_until")
+ final DateTime validUntil;
+}
+
+@JsonSerializable(createToJson: false)
+class StealthExEstimate {
+ const StealthExEstimate({required this.estimatedAmount, this.rate});
+
+ factory StealthExEstimate.fromJson(Map<String, dynamic> json) =>
+ _$StealthExEstimateFromJson(json);
+
+ @JsonKey(name: "estimated_amount")
+ final double estimatedAmount;
+
+ @JsonKey(name: "rate")
+ final StealthExEstimateRate? rate;
+}
+
+
+@JsonSerializable(explicitToJson: true)
+class StealthExCreateExchangeRequest {
+ const StealthExCreateExchangeRequest({
+ required this.route,
+ required this.amount,
+ required this.estimation,
+ required this.rate,
+ required this.address,
+ this.rateId,
+ this.extraId,
+ this.refundAddress,
+ this.refundExtraId,
+ this.additionalFeePercent,
+ });
+
+ @JsonKey(name: "route")
+ final StealthExRoute route;
+ @JsonKey(name: "amount")
+ final double amount;
+ @JsonKey(name: "estimation")
+ final StealthExEstimation estimation;
+ @JsonKey(name: "rate")
+ final StealthExRateType rate;
+ @JsonKey(name: "address")
+ final String address;
+ @JsonKey(name: "rate_id", includeIfNull: false)
+ final String? rateId;
+ @JsonKey(name: "extra_id", includeIfNull: false)
+ final String? extraId;
+ @JsonKey(name: "refund_address", includeIfNull: false)
+ final String? refundAddress;
+ @JsonKey(name: "refund_extra_id", includeIfNull: false)
+ final String? refundExtraId;
+ @JsonKey(name: "additional_fee_percent", includeIfNull: false)
+ final double? additionalFeePercent;
+
+ Map<String, dynamic> toJson() => _$StealthExCreateExchangeRequestToJson(this);
+}
+
+@JsonSerializable(createToJson: false)
+class StealthExExchangeSide {
+ const StealthExExchangeSide({
+ required this.symbol,
+ required this.network,
+ required this.amount,
+ required this.expectedAmount,
+ required this.address,
+ this.extraId,
+ this.txHash,
+ this.addressExplorerUrl,
+ this.txExplorerUrl,
+ });
+
+ factory StealthExExchangeSide.fromJson(Map<String, dynamic> json) =>
+ _$StealthExExchangeSideFromJson(json);
+
+ @JsonKey(name: "symbol")
+ final String symbol;
+ @JsonKey(name: "network")
+ final String network;
+ @JsonKey(name: "amount")
+ final double amount;
+ @JsonKey(name: "expected_amount")
+ final double expectedAmount;
+ @JsonKey(name: "address")
+ final String address;
+ @JsonKey(name: "extra_id")
+ final String? extraId;
+ @JsonKey(name: "tx_hash")
+ final String? txHash;
+ @JsonKey(name: "address_explorer_url")
+ final String? addressExplorerUrl;
+ @JsonKey(name: "tx_explorer_url")
+ final String? txExplorerUrl;
+}
+
+@JsonSerializable(createToJson: false)
+@TradeStateConverter()
+class StealthExExchange {
+ const StealthExExchange({
+ required this.id,
+ required this.status,
+ required this.rate,
+ required this.deposit,
+ required this.withdrawal,
+ required this.createdAt,
+ this.refundAddress,
+ this.refundExtraId,
+ this.expiresAt,
+ });
+
+ factory StealthExExchange.fromJson(Map<String, dynamic> json) =>
+ _$StealthExExchangeFromJson(json);
+
+ @JsonKey(name: "id")
+ final String id;
+ @JsonKey(name: "status")
+ final TradeState status;
+ @JsonKey(name: "rate", unknownEnumValue: StealthExRateType.unknown)
+ final StealthExRateType rate;
+ @JsonKey(name: "deposit")
+ final StealthExExchangeSide deposit;
+ @JsonKey(name: "withdrawal")
+ final StealthExExchangeSide withdrawal;
+ @JsonKey(name: "refund_address")
+ final String? refundAddress;
+ @JsonKey(name: "refund_extra_id")
+ final String? refundExtraId;
+ @JsonKey(name: "created_at")
+ final DateTime createdAt;
+ @JsonKey(name: "expires_at")
+ final DateTime? expiresAt;
+}
### lib/exchange/provider/stealthex/stealthex_exchange_provider.dart
@@ -0,0 +1,243 @@
+import "dart:convert";
+
+import "package:cake_wallet/.secrets.g.dart" as secrets;
+import "package:cake_wallet/exchange/exchange_provider_description.dart";
+import "package:cake_wallet/exchange/provider/exchange_provider.dart";
+import "package:cake_wallet/exchange/provider/stealthex/stealthex_api_schema.dart";
+import "package:cake_wallet/exchange/rate_request.dart";
+import "package:cake_wallet/exchange/trade.dart";
+import "package:cake_wallet/exchange/trade_not_created_exception.dart";
+import "package:cake_wallet/exchange/trade_request.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/exchange_limits.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/provider_rate.dart";
+import "package:cw_core/amount/exchange_rate.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/crypto_currency.dart";
+
+class StealthExExchangeProvider extends LimitsCacheExchangeProvider {
+ StealthExExchangeProvider({super.proxyWrapper});
+
+ static const 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
+ bool get supportsFixedRate => true;
+
+ @override
+ ExchangeProviderDescription get description => ExchangeProviderDescription.stealthEx;
+
+ @override
+ Future<ExchangeLimits> 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 = StealthExRangeRequest(route: StealthExRoute(from: curFrom, to: curTo),
+ estimation: isFixedRateMode ? StealthExEstimation.reversed : StealthExEstimation.direct,
+ rate: isFixedRateMode ? .fixed : .floating,
+ additionalFeePercent: _additionalFeePercent);
+
+ 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 responseData = StealthExRange.fromJson(
+ json.decode(response.body) as Map<String, dynamic>);
+ return ExchangeLimits(
+ min: Money.trySafeParse(responseData.minAmount, from),
+ max: Money.trySafeParse(responseData.maxAmount, from),
+ );
+ }
+
+ @override
+ Future<ProviderRate> fetchRate(RateRequest request) async {
+ if (request is! FloatingRateRequest) {
+ throw Exception("fixed rate unsupported");
+ }
+
+ final response = await getEstimatedExchangeAmount(
+ from: request.depositCurrency,
+ to: request.payoutCurrency,
+ amount: double.parse(request.depositAmount.toString()),
+ isFixedRateMode: false,
+ );
+
+ if (response.estimatedAmount <= 0.0) {
+ throw Exception("negative amount");
+ }
+
+ return ProviderRate(provider: description,
+ rate: ExchangeRate.fromAmounts(
+ request.depositAmount, Money.safeParse(response.estimatedAmount, request.payoutCurrency)),
+ limits: await getLimits(
+ from: request.depositCurrency, to: request.payoutCurrency, isFixedRateMode: false));
+ }
+
+ @override
+ Future<Trade> createTrade({required TradeRequest request}) async {
+ String? rateId;
+ DateTime? validUntil;
+
+ if (request.isFixedRate) {
+ final response = await getEstimatedExchangeAmount(
+ from: request.depositCurrency,
+ to: request.payoutCurrency,
+ amount: double.parse(request.depositAmount.toString()),
+ isFixedRateMode: request.isFixedRate);
+ rateId = response.rate?.id;
+ validUntil = response.rate?.validUntil;
+ 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),
+ // if (request.toAddressExtraId.isNotEmpty) 'extra_id': request.toAddressExtraId,
+ // 'refund_address': _normalizeAddress(request.refundAddress),
+ // 'additional_fee_percent': _additionalFeePercent,
+ // };
+ final body = StealthExCreateExchangeRequest(
+ route: StealthExRoute(from: request.depositCurrency, to: request.payoutCurrency),
+ amount: request.isFixedRate
+ ? double.parse(request.payoutAmount.toString())
+ : double.parse(request.depositAmount.toString()),
+ estimation: request.isFixedRate ? .reversed : .direct,
+ rate: request.isFixedRate ? .fixed : .floating,
+ address: _normalizeAddress(request.payoutAddress),
+ refundAddress: _normalizeAddress(request.refundAddress),
+ extraId: request.toAddressExtraId,
+ additionalFeePercent: _additionalFeePercent
+ );
+
+ final response = await proxyWrapper.post(
+ clearnetUri: Uri.parse(_baseUrl + _exchangesPath),
+ headers: headers,
+ body: json.encode(body),
+ );
+
+ if (response.statusCode != 201) {
+ throw Exception("StealthEx create trade failed: ${response.body}");
+ }
+ final responseData = StealthExExchange.fromJson(
+ json.decode(response.body) as Map<String, dynamic>);
+
+ final createdAt = responseData.createdAt.toLocal();
+ final expiredAt = validUntil != null
+ ? validUntil.toLocal()
+ : DateTime.now().add(const Duration(minutes: 5));
+
+ CryptoCurrency fromCurrency;
+ if (request.depositCurrency.tag != null &&
+ request.depositCurrency.title.toLowerCase() == responseData.deposit.symbol) {
+ fromCurrency = request.depositCurrency;
+ } else {
+ fromCurrency = CryptoCurrency.fromString(responseData.deposit.symbol);
+ }
+
+ CryptoCurrency toCurrency;
+ if (request.payoutCurrency.tag != null &&
+ request.payoutCurrency.title.toLowerCase() == responseData.withdrawal.symbol) {
+ toCurrency = request.payoutCurrency;
+ } else {
+ toCurrency = CryptoCurrency.fromString(responseData.withdrawal.symbol);
+ }
+
+
+ return Trade(
+ id: responseData.id,
+ provider: description,
+ fundingAddress: responseData.deposit.address,
+ payoutAddress: responseData.withdrawal.address,
+ refundAddress: responseData.refundAddress ?? "",
+ state: responseData.status,
+ createdAt: createdAt,
+ expiredAt: expiredAt,
+ extraId: responseData.deposit.extraId,
+ toAddressExtraId: request.toAddressExtraId,
+ depositAmount: Money.safeParse(responseData.deposit.amount, fromCurrency),
+ payoutAmount: Money.safeParse(responseData.withdrawal.amount, toCurrency),
+ );
+ }
+
+ @override
+ Future<Trade> updateTrade(Trade trade) async {
+ final headers = {"Authorization": apiKey, "Content-Type": "application/json"};
+
+ final uri = Uri.parse("$_baseUrl$_exchangesPath/${trade.id}");
+ final response = await proxyWrapper.get(clearnetUri: uri, headers: headers);
+
+ if (response.statusCode != 200) {
+ throw Exception("StealthEx fetch trade failed: ${response.body}");
+ }
+ final responseData = StealthExExchange.fromJson(
+ json.decode(response.body) as Map<String, dynamic>);
+
+
+ return trade.copyWith(
+ fundingAddress: responseData.deposit.address,
+ payoutAddress: responseData.withdrawal.address,
+ refundAddress: responseData.refundAddress ?? "",
+ state: responseData.status,
+ createdAt: responseData.createdAt,
+ isRefund: responseData.status == .refunded,
+ extraId: responseData.deposit.extraId,
+ depositAmount: Money.safeParse(responseData.deposit.amount, trade.depositCurrency),
+ payoutAmount: Money.safeParse(responseData.withdrawal.amount, trade.payoutCurrency),
+ );
+ }
+
+ Future<StealthExEstimate> getEstimatedExchangeAmount({required CryptoCurrency from,
+ required CryptoCurrency to,
+ required double amount,
+ required bool isFixedRateMode}) async {
+ final headers = {"Authorization": apiKey, "Content-Type": "application/json"};
+
+ final body = StealthExEstimateRequest(route: StealthExRoute(from: from, to: to),
+ amount: amount,
+ estimation: isFixedRateMode ? .reversed : .direct,
+ rate: isFixedRateMode ? .fixed : .floating,
+ additionalFeePercent: _additionalFeePercent);
+
+ final response = await proxyWrapper.post(
+ clearnetUri: Uri.parse(_baseUrl + _amountPath),
+ headers: headers,
+ body: json.encode(body),
+ );
+
+ if (response.statusCode != 200) {
+ throw Exception(
+ "stealthex estimated rate response: ${response.statusCode} ${response.body}",
+ );
+ }
+ return StealthExEstimate.fromJson(json.decode(response.body) as Map<String, dynamic>);
+ }
+
+
+ String _normalizeAddress(String address) =>
+ address.startsWith("bitcoincash:") ? address.replaceFirst("bitcoincash:", "") : address;
+}
### lib/exchange/provider/swapsxyz/swapsxyz_api_schema.dart
@@ -0,0 +1,990 @@
+// spec reference: https://docs.swaps.xyz/swap-api-reference/openapi.json
+
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/exchange/utils/json_converters.dart";
+import "package:cake_wallet/exchange/utils/provider_api.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:json_annotation/json_annotation.dart";
+
+part "swapsxyz_api_schema.g.dart";
+
+
+
+class SwapsXyzBigIntAmountConverter implements JsonConverter<BigInt, String> {
+ const SwapsXyzBigIntAmountConverter();
+
+ @override
+ BigInt fromJson(String json) => BigInt.parse(json.replaceAll("n", ""));
+
+ @override
+ String toJson(BigInt value) => value.toString();
+}
+
+
+// docs literally say "integer or string"
+class SwapsXyzTimestampConverter implements JsonConverter<DateTime, Object> {
+ const SwapsXyzTimestampConverter();
+
+ @override
+ DateTime fromJson(Object json) {
+ if (json is num) {
+ return DateTime.fromMillisecondsSinceEpoch(json.toInt() * 1000, isUtc: true);
+ }
+ final seconds = int.tryParse(json.toString());
+ if (seconds != null) {
+ return DateTime.fromMillisecondsSinceEpoch(seconds * 1000, isUtc: true);
+ }
+ return DateTime.parse(json.toString());
+ }
+
+ @override
+ Object toJson(DateTime value) => value.millisecondsSinceEpoch ~/ 1000;
+}
+
+
+
+enum SwapsXyzVmId {
+ @JsonValue("evm")
+ evm,
+ @JsonValue("solana")
+ solana,
+ @JsonValue("alt-vm")
+ altVm,
+ @JsonValue("hypercore")
+ hypercore,
+ @JsonValue("tron")
+ tron,
+ unknown;
+
+ String toJson() => _$SwapsXyzVmIdEnumMap[this]!;
+}
+
+enum SwapsXyzActionType {
+ @JsonValue("swap-action")
+ swapAction,
+ @JsonValue("evm-calldata-tx")
+ evmCalldataTx,
+ @JsonValue("polymarket")
+ polymarket,
+ unknown,
+}
+
+enum SwapsXyzExecutionsType {
+ @JsonValue("DEFAULT")
+ standard,
+ @JsonValue("GASLESS")
+ gasless,
+ unknown,
+}
+
+enum SwapsXyzSwapDirection {
+ @JsonValue("exact-amount-in")
+ exactAmountIn,
+ @JsonValue("exact-amount-out")
+ exactAmountOut,
+ unknown,
+}
+
+enum SwapsXyzTxStatusValue {
+ @JsonValue("not yet created")
+ notYetCreated,
+ @JsonValue("submitted")
+ submitted,
+ @JsonValue("pending")
+ pending,
+ @JsonValue("success")
+ success,
+ @JsonValue("completed")
+ completed,
+ @JsonValue("requires refund")
+ requiresRefund,
+ @JsonValue("refunded")
+ refunded,
+ @JsonValue("expired")
+ expired,
+ @JsonValue("failed")
+ failed,
+ @JsonValue("processing")
+ procesing,
+ @JsonValue("cancelled")
+ cancelled,
+ @JsonValue("error")
+ error,
+ unknown,
+}
+
+extension StatusToState on SwapsXyzTxStatusValue {
+ TradeState get toState => switch (this) {
+ .notYetCreated => .toBeCreated,
+ .submitted => .pending,
+ .pending => .pending,
+ .success => .success,
+ .completed => .success,
+ .requiresRefund => .refund,
+ .refunded => .refunded,
+ .expired => .expired,
+ .failed => .failed,
+ .procesing => .pending,
+ .cancelled => .failed,
+ .error => .failed,
+ _ => .pending,
+ };
+}
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzError {
+ const SwapsXyzError({
+ this.code,
+ this.name,
+ this.message,
+ this.title,
+ this.statusCode,
+ this.timestamp,
+ this.details,
+ });
+
+ factory SwapsXyzError.fromJson(Map<String, dynamic> json) => _$SwapsXyzErrorFromJson(json);
+
+ @JsonKey(name: "code")
+ final String? code;
+ @JsonKey(name: "name")
+ final String? name;
+ @JsonKey(name: "message")
+ final String? message;
+ @JsonKey(name: "title")
+ final String? title;
+ @JsonKey(name: "statusCode")
+ final int? statusCode;
+ @JsonKey(name: "timestamp")
+ final DateTime? timestamp;
+
+ @JsonKey(name: "details")
+ final Map<String, dynamic>? details;
+}
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzErrorResponse {
+ const SwapsXyzErrorResponse({required this.success, this.error});
+
+ factory SwapsXyzErrorResponse.fromJson(Map<String, dynamic> json) =>
+ _$SwapsXyzErrorResponseFromJson(json);
+
+ static String? messageOf(Map<String, dynamic> json) => switch (json["error"]) {
+ {"message": final Object message} => message.toString(),
+ _ => null,
+ };
+
+ @JsonKey(name: "success")
+ final bool success;
+ @JsonKey(name: "error")
+ final SwapsXyzError? error;
+}
+
+
+class SwapsXyzChainListRequest extends ApiRequest<List<SwapsXyzChain>> {
+ const SwapsXyzChainListRequest();
+
+ @override
+ String path() => "/api/getChainList";
+
+ @override
+ Map<String, dynamic> toJson() => const {};
+
+ @override
+ List<SwapsXyzChain> decode(Object json) => (json as List<dynamic>)
+ .map((item) => SwapsXyzChain.fromJson(item as Map<String, dynamic>))
+ .toList();
+}
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzChain {
+ const SwapsXyzChain({required this.chainId, required this.name, required this.vmId});
+
+ factory SwapsXyzChain.fromJson(Map<String, dynamic> json) => _$SwapsXyzChainFromJson(json);
+
+ @JsonKey(name: "chainId")
+ final int chainId;
+ @JsonKey(name: "name")
+ final String name;
+ @JsonKey(name: "vmId", unknownEnumValue: SwapsXyzVmId.unknown)
+ final SwapsXyzVmId vmId;
+}
+
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzTokenInfo {
+ const SwapsXyzTokenInfo({
+ required this.chainId,
+ required this.address,
+ required this.name,
+ required this.symbol,
+ required this.decimals,
+ required this.isNative,
+ this.logo,
+ this.swapsXyzCode,
+ });
+
+ factory SwapsXyzTokenInfo.fromJson(Map<String, dynamic> json) =>
+ _$SwapsXyzTokenInfoFromJson(json);
+
+ @JsonKey(name: "chainId")
+ final int chainId;
+ @JsonKey(name: "address")
+ final String address;
+ @JsonKey(name: "name")
+ final String name;
+ @JsonKey(name: "symbol")
+ final String symbol;
+ @JsonKey(name: "decimals")
+ final int decimals;
+ @JsonKey(name: "isNative")
+ final bool isNative;
+ @JsonKey(name: "logo")
+ final String? logo;
+ @JsonKey(name: "swapsXyzCode")
+ final String? swapsXyzCode;
+}
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzTokenInfoWithAmounts {
+ const SwapsXyzTokenInfoWithAmounts({
+ required this.chainId,
+ required this.address,
+ required this.name,
+ required this.symbol,
+ required this.decimals,
+ required this.isNative,
+ this.logo,
+ this.swapsXyzCode,
+ this.minAmount,
+ this.maxAmount,
+ });
+
+ factory SwapsXyzTokenInfoWithAmounts.fromJson(Map<String, dynamic> json) =>
+ _$SwapsXyzTokenInfoWithAmountsFromJson(json);
+
+ @JsonKey(name: "chainId")
+ final int chainId;
+ @JsonKey(name: "address")
+ final String address;
+ @JsonKey(name: "name")
+ final String name;
+ @JsonKey(name: "symbol")
+ final String symbol;
+ @JsonKey(name: "decimals")
+ final int decimals;
+ @JsonKey(name: "isNative")
+ final bool isNative;
+ @JsonKey(name: "logo")
+ final String? logo;
+ @JsonKey(name: "swapsXyzCode")
+ final String? swapsXyzCode;
+
+ @JsonKey(name: "minAmount")
+ final String? minAmount;
+ @JsonKey(name: "maxAmount")
+ final String? maxAmount;
+}
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzAmountLimits {
+ const SwapsXyzAmountLimits({this.minAmount, this.maxAmount});
+
+ factory SwapsXyzAmountLimits.fromJson(Map<String, dynamic> json) =>
+ _$SwapsXyzAmountLimitsFromJson(json);
+
+ @JsonKey(name: "minAmount")
+ final String? minAmount;
+ @JsonKey(name: "maxAmount")
+ final String? maxAmount;
+}
+
+class SwapsXyzPathTokens {
+ const SwapsXyzPathTokens.all() : tokens = null;
+
+ const SwapsXyzPathTokens.list(this.tokens);
+
+ final List<SwapsXyzTokenInfoWithAmounts>? tokens;
+
+ bool get isEmpty => tokens?.isEmpty ?? true;
+
+ bool get isNotEmpty => !isEmpty;
+
+ bool get isAll => tokens == null;
+}
+
+class SwapsXyzPathTokensConverter implements JsonConverter<SwapsXyzPathTokens, Object> {
+ const SwapsXyzPathTokensConverter();
+
+ @override
+ SwapsXyzPathTokens fromJson(Object json) {
+ if (json is List) {
+ return SwapsXyzPathTokens.list(
+ json
+ .map((e) => SwapsXyzTokenInfoWithAmounts.fromJson(e as Map<String, dynamic>))
+ .toList(),
+ );
+ }
+ return const SwapsXyzPathTokens.all();
+ }
+
+ @override
+ Object toJson(SwapsXyzPathTokens value) => value.tokens ?? "all";
+}
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzChainPath {
+ const SwapsXyzChainPath({
+ required this.chainId,
+ required this.tokens,
+ required this.supportsExactAmountIn,
+ required this.supportsExactAmountOut,
+ this.amountLimits,
+ });
+
+ factory SwapsXyzChainPath.fromJson(Map<String, dynamic> json) =>
+ _$SwapsXyzChainPathFromJson(json);
+
+ @JsonKey(name: "chainId")
+ final int chainId;
+ @JsonKey(name: "tokens")
+ @SwapsXyzPathTokensConverter()
+ final SwapsXyzPathTokens tokens;
+ @JsonKey(name: "supportsExactAmountIn")
+ final bool supportsExactAmountIn;
+ @JsonKey(name: "supportsExactAmountOut")
+ final bool supportsExactAmountOut;
+
+ @JsonKey(name: "amountLimits")
+ final SwapsXyzAmountLimits? amountLimits;
+}
+
+/// query for GET /api/getPaths. leave dstChainId and dstToken off to get every path out of the
+/// source token
+@JsonSerializable()
+class SwapsXyzPathsRequest extends ApiRequest<SwapsXyzPathsResponse> {
+ const SwapsXyzPathsRequest({
+ required this.srcChainId,
+ required this.srcToken,
+ this.dstChainId,
+ this.dstToken,
+ this.excludeBridgeIds,
+ this.excludeDexIds,
+ });
+
+ @JsonKey(name: "srcChainId")
+ final String srcChainId;
+ @JsonKey(name: "srcToken")
+ final String srcToken;
+ @JsonKey(name: "dstChainId", includeIfNull: false)
+ final String? dstChainId;
+ @JsonKey(name: "dstToken", includeIfNull: false)
+ final String? dstToken;
+
+ @JsonKey(name: "excludeBridgeIds", includeIfNull: false)
+ final List<String>? excludeBridgeIds;
+ @JsonKey(name: "excludeDexIds", includeIfNull: false)
+ final List<String>? excludeDexIds;
+
+ @override
+ String path() => "/api/getPaths";
+
+ @override
+ Map<String, dynamic> toJson() => _$SwapsXyzPathsRequestToJson(this);
+
+ @override
+ SwapsXyzPathsResponse decode(Object json) =>
+ SwapsXyzPathsResponse.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzPathsResponse {
+ const SwapsXyzPathsResponse({
+ required this.srcChainId,
+ required this.srcToken,
+ required this.paths,
+ this.timestamp,
+ });
+
+ factory SwapsXyzPathsResponse.fromJson(Map<String, dynamic> json) =>
+ _$SwapsXyzPathsResponseFromJson(json);
+
+ @JsonKey(name: "srcChainId")
+ final int srcChainId;
+
+ @JsonKey(name: "srcToken")
+ final SwapsXyzTokenInfoWithAmounts srcToken;
+ @JsonKey(name: "paths")
+ final List<SwapsXyzChainPath> paths;
+ @JsonKey(name: "timestamp")
+ final String? timestamp;
+}
+
+
+/// query for GET /api/getQuote. undocumented like the response, so there may be more params it
+/// accepts - these are the ones we send
+@JsonSerializable()
+class SwapsXyzQuoteRequest extends ApiRequest<SwapsXyzQuote> {
+ const SwapsXyzQuoteRequest({
+ required this.srcChainId,
+ required this.srcToken,
+ required this.dstChainId,
+ required this.dstToken,
+ required this.amount,
+ this.swapDirection,
+ });
+
+ @JsonKey(name: "srcChainId")
+ final String srcChainId;
+ @JsonKey(name: "srcToken")
+ final String srcToken;
+ @JsonKey(name: "dstChainId")
+ final String dstChainId;
+ @JsonKey(name: "dstToken")
+ final String dstToken;
+
+ // base units of the source token for exact-amount-in, of the destination for exact-amount-out
+ @JsonKey(name: "amount")
+ final String amount;
+ @JsonKey(name: "swapDirection", includeIfNull: false)
+ final SwapsXyzSwapDirection? swapDirection;
+
+ @override
+ String path() => "/api/getQuote";
+
+ @override
+ Map<String, dynamic> toJson() => _$SwapsXyzQuoteRequestToJson(this);
+
+ @override
+ SwapsXyzQuote decode(Object json) => SwapsXyzQuote.fromJson(json as Map<String, dynamic>);
+}
+
+// getQuote is undocumented, this is based on curled response
+@JsonSerializable(createToJson: false)
+class SwapsXyzQuote {
+ const SwapsXyzQuote({
+ required this.amountIn,
+ required this.amountInMax,
+ required this.amountOut,
+ required this.amountOutMin,
+ required this.exchangeRate,
+ required this.vmId,
+ this.protocolFee,
+ this.applicationFee,
+ this.bridgeFee,
+ this.estimatedTxTime,
+ this.estimatedPriceImpact,
+ this.requiresTokenApproval,
+ this.requiresRegisterTransaction,
+ this.executionsType,
+ });
+
+ factory SwapsXyzQuote.fromJson(Map<String, dynamic> json) => _$SwapsXyzQuoteFromJson(json);
+
+ @JsonKey(name: "amountIn")
+ final SwapsXyzPayment amountIn;
+
+ @JsonKey(name: "amountInMax")
+ final SwapsXyzPayment amountInMax;
+ @JsonKey(name: "amountOut")
+ final SwapsXyzPayment amountOut;
+
+ @JsonKey(name: "amountOutMin")
+ final SwapsXyzPayment amountOutMin;
+ @JsonKey(name: "protocolFee")
+ final SwapsXyzPayment? protocolFee;
+
+ @JsonKey(name: "applicationFee")
+ final SwapsXyzPayment? applicationFee;
+ @JsonKey(name: "bridgeFee")
+ final SwapsXyzPayment? bridgeFee;
+
+ @JsonKey(name: "exchangeRate")
+ final double exchangeRate;
+
+ @JsonKey(name: "estimatedTxTime")
+ final double? estimatedTxTime;
+ @JsonKey(name: "estimatedPriceImpact")
+ final double? estimatedPriceImpact;
+ @JsonKey(name: "vmId", unknownEnumValue: SwapsXyzVmId.unknown)
+ final SwapsXyzVmId vmId;
+ @JsonKey(name: "requiresTokenApproval")
+ final bool? requiresTokenApproval;
+ @JsonKey(name: "requiresRegisterTransaction")
+ final bool? requiresRegisterTransaction;
+ @JsonKey(name: "executionsType", unknownEnumValue: SwapsXyzExecutionsType.unknown)
+ final SwapsXyzExecutionsType? executionsType;
+}
+
+
+@JsonSerializable()
+@StringBoolConverter()
+class SwapsXyzActionRequest extends ApiRequest<SwapsXyzActionResponse> {
+ const SwapsXyzActionRequest({
+ required this.actionType,
+ required this.sender,
+ required this.srcChainId,
+ required this.srcToken,
+ required this.dstChainId,
+ required this.dstToken,
+ required this.slippage,
+ this.amount,
+ this.swapDirection,
+ this.recipient,
+ this.to,
+ this.data,
+ this.value,
+ this.erc20Amount,
+ this.erc20Spender,
+ this.solanaSponsor,
+ this.bridgeIds,
+ this.refundTo,
+ this.returnDepositAddress,
+ this.appFees,
+ this.userId,
+ this.gasless,
+ });
+
+ factory SwapsXyzActionRequest.fromJson(Map<String, dynamic> json) =>
+ _$SwapsXyzActionRequestFromJson(json);
+
+ @JsonKey(name: "actionType")
+ final SwapsXyzActionType actionType;
+ @JsonKey(name: "sender")
+ final String sender;
+
+ @JsonKey(name: "srcChainId")
+ final String srcChainId;
+ @JsonKey(name: "srcToken")
+ final String srcToken;
+ @JsonKey(name: "dstChainId")
+ final String dstChainId;
+ @JsonKey(name: "dstToken")
+ final String dstToken;
+
+ @JsonKey(name: "slippage")
+ final String slippage;
+
+ @JsonKey(name: "amount", includeIfNull: false)
+ final String? amount;
+ @JsonKey(name: "swapDirection", includeIfNull: false)
+ final SwapsXyzSwapDirection? swapDirection;
+
+ @JsonKey(name: "recipient", includeIfNull: false)
+ final String? recipient;
+
+ @JsonKey(name: "to", includeIfNull: false)
+ final String? to;
+ @JsonKey(name: "data", includeIfNull: false)
+ final String? data;
+ @JsonKey(name: "value", includeIfNull: false)
+ final String? value;
+ @JsonKey(name: "erc20Amount", includeIfNull: false)
+ final String? erc20Amount;
+ @JsonKey(name: "erc20Spender", includeIfNull: false)
+ final String? erc20Spender;
+ @JsonKey(name: "solanaSponsor", includeIfNull: false)
+ final String? solanaSponsor;
+ @JsonKey(name: "bridgeIds", includeIfNull: false)
+ final List<String>? bridgeIds;
+ @JsonKey(name: "refundTo", includeIfNull: false)
+ final String? refundTo;
+ @JsonKey(name: "returnDepositAddress", includeIfNull: false)
+ final bool? returnDepositAddress;
+
+ @JsonKey(name: "appFees", includeIfNull: false)
+ final String? appFees;
+ @JsonKey(name: "userId", includeIfNull: false)
+ final String? userId;
+ @JsonKey(name: "gasless", includeIfNull: false)
+ final bool? gasless;
+
+ @override
+ String path() => "/api/getAction";
+
+ @override
+ Map<String, dynamic> toJson() => _$SwapsXyzActionRequestToJson(this);
+
+ @override
+ SwapsXyzActionResponse decode(Object json) =>
+ SwapsXyzActionResponse.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzPayment {
+ const SwapsXyzPayment({
+ required this.chainId,
+ required this.address,
+ required this.name,
+ required this.symbol,
+ required this.decimals,
+ required this.isNative,
+ required this.amount,
+ this.logo,
+ this.swapsXyzCode,
+ this.usdAmount,
+ });
+
+ factory SwapsXyzPayment.fromJson(Map<String, dynamic> json) => _$SwapsXyzPaymentFromJson(json);
+
+ @JsonKey(name: "chainId")
+ final int chainId;
+ @JsonKey(name: "address")
+ final String address;
+ @JsonKey(name: "name")
+ final String name;
+ @JsonKey(name: "symbol")
+ final String symbol;
+ @JsonKey(name: "decimals")
+ final int decimals;
+ @JsonKey(name: "isNative")
+ final bool isNative;
+ @JsonKey(name: "amount")
+ @SwapsXyzBigIntAmountConverter()
+ final BigInt amount;
+ @JsonKey(name: "logo")
+ final String? logo;
+ @JsonKey(name: "swapsXyzCode")
+ final String? swapsXyzCode;
+ @JsonKey(name: "usdAmount")
+ final double? usdAmount;
+
+ Money toMoney(CryptoCurrency currency) =>
+ Money(amount, currency, decimals).copyWith(currency: currency);
+}
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzEvmTransaction {
+ const SwapsXyzEvmTransaction({
+ required this.to,
+ required this.data,
+ required this.value,
+ this.chainId,
+ });
+
+ factory SwapsXyzEvmTransaction.fromJson(Map<String, dynamic> json) =>
+ _$SwapsXyzEvmTransactionFromJson(json);
+
+ @JsonKey(name: "to")
+ final String to;
+
+ @JsonKey(name: "data")
+ final String data;
+ @JsonKey(name: "value")
+ final String value;
+ @JsonKey(name: "chainId")
+ final int? chainId;
+}
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzSolanaTransaction {
+ const SwapsXyzSolanaTransaction({
+ required this.base64Tx,
+ required this.recentBlockhash,
+ required this.payer,
+ });
+
+ factory SwapsXyzSolanaTransaction.fromJson(Map<String, dynamic> json) =>
+ _$SwapsXyzSolanaTransactionFromJson(json);
+
+ @JsonKey(name: "base64Tx")
+ final String base64Tx;
+ @JsonKey(name: "recentBlockhash")
+ final String recentBlockhash;
+ @JsonKey(name: "payer")
+ final String payer;
+}
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzActionResponse {
+ const SwapsXyzActionResponse({
+ required this.tx,
+ required this.txId,
+ required this.vmId,
+ required this.amountIn,
+ required this.amountInMax,
+ required this.amountOut,
+ required this.amountOutMin,
+ required this.protocolFee,
+ required this.applicationFee,
+ required this.exchangeRate,
+ required this.estimatedTxTime,
+ required this.requiresTokenApproval,
+ required this.requiresRegisterTransaction,
+ this.estimatedPriceImpact,
+ this.bridgeFee,
+ this.bridgeIds,
+ this.allRoutes,
+ this.executionsType,
+ });
+
+ factory SwapsXyzActionResponse.fromJson(Map<String, dynamic> json) =>
+ _$SwapsXyzActionResponseFromJson(json);
+
+ @JsonKey(name: "tx")
+ final Map<String, dynamic> tx;
+ @JsonKey(name: "txId")
+ final String txId;
+ @JsonKey(name: "vmId", unknownEnumValue: SwapsXyzVmId.unknown)
+ final SwapsXyzVmId vmId;
+ @JsonKey(name: "amountIn")
+ final SwapsXyzPayment amountIn;
+ @JsonKey(name: "amountInMax")
+ final SwapsXyzPayment amountInMax;
+ @JsonKey(name: "amountOut")
+ final SwapsXyzPayment amountOut;
+ @JsonKey(name: "amountOutMin")
+ final SwapsXyzPayment amountOutMin;
+ @JsonKey(name: "protocolFee")
+ final SwapsXyzPayment protocolFee;
+ @JsonKey(name: "applicationFee")
+ final SwapsXyzPayment applicationFee;
+ @JsonKey(name: "bridgeFee")
+ final SwapsXyzPayment? bridgeFee;
+ @JsonKey(name: "bridgeIds")
+ final List<String>? bridgeIds;
+ @JsonKey(name: "exchangeRate")
+ final double exchangeRate;
+
+ @JsonKey(name: "estimatedTxTime")
+ final double estimatedTxTime;
+ @JsonKey(name: "estimatedPriceImpact")
+ final double? estimatedPriceImpact;
+ @JsonKey(name: "requiresTokenApproval")
+ final bool requiresTokenApproval;
+ @JsonKey(name: "requiresRegisterTransaction")
+ final bool requiresRegisterTransaction;
+ @JsonKey(name: "allRoutes")
+ final List<Map<String, dynamic>>? allRoutes;
+ @JsonKey(name: "executionsType", unknownEnumValue: SwapsXyzExecutionsType.unknown)
+ final SwapsXyzExecutionsType? executionsType;
+
+ SwapsXyzEvmTransaction get evmTx => SwapsXyzEvmTransaction.fromJson(tx);
+
+ SwapsXyzSolanaTransaction get solanaTx => SwapsXyzSolanaTransaction.fromJson(tx);
+}
+
+
+@JsonSerializable()
+class SwapsXyzTxRegistrationRequest extends ApiRequest<List<SwapsXyzValidatedTxId>> {
+ const SwapsXyzTxRegistrationRequest({
+ required this.txId,
+ this.txHash,
+ this.vmId,
+ this.chainId,
+ }) : super.post();
+
+ @JsonKey(name: "txId")
+ final String txId;
+ @JsonKey(name: "txHash", includeIfNull: false)
+ final String? txHash;
+
+ @JsonKey(name: "vmId", includeIfNull: false)
+ final String? vmId;
+ @JsonKey(name: "chainId", includeIfNull: false)
+ final int? chainId;
+
+ @override
+ String path() => "/api/registerTxs";
+
+ @override
+ Map<String, dynamic> toJson() => _$SwapsXyzTxRegistrationRequestToJson(this);
+
+ @override
+ List<SwapsXyzValidatedTxId> decode(Object json) => (json as List<dynamic>)
+ .map((item) => SwapsXyzValidatedTxId.fromJson(item as Map<String, dynamic>))
+ .toList();
+}
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzValidatedTxId {
+ const SwapsXyzValidatedTxId({required this.success, this.error});
+
+ factory SwapsXyzValidatedTxId.fromJson(Map<String, dynamic> json) =>
+ _$SwapsXyzValidatedTxIdFromJson(json);
+
+ @JsonKey(name: "success")
+ final bool success;
+ @JsonKey(name: "error")
+ final String? error;
+}
+
+
+/// query for GET /api/getStatus. all three are optional in the spec: look up by txId, or by
+/// txHash plus the chainId it was sent on
+@JsonSerializable()
+class SwapsXyzStatusRequest extends ApiRequest<SwapsXyzTxDetails> {
+ const SwapsXyzStatusRequest({this.txId, this.txHash, this.chainId});
+
+ @JsonKey(name: "txId", includeIfNull: false)
+ final String? txId;
+ @JsonKey(name: "txHash", includeIfNull: false)
+ final String? txHash;
+ @JsonKey(name: "chainId", includeIfNull: false)
+ final String? chainId;
+
+ @override
+ String path() => "/api/getStatus";
+
+ @override
+ Map<String, dynamic> toJson() => _$SwapsXyzStatusRequestToJson(this);
+
+ @override
+ SwapsXyzTxDetails decode(Object json) {
+ final map = json as Map<String, dynamic>;
+ if (map["success"] == false) {
+ throw Exception(SwapsXyzErrorResponse.messageOf(map) ?? "getStatus failed: $map");
+ }
+ return SwapsXyzTxDetails.fromJson(map);
+ }
+}
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzToken {
+ const SwapsXyzToken({
+ required this.name,
+ required this.symbol,
+ required this.decimals,
+ required this.amount,
+ required this.chainId,
+ this.address,
+ this.isNative,
+ this.usdAmount,
+ });
+
+ factory SwapsXyzToken.fromJson(Map<String, dynamic> json) => _$SwapsXyzTokenFromJson(json);
+
+ @JsonKey(name: "name")
+ final String name;
+ @JsonKey(name: "symbol")
+ final String symbol;
+ @JsonKey(name: "decimals")
+ final int decimals;
+ @JsonKey(name: "amount")
+ @SwapsXyzBigIntAmountConverter()
+ final BigInt amount;
+ @JsonKey(name: "chainId")
+ final int chainId;
+
+ @JsonKey(name: "address")
+ final String? address;
+ @JsonKey(name: "isNative")
+ final bool? isNative;
+ @JsonKey(name: "usdAmount")
+ final double? usdAmount;
+
+ Money toMoney(CryptoCurrency currency) =>
+ Money(amount, currency, decimals).copyWith(currency: currency);
+}
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzOnchainTx {
+ const SwapsXyzOnchainTx({
+ required this.txHash,
+ required this.chainId,
+ required this.timestamp,
+ this.toAddress,
+ this.value,
+ this.paymentToken,
+ this.revertReason,
+ });
+
+ factory SwapsXyzOnchainTx.fromJson(Map<String, dynamic> json) =>
+ _$SwapsXyzOnchainTxFromJson(json);
+
+ @JsonKey(name: "txHash")
+ final String txHash;
+ @JsonKey(name: "chainId")
+ final int chainId;
+ @JsonKey(name: "timestamp")
+ @SwapsXyzTimestampConverter()
+ final DateTime timestamp;
+ @JsonKey(name: "toAddress")
+ final String? toAddress;
+ @JsonKey(name: "value")
+ final String? value;
+
+ @JsonKey(name: "paymentToken")
+ final SwapsXyzToken? paymentToken;
+ @JsonKey(name: "revertReason")
+ final String? revertReason;
+}
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzTxNode {
+ const SwapsXyzTxNode({required this.chainId, this.txHash, this.timestamp, this.nextBridge});
+
+ factory SwapsXyzTxNode.fromJson(Map<String, dynamic> json) => _$SwapsXyzTxNodeFromJson(json);
+
+ @JsonKey(name: "chainId")
+ final int chainId;
+ @JsonKey(name: "txHash")
+ final String? txHash;
+ @JsonKey(name: "timestamp")
+ @SecondsDateTimeConverter()
+ final DateTime? timestamp;
+
+ @JsonKey(name: "nextBridge")
+ final String? nextBridge;
+}
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzBridgeDetails {
+ const SwapsXyzBridgeDetails({required this.isBridge, this.bridgeTime, this.txPath});
+
+ factory SwapsXyzBridgeDetails.fromJson(Map<String, dynamic> json) =>
+ _$SwapsXyzBridgeDetailsFromJson(json);
+
+ @JsonKey(name: "isBridge")
+ final bool isBridge;
+
+ @JsonKey(name: "bridgeTime")
+ final double? bridgeTime;
+ @JsonKey(name: "txPath")
+ final List<SwapsXyzTxNode>? txPath;
+}
+
+@JsonSerializable(createToJson: false)
+class SwapsXyzTxDetails {
+ const SwapsXyzTxDetails({
+ required this.status,
+ required this.sender,
+ required this.srcChainId,
+ required this.txId,
+ this.dstChainId,
+ this.srcTxHash,
+ this.dstTxHash,
+ this.bridgeDetails,
+ this.srcTx,
+ this.dstTx,
+ this.usdValue,
+ });
+
+ factory SwapsXyzTxDetails.fromJson(Map<String, dynamic> json) =>
+ _$SwapsXyzTxDetailsFromJson(json);
+
+ @JsonKey(name: "status", unknownEnumValue: SwapsXyzTxStatusValue.unknown)
+ final SwapsXyzTxStatusValue status;
+
+ @JsonKey(name: "sender")
+ final String sender;
+ @JsonKey(name: "srcChainId")
+ final int srcChainId;
+ @JsonKey(name: "dstChainId")
+ final int? dstChainId;
+ @JsonKey(name: "txId")
+ final String txId;
+ @JsonKey(name: "srcTxHash")
+ final String? srcTxHash;
+ @JsonKey(name: "dstTxHash")
+ final String? dstTxHash;
+ @JsonKey(name: "bridgeDetails")
+ final SwapsXyzBridgeDetails? bridgeDetails;
+ @JsonKey(name: "srcTx")
+ final SwapsXyzOnchainTx? srcTx;
+ @JsonKey(name: "dstTx")
+ final SwapsXyzOnchainTx? dstTx;
+ @JsonKey(name: "usdValue")
+ final double? usdValue;
+}
### lib/exchange/provider/swapsxyz/swapsxyz_exchange_provider.dart
@@ -0,0 +1,919 @@
+import "package:cake_wallet/.secrets.g.dart" as secrets;
+import "package:cake_wallet/core/utilities.dart";
+import "package:cake_wallet/evm/evm.dart";
+import "package:cake_wallet/exchange/exchange_provider_description.dart";
+import "package:cake_wallet/exchange/provider/exchange_provider.dart";
+import "package:cake_wallet/exchange/provider/swapsxyz/swapsxyz_api_schema.dart";
+import "package:cake_wallet/exchange/rate_request.dart";
+import "package:cake_wallet/exchange/trade.dart";
+import "package:cake_wallet/exchange/trade_request.dart";
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/exchange/utils/provider_api.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/exchange_limits.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/provider_rate.dart";
+import "package:cake_wallet/reactions/wallet_connect.dart";
+import "package:cake_wallet/store/settings_store.dart";
+import "package:cw_core/amount/exchange_rate.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/erc20_token.dart";
+import "package:cw_core/pending_transaction.dart";
+import "package:cw_core/transaction_priority.dart";
+import "package:cw_core/utils/print_verbose.dart";
+import "package:cw_core/wallet_base.dart";
+
+class SwapsXyzTrade extends RoutableTrade {
+ SwapsXyzTrade({
+ required this.vmId, required this.needToRegister,
+ required this.sourceTokenAddress,
+ required this.sourceTokenDecimals,
+ required this.sourceTokenAmountRaw,
+ required this.requiresTokenApproval,
+ required super.fundingAddress,
+ required super.state,
+ required super.depositAmount,
+ required super.payoutAmount,
+ required super.id,
+ required super.provider,
+ required super.payoutAddress,
+ required super.refundAddress,
+
+ required super.routerData,
+ required super.routerValue,
+ super.router,
+ super.createdAt,
+ super.expiredAt,
+ super.extraId,
+ super.outputTransaction,
+ super.walletId,
+ super.toAddressExtraId,
+ super.password,
+ super.providerId,
+ super.memo,
+ super.txId,
+ super.isRefund,
+ }) : super();
+
+ final bool needToRegister;
+ final String sourceTokenAddress;
+ final int sourceTokenDecimals;
+ final SwapsXyzVmId vmId;
+ final String sourceTokenAmountRaw;
+ final bool requiresTokenApproval;
+}
+
+class SwapsXyzExchangeProvider extends LimitsCacheExchangeProvider
+ implements TransactionCreationExchangeProvider, TransactionRegistrationExchangeProvider {
+ SwapsXyzExchangeProvider({required SettingsStore settingsStore, super.proxyWrapper})
+ : _settingsStore = settingsStore;
+
+ final SettingsStore _settingsStore;
+
+ 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 const _apiKey = secrets.swapsXyzApiKey;
+ static const _baseUrl = "api-v2.swaps.xyz";
+
+ late final _api = ProviderApi(
+ proxyWrapper,
+ authority: _baseUrl,
+ headers: {"x-api-key": _apiKey},
+ errorMessage: SwapsXyzErrorResponse.messageOf,
+ );
+
+ static final _supportedChainList = <SwapsXyzChain>[];
+ final Map<int, List<TokenPathInfo>> _tokensCache = {};
+
+ @override
+ bool get supportsFixedRate => false;
+
+ @override
+ ExchangeProviderDescription get description => ExchangeProviderDescription.swapsXyz;
+
+ @override
+ Future<ExchangeLimits> fetchLimits({
+ required CryptoCurrency from,
+ required CryptoCurrency to,
+ required bool isFixedRateMode,
+ }) async {
+ final chains = await _getSupportedChains();
+ 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 body = await _api.send(
+ SwapsXyzPathsRequest(
+ srcChainId: srcChain.chainId.toString(),
+ srcToken: srcToken,
+ dstChainId: dstChain.chainId.toString(),
+ dstToken: dstToken,
+ ),
+ );
+
+ if (body.paths.isEmpty) {
+ throw Exception("No paths for ${fromToUse.title} -> ${toToUse.title}");
+ }
+
+ final int requestedDstId = dstChain.chainId;
+
+ SwapsXyzChainPath? path = body.paths.firstWhereOrNull((p) => p.chainId == requestedDstId);
+
+ path ??= body.paths.firstWhere(
+ (p) => (p.tokens is List) || p.amountLimits != null,
+ orElse: () => body.paths.first,
+ );
+
+ if (isFixedRateMode && !path.supportsExactAmountOut) {
+ throw Exception("This route does not support fixed receive (exact-amount-out)");
+ }
+ if (!isFixedRateMode && !path.supportsExactAmountIn) {
+ throw Exception("This route does not support exact send (exact-amount-in)");
+ }
+
+ if (isFixedRateMode) {
+ final tokensField = path.tokens;
+
+ if (tokensField.isNotEmpty) {
+ final tokens = tokensField.tokens!;
+ final wantSym = _normalizeCakeNativeTokenName(toToUse.title).toUpperCase();
+ final wantAddr = dstToken.toLowerCase();
+
+ final match = tokens.firstWhereOrNull((t) {
+ final sym = t.symbol.toUpperCase();
+ final addr = t.address.toLowerCase();
+ return sym == wantSym || (addr.isNotEmpty && addr == wantAddr);
+ });
+
+ if (match != null) {
+ return ExchangeLimits(
+ min: Money.trySafeParse(match.minAmount, from),
+ max: Money.trySafeParse(match.maxAmount, from),
+ );
+ }
+ }
+ }
+ return ExchangeLimits(
+ min: Money.trySafeParse(path.amountLimits?.minAmount, from),
+ max: Money.trySafeParse(path.amountLimits?.maxAmount, from),
+ );
+ }
+
+ Future<SwapsXyzChainPath?> _pickPath({
+ required int srcChainId,
+ required String srcToken,
+ required int dstChainId,
+ required String dstToken,
+ }) async {
+ try {
+ final response = await _api.send(
+ SwapsXyzPathsRequest(
+ srcChainId: srcChainId.toString(),
+ srcToken: srcToken,
+ dstChainId: dstChainId.toString(),
+ dstToken: dstToken,
+ ),
+ );
+ return response.paths.firstOrNull;
+ } on ProviderHttpException {
+ return null;
+ }
+ }
+
+ @override
+ Future<ProviderRate> fetchRate(RateRequest request) async {
+ if (_notSupportedAsSourceToken.contains(request.depositCurrency)) {
+ throw Exception(
+ "fetchRate: source token ${request.depositCurrency.symbol} is not supported as source token",
+ );
+ }
+
+ if(_notSupportedAsSourceToken.contains(request.payoutCurrency)) {
+ throw Exception(
+ "fetchRate: source token ${request.payoutCurrency.symbol} is not supported as destination token",
+ );
+ }
+
+ final chains = await _getSupportedChains();
+ if (chains.isEmpty) {
+ throw Exception("chains.isEmpty");
+ }
+
+ final srcChain = _findChainByCurrency(request.depositCurrency, chains);
+ final dstChain = _findChainByCurrency(request.payoutCurrency, chains);
+
+ await _ensureTokensCached(
+ fromChain: srcChain,
+ toChain: dstChain,
+ from: request.depositCurrency,
+ to: request.payoutCurrency,
+ );
+
+ final srcToken = _getTokenAddress(currency: request.depositCurrency, chain: srcChain);
+ final dstToken = _getTokenAddress(currency: request.payoutCurrency, chain: dstChain);
+
+ if (request is FixedRateRequest) {
+ final path = await _pickPath(
+ srcChainId: srcChain.chainId,
+ srcToken: srcToken,
+ dstChainId: dstChain.chainId,
+ dstToken: dstToken,
+ );
+ if (path == null || !path.supportsExactAmountOut) {
+ throw Exception(
+ "fetchRate: route does not support exact-amount-out for ${request.depositCurrency.symbol} -> ${request.payoutCurrency.title}",
+ );
+ }
+ }
+
+ final decimals = request is FixedRateRequest
+ ? _chainDecimals(request.payoutCurrency, dstChain)
+ : _chainDecimals(request.depositCurrency, srcChain);
+
+ final data = await _api.send(
+ SwapsXyzQuoteRequest(
+ srcChainId: srcChain.chainId.toString(),
+ srcToken: srcToken,
+ dstChainId: dstChain.chainId.toString(),
+ dstToken: dstToken,
+ amount: _toChainUnits(request.amount, decimals).toString(),
+ swapDirection: switch (request) {
+ FloatingRateRequest() => .exactAmountIn,
+ FixedRateRequest() => .exactAmountOut,
+ },
+ ),
+ );
+
+ _checkDecimals(request is FixedRateRequest ? data.amountOut : data.amountIn, decimals);
+
+ return ProviderRate(
+ provider: description,
+ rate: switch (request) {
+ FloatingRateRequest() => ExchangeRate.fromAmounts(
+ request.amount,
+ data.amountOut.toMoney(request.payoutCurrency),
+ ),
+ FixedRateRequest() => ExchangeRate.fromAmounts(
+ data.amountIn.toMoney(request.depositCurrency),
+ request.amount,
+ ),
+ },
+ limits: await getLimits(
+ from: request.depositCurrency,
+ to: request.payoutCurrency,
+ isFixedRateMode: request is FixedRateRequest,
+ ),
+ );
+ }
+
+ @override
+ Future<Trade> createTrade({required TradeRequest request}) async {
+ final sender = request.refundAddress.trim();
+ final recipient = request.payoutAddress.trim();
+ if (sender.isEmpty || recipient.isEmpty) {
+ throw Exception("Sender (refundAddress) or recipient (toAddress) is empty");
+ }
+
+ final chains = await _getSupportedChains();
+ if (chains.isEmpty) {
+ throw Exception("Failed to fetch supported chains");
+ }
+ final srcChain = _findChainByCurrency(request.depositCurrency, chains);
+ final dstChain = _findChainByCurrency(request.payoutCurrency, chains);
+
+ await _ensureTokensCached(
+ fromChain: srcChain,
+ toChain: dstChain,
+ from: request.depositCurrency,
+ to: request.payoutCurrency,
+ );
+
+ final srcToken = _getTokenAddress(currency: request.depositCurrency, chain: srcChain);
+ final dstToken = _getTokenAddress(currency: request.payoutCurrency, chain: dstChain);
+
+ final amount = request.isFixedRate
+ ? request.payoutAmount
+ : request.depositAmount;
+ final decimals = request.isFixedRate
+ ? _chainDecimals(request.payoutCurrency, dstChain)
+ : _chainDecimals(request.depositCurrency, srcChain);
+
+ final data = await _api.send(
+ SwapsXyzActionRequest(
+ actionType: .swapAction,
+ sender: sender,
+ srcChainId: srcChain.chainId.toString(),
+ srcToken: srcToken,
+ dstChainId: dstChain.chainId.toString(),
+ dstToken: dstToken,
+ slippage: "300",
+ swapDirection: request.isFixedRate ? .exactAmountOut : .exactAmountIn,
+ amount: _toChainUnits(amount, decimals).toString(),
+ recipient: recipient,
+ ),
+ );
+
+ _checkDecimals(request.isFixedRate ? data.amountOut : data.amountIn, decimals);
+
+ final txId = data.txId;
+
+ final vmId = data.vmId;
+ final txObj = data.tx;
+
+ 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 ?? [];
+ 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 == .altVm ||
+ bridgeIds.contains("alt-vm") ||
+ chainId == "solana" ||
+ bridgeIds.contains("solana");
+
+ return SwapsXyzTrade(
+ state: TradeState.created,
+ depositAmount: request.depositAmount,
+ payoutAmount: request.payoutAmount,
+ fundingAddress: txTo ?? "",
+ createdAt: DateTime.now(),
+ id: txId,
+ provider: description,
+ payoutAddress: request.payoutAddress,
+ refundAddress: request.refundAddress,
+ routerData: routerData ?? "",
+ routerValue: txValue,
+ router: srcChain.chainId.toString(),
+ providerId: vmId.name,
+ vmId: vmId,
+ needToRegister: needToRegisterInSwapXyz,
+ sourceTokenAddress: data.amountIn.address,
+ sourceTokenDecimals: data.amountIn.decimals,
+ sourceTokenAmountRaw: data.amountInMax.amount.toString(),
+ requiresTokenApproval: data.requiresTokenApproval,
+ );
+ }
+
+ /// Alt-vm routes are only picked up once their source tx is registered with Swaps.xyz.
+ @override
+ Future<Trade> registerTransaction(Trade trade, String txHash) async {
+ trade as SwapsXyzTrade;
+
+ if (!trade.needToRegister) {
+ return trade;
+ }
+
+ final chainId = int.tryParse(trade.router ?? "");
+ if (chainId == null || chainId <= 0) {
+ throw Exception("Can't register $txHash, invalid chain id ${trade.router}");
+ }
+
+ final response = await _api.send(
+ SwapsXyzTxRegistrationRequest(
+ txId: trade.id,
+ txHash: txHash,
+ vmId: trade.vmId.toJson(),
+ chainId: chainId,
+ ),
+ );
+
+ if (response.firstOrNull?.success != true) {
+ throw Exception("Swaps.xyz didn't accept the registration of $txHash");
+ }
+
+ return trade;
+ }
+
+ @override
+ Future<Trade> updateTrade(Trade trade) async {
+ final data = await _api.send(SwapsXyzStatusRequest(txId: trade.id));
+
+ return trade.copyWith(
+ id: data.txId,
+ provider: description,
+ fundingAddress: data.srcTx?.toAddress,
+ payoutAddress: data.dstTx?.toAddress,
+ txId: data.srcTx?.txHash,
+ state: data.status.toState,
+ createdAt: data.srcTx?.timestamp ?? data.dstTx?.timestamp,
+ refundAddress: data.sender,
+ depositAmount: data.srcTx?.paymentToken?.toMoney(trade.depositCurrency),
+ payoutAmount: data.dstTx?.paymentToken?.toMoney(trade.payoutCurrency),
+ );
+ }
+
+ /// Swaps.xyz counts in the token's on-chain decimals, which aren't always Cake's
+ /// (AVAX is 9 in Cake, 18 on the C-chain)
+ int _chainDecimals(CryptoCurrency currency, SwapsXyzChain chain) =>
+ _tokensCache[chain.chainId]
+ ?.firstWhereOrNull((t) => t.symbol == _normalizeCakeNativeTokenName(currency.title))
+ ?.decimals ??
+ currency.decimals;
+
+ static BigInt _toChainUnits(Money amount, int decimals) => decimals >= amount.decimals
+ ? amount.amount * BigInt.from(10).pow(decimals - amount.decimals)
+ : amount.amount ~/ BigInt.from(10).pow(amount.decimals - decimals);
+
+ static void _checkDecimals(SwapsXyzPayment echoed, int sent) {
+ if (echoed.decimals != sent) {
+ throw Exception(
+ "Swaps.xyz counts ${echoed.symbol} in ${echoed.decimals} decimals, the amount was sent in $sent",
+ );
+ }
+ }
+
+ // Load & cache supported chains once
+ Future<List<SwapsXyzChain>> _getSupportedChains() async {
+ if (_supportedChainList.isNotEmpty) {
+ return _supportedChainList;
+ }
+ try {
+ final data = await _api.send(const SwapsXyzChainListRequest());
+ _supportedChainList
+ ..clear()
+ ..addAll(data);
+ return _supportedChainList;
+ } catch (e) {
+ printV(e);
+ return [];
+ }
+ }
+
+ Future<void> _ensureTokensCached({
+ required SwapsXyzChain fromChain,
+ required SwapsXyzChain 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 SwapsXyzPathsResponse body;
+ try {
+ body = await _api.send(
+ SwapsXyzPathsRequest(
+ srcChainId: srcChainId.toString(),
+ // Native placeholder
+ srcToken: "0x0000000000000000000000000000000000000000",
+ ),
+ );
+ } catch (e) {
+ printV("getPaths failed: $e");
+ return;
+ }
+
+ // Always cache the source chain's native token
+ if (body.srcToken.symbol.isNotEmpty) {
+ // Treat native token as address = null so _getTokenAddress() emits zero-address
+ _mergeCache(srcChainId, [TokenPathInfo.fromToken(body.srcToken, dropNativeAddress: true)]);
+ }
+
+ for (final path in body.paths) {
+ // "all" -> cache empty list to indicate all tokens supported
+ if (path.tokens.isAll) {
+ _tokensCache[path.chainId] ??= <TokenPathInfo>[];
+ } else if (path.tokens.isNotEmpty) {
+ _mergeCache(path.chainId, path.tokens.tokens!.map(TokenPathInfo.fromToken).toList());
+ }
+ }
+ }
+
+ // 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 SwapsXyzChain chain}) {
+ final symbol = _normalizeCakeNativeTokenName(currency.title);
+ final list = _tokensCache[chain.chainId];
+
+ 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";
+ }
+ }
+ }
+
+ 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;
+ }
+
+ SwapsXyzChain _findChainByCurrency(CryptoCurrency cur, List<SwapsXyzChain> chains) {
+ final network = _normalizeCakeNetwork(cur.tag ?? cur.title);
+ return chains.firstWhere(
+ (c) => c.name.toUpperCase() == network,
+ orElse: () => throw Exception("Unsupported chain for ${cur.title}"),
+ );
+ }
+
+ String _normalizeCakeNetwork(String network) => 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(),
+ };
+
+ String _decodeMethodSelector(String s) =>
+ (s.startsWith("0x") && s.length >= 10) ? s.substring(0, 10) : "";
+
+ @override
+ Future<PendingTransaction?> createTransaction(WalletBase wallet, Trade trade) async {
+ trade as SwapsXyzTrade;
+
+ final routerTo = trade.fundingAddress;
+ final routerData = trade.routerData;
+
+ if (!isEVMCompatibleChain(wallet.type) || routerData.isEmpty || routerData == "0x") {
+ return null;
+ }
+
+ final tokenContract = trade.sourceTokenAddress.toLowerCase();
+ final priority = _settingsStore.getPriority(wallet.type, chainId: wallet.chainId);
+ final routerValueWei = BigInt.tryParse(trade.routerValue) ?? BigInt.zero;
+
+ final selector = _decodeMethodSelector(routerData);
+ const transferSig = "0xa9059cbb";
+ const swapAndExecuteSig = "0x9be111d1";
+
+ // Direct Transfer (Simple routing, no approval needed)
+ if (selector == transferSig) {
+ return evm!.createRawCallDataTransaction(
+ wallet,
+ routerTo,
+ routerData,
+ Money.zero(wallet.currency),
+ priority,
+ useBlinkProtection: canSupportBlinkProtection(wallet.chainId)
+ ? _settingsStore.useBlinkProtection
+ : false,
+ );
+ }
+
+ // Smart Swap (Requires Approval)
+ if (selector == swapAndExecuteSig) {
+ final requiredAmount =
+ BigInt.tryParse(trade.sourceTokenAmountRaw.replaceAll("n", "")) ?? BigInt.zero;
+
+ Future<PendingTransaction> buildSwap() {
+ printV("[Swaps.xyz sending flow] Building swap transaction");
+ return evm!.createRawCallDataTransaction(
+ wallet,
+ routerTo,
+ routerData,
+ Money(routerValueWei, wallet.currency),
+ priority,
+ sourceTokenAddress: tokenContract,
+ sourceTokenAmount: requiredAmount,
+ useBlinkProtection: canSupportBlinkProtection(wallet.chainId)
+ ? _settingsStore.useBlinkProtection
+ : false,
+ );
+ }
+
+ final needsApproval = tokenContract.isNotEmpty && requiredAmount > BigInt.zero
+ ? await evm!.isApprovalRequired(wallet, tokenContract, routerTo, requiredAmount)
+ : false;
+
+ printV(
+ "[Swaps.xyz sending flow] Approval required: $needsApproval for token ${trade.depositAmount.serialized} with amount $requiredAmount",
+ );
+
+ if (!needsApproval) {
+ return buildSwap();
+ }
+
+ // USDT Approval Flow (Special Case). We must reset allowance to 0 first.
+ final isUSDTMainnet =
+ wallet.chainId == 1 &&
+ tokenContract.toLowerCase() == "0xdac17f958d2ee523a2206206994597c13d831ec7";
+ final currentAllowance =
+ isUSDTMainnet ? await evm!.getAllowance(wallet, tokenContract, routerTo) : null;
+ final needsReset = currentAllowance != null && currentAllowance > BigInt.zero;
+
+ if (needsReset) {
+ printV(
+ "[Swaps.xyz sending flow] currentAllowance USDT: $currentAllowance. Resetting to 0 before setting new allowance.",
+ );
+ }
+
+ Future<PendingTransaction> buildApproval(BigInt amount) async {
+ final approvalTx = await buildApprovalNeeded(
+ wallet: wallet,
+ spender: routerTo,
+ tokenContract: tokenContract,
+ requiredAmount: amount,
+ sourceTokenDecimals: trade.sourceTokenDecimals,
+ priority: priority,
+ );
+
+ if (approvalTx == null) {
+ throw Exception("Failed to build approval transaction");
+ }
+ return approvalTx;
+ }
+
+ Future<void> sendApproval(PendingTransaction approvalTx, BigInt amount) async {
+ printV(
+ "[Swaps.xyz sending flow] Submitting approval transaction for token ${trade.depositAmount.serialized} with amount $amount",
+ );
+ await approvalTx.commit();
+
+ final isReset = amount == BigInt.zero;
+ final isApproved = await _waitForApprovalUpdate(
+ wallet: wallet,
+ tokenContract: tokenContract,
+ spender: routerTo,
+ requiredAmount: amount,
+ waitForExactMatch: isReset,
+ );
+
+ if (!isApproved) {
+ throw Exception(
+ isReset
+ ? "Failed to reset USDT allowance. Please try again."
+ : "Approval transaction failed or timed out on-chain. Try again.",
+ );
+ }
+ printV("[Swaps.xyz sending flow] Approval to $amount confirmed on-chain.");
+ }
+
+ final firstApproval = await buildApproval(needsReset ? BigInt.zero : requiredAmount);
+
+ return _ApproveThenSwapTransaction(firstApproval, () async {
+ await sendApproval(firstApproval, needsReset ? BigInt.zero : requiredAmount);
+ if (needsReset) {
+ await sendApproval(await buildApproval(requiredAmount), requiredAmount);
+ }
+
+ final swapTx = await buildSwap();
+ await swapTx.commit();
+ return swapTx;
+ });
+ }
+
+ throw Exception("invalid selector");
+ }
+
+ Future<PendingTransaction?> buildApprovalNeeded({
+ required WalletBase wallet,
+ required String spender,
+ required String tokenContract,
+ required BigInt requiredAmount,
+ required TransactionPriority? priority,
+ int? sourceTokenDecimals,
+ }) {
+ final erc20Token = wallet.balance.keys.whereType<Erc20Token>().firstWhere(
+ (t) => t.contractAddress.toLowerCase() == tokenContract.toLowerCase(),
+ orElse: () => Erc20Token(
+ name: "",
+ symbol: "",
+ contractAddress: tokenContract,
+ decimal: sourceTokenDecimals ?? 18,
+ enabled: true,
+ ),
+ );
+
+ return evm!.createTokenApproval(
+ wallet,
+ Money(requiredAmount, erc20Token),
+ spender,
+ priority,
+ useBlinkProtection: canSupportBlinkProtection(wallet.chainId)
+ ? _settingsStore.useBlinkProtection
+ : false,
+ );
+ }
+
+ Future<bool> _waitForApprovalUpdate({
+ required WalletBase wallet,
+ required String tokenContract,
+ required String spender,
+ required BigInt requiredAmount,
+ bool waitForExactMatch = false,
+ }) async {
+ int attempts = 0;
+ const int maxAttempts = 30; // ~60 seconds
+
+ printV(
+ "[Swaps.xyz sending flow] Starting allowance check. Target: $requiredAmount (Exact match: $waitForExactMatch)",
+ );
+
+ while (attempts < maxAttempts) {
+ try {
+ final currentAllowance = await evm!.getAllowance(wallet, tokenContract, spender);
+
+ if (currentAllowance != null) {
+ printV(
+ "[Swaps.xyz sending flow] Current Allowance: $currentAllowance / Target: $requiredAmount",
+ );
+
+ if (waitForExactMatch) {
+ // For Reset (Target 0): We need it to be exactly 0 (or less, though it can't be negative)
+ if (currentAllowance <= requiredAmount) {
+ printV("[Swaps.xyz sending flow] Allowance reset verified!");
+ return true;
+ }
+ } else {
+ // For Approval: We need it to be at least the required amount
+ if (currentAllowance >= requiredAmount) {
+ printV("[Swaps.xyz sending flow] Allowance verified!");
+ return true;
+ }
+ }
+ }
+ } catch (e) {
+ printV("[Swaps.xyz sending flow] Allowance check error: $e");
+ }
+
+ await Future.delayed(const Duration(seconds: 1));
+ attempts++;
+ }
+
+ printV("[Swaps.xyz sending flow] Allowance check timed out.");
+ return false;
+ }
+}
+
+class _ApproveThenSwapTransaction with PendingTransaction {
+ _ApproveThenSwapTransaction(this._firstApproval, this._send);
+
+ final PendingTransaction _firstApproval;
+ final Future<PendingTransaction> Function() _send;
+ PendingTransaction? _swap;
+
+ PendingTransaction get _current => _swap ?? _firstApproval;
+
+ @override
+ String get id => _current.id;
+
+ @override
+ Money get amount => _current.amount;
+
+ @override
+ Money get fee => _current.fee;
+
+ @override
+ String get amountFormatted => _current.amountFormatted;
+
+ @override
+ String get feeFormatted => _current.feeFormatted;
+
+ @override
+ String get feeFormattedValue => _current.feeFormattedValue;
+
+ @override
+ String get hex => _current.hex;
+
+ @override
+ String? get evmTxHashFromRawHex => _current.evmTxHashFromRawHex;
+
+ @override
+ Future<void> commit() async => _swap = await _send();
+
+ @override
+ Future<Map<String, String>> commitUR() => throw UnimplementedError();
+}
+
+class TokenPathInfo {
+ TokenPathInfo({
+ required this.symbol,
+ required this.address,
+ required this.decimals,
+ required this.minAmount,
+ required this.maxAmount,
+ });
+
+ factory TokenPathInfo.fromToken(
+ SwapsXyzTokenInfoWithAmounts token, {
+ bool dropNativeAddress = false,
+ }) => TokenPathInfo(
+ symbol: token.symbol.toUpperCase(),
+ address: dropNativeAddress && token.isNative ? null : token.address,
+ decimals: token.decimals,
+ minAmount: token.minAmount,
+ maxAmount: token.maxAmount,
+ );
+ final String symbol;
+ final String? address;
+ final int? decimals;
+ final String? minAmount;
+ final String? maxAmount;
+}
### lib/exchange/provider/swapsxyz_exchange_provider.dart
@@ -1,841 +0,0 @@
-import 'dart:convert';
-
-import 'package:cake_wallet/.secrets.g.dart' as secrets;
-import "package:cake_wallet/exchange/exchange_exceptions.dart";
-import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/limits.dart';
-import 'package:cake_wallet/exchange/trade.dart';
-import 'package:cake_wallet/exchange/trade_not_created_exception.dart';
-import 'package:cake_wallet/exchange/trade_request.dart';
-import 'package:cake_wallet/exchange/trade_state.dart';
-import 'package:cw_core/amount_converter.dart';
-import "package:cw_core/exceptions/cake_exception.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
- bool get supportsMemoOrDestinationTag => 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 ExchangeProviderResponseException('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 ExchangeProviderResponseCodeException('Unexpected http status: ${res.statusCode}', 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 ExchangeProviderResponseException('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 ExchangeProviderResponseException(
- 'This route does not support fixed receive (exact-amount-out)');
- }
- if (!isFixedRateMode && !supportsExactAmountIn) {
- throw ExchangeProviderResponseException(
- '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 ExchangeProviderResponseException('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 ArgumentError(
- 'Sender (refundAddress) or recipient (toAddress) is empty');
- }
-
- final chains = await _geSupportedChain();
- if (chains.isEmpty) throw ExchangeProviderResponseException('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 ArgumentError('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 ExchangeProviderResponseException('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 ExchangeProviderResponseException('Does not support that method selector');
- }
-
- final txValue = txObj['value']?.toString() ?? '0';
-
- final bridgeIds = (data['bridgeIds'] as List?) ?? const [];
- if (txId.isEmpty) throw ExchangeProviderResponseException('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 ArgumentError('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 ExchangeProviderResponseCodeException('getStatus failed: ${resp.statusCode} ${resp.body}', resp.statusCode);
- }
-
- 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 ExchangeProviderResponseException(
- '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 BadCurrencyException('Unsupported chain for ${cur.title}', cur),
- );
- }
-
- 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});
-}
### lib/exchange/provider/swaptrade/swaptrade_api_schema.dart
@@ -0,0 +1,450 @@
+// spec reference: https://github.com/Swaptrade/swaptrade.github.io/blob/main/openapi.yaml
+
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/exchange/utils/provider_api.dart";
+import "package:json_annotation/json_annotation.dart";
+
+part "swaptrade_api_schema.g.dart";
+
+// numbers are inconsistently typed - get-coins returns price as "565.95000000" for most coins
+// but as 1 for USDT, and min/max as either int or double. note that an unsupported pair answers
+// with success and a price of "NaN", which double.parse happily returns as NaN
+class SwapTradeAmountConverter implements JsonConverter<double, Object> {
+ const SwapTradeAmountConverter();
+
+ @override
+ double fromJson(Object json) {
+ if (json is num) {
+ return json.toDouble();
+ }
+ if (json is String) {
+ return double.parse(json);
+ }
+ throw ArgumentError("unexpected SwapTrade amount: $json");
+ }
+
+ @override
+ Object toJson(double value) => value;
+}
+
+// the networks of a coin arrive as one comma separated string of chains, e.g. "ETH,TRX,BSC"
+class SwapTradeNetworkListConverter implements JsonConverter<List<String>, String?> {
+ const SwapTradeNetworkListConverter();
+
+ @override
+ List<String> fromJson(String? json) => (json ?? "")
+ .split(",")
+ .map((network) => network.trim())
+ .where((network) => network.isNotEmpty)
+ .toList();
+
+ @override
+ String? toJson(List<String> value) => value.isEmpty ? null : value.join(",");
+}
+
+class SwapTradeStatusConverter implements JsonConverter<TradeState, String> {
+ const SwapTradeStatusConverter();
+
+ @override
+ TradeState fromJson(String json) => switch (json) {
+ "1" => TradeState.waitingPayment,
+ "2" => TradeState.confirming,
+ "3" || "13" => TradeState.processing,
+ "4" || "5" => TradeState.exchanging,
+ "6" || "7" => TradeState.sending,
+ "8" => TradeState.completed,
+ "9" => TradeState.expired,
+ "10" => TradeState.underpaid,
+ "11" => TradeState.pending,
+ "12" => TradeState.refunded,
+ _ => TradeState.deserialize(raw: json),
+ };
+
+ @override
+ String toJson(TradeState state) => state.serialize();
+}
+
+@JsonSerializable(createToJson: false)
+class SwapTradeError {
+ const SwapTradeError({this.msg});
+
+ factory SwapTradeError.fromJson(Map<String, dynamic> json) => _$SwapTradeErrorFromJson(json);
+
+ @JsonKey(name: "msg")
+ final String? msg;
+}
+
+
+@JsonSerializable(createToJson: false)
+@SwapTradeAmountConverter()
+class SwapTradeCoin {
+ const SwapTradeCoin({
+ required this.id,
+ required this.name,
+ this.network = const [],
+ this.price,
+ this.min,
+ this.max,
+ this.minIncoming,
+ this.maxIncoming,
+ this.minOutgoing,
+ this.maxOutgoing,
+ this.minOutgoingUsd,
+ this.maxOutgoingUsd,
+ this.fee,
+ this.networkFee,
+ this.memo,
+ this.enabled,
+ this.amountScale,
+ this.erc,
+ });
+
+ factory SwapTradeCoin.fromJson(Map<String, dynamic> json) => _$SwapTradeCoinFromJson(json);
+
+ @JsonKey(name: "id")
+ final String id;
+ @JsonKey(name: "name")
+ final String name;
+
+ @JsonKey(name: "network")
+ @SwapTradeNetworkListConverter()
+ final List<String> network;
+
+ @JsonKey(name: "price")
+ final double? price;
+ @JsonKey(name: "min")
+ final double? min;
+ @JsonKey(name: "max")
+ final double? max;
+ @JsonKey(name: "min_incoming")
+ final double? minIncoming;
+ @JsonKey(name: "max_incoming")
+ final double? maxIncoming;
+ @JsonKey(name: "min_outgoing")
+ final double? minOutgoing;
+ @JsonKey(name: "max_outgoing")
+ final double? maxOutgoing;
+ @JsonKey(name: "min_outgoing_USD")
+ final double? minOutgoingUsd;
+ @JsonKey(name: "max_outgoing_USD")
+ final double? maxOutgoingUsd;
+ @JsonKey(name: "fee")
+ final double? fee;
+ @JsonKey(name: "network_fee")
+ final double? networkFee;
+
+ @JsonKey(name: "memo")
+ final bool? memo;
+ @JsonKey(name: "enabled")
+ final bool? enabled;
+
+ @JsonKey(name: "amount_scale")
+ final int? amountScale;
+
+ // seems undocumented, but we use it anyway?
+ @JsonKey(name: "erc")
+ final int? erc;
+}
+
+class SwapTradeCoinsRequest extends ApiRequest<SwapTradeCoinsResponse> {
+ const SwapTradeCoinsRequest();
+
+ @override
+ String path() => "/api/swap/get-coins";
+
+ @override
+ Map<String, dynamic> toJson() => const {};
+
+ @override
+ SwapTradeCoinsResponse decode(Object json) =>
+ SwapTradeCoinsResponse.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+class SwapTradeCoinsResponse {
+ const SwapTradeCoinsResponse({required this.success, this.status, this.msg, this.data, this.errors});
+
+ factory SwapTradeCoinsResponse.fromJson(Map<String, dynamic> json) =>
+ _$SwapTradeCoinsResponseFromJson(json);
+
+ @JsonKey(name: "success")
+ final bool success;
+ @JsonKey(name: "status")
+ final int? status;
+ @JsonKey(name: "msg")
+ final String? msg;
+ @JsonKey(name: "data")
+ final List<SwapTradeCoin>? data;
+ @JsonKey(name: "errors")
+ final List<SwapTradeError>? errors;
+}
+
+
+@JsonSerializable()
+class SwapTradeGetRateRequest {
+ const SwapTradeGetRateRequest({
+ required this.coinSend,
+ required this.coinReceive,
+ this.amount,
+ this.ref,
+ });
+
+ @JsonKey(name: "coin_send")
+ final String coinSend;
+ @JsonKey(name: "coin_receive")
+ final String coinReceive;
+
+ // not in the spec, but we use it ig?
+ @JsonKey(name: "amount", includeIfNull: false)
+ final String? amount;
+
+ @JsonKey(name: "ref", defaultValue: "cake")
+ final String? ref;
+
+ Map<String, dynamic> toJson() => _$SwapTradeGetRateRequestToJson(this);
+}
+
+@JsonSerializable()
+class SwapTradeGetPriceRequest extends ApiRequest<SwapTradeRateResponse> {
+ SwapTradeGetPriceRequest({required this.coinSend, required this.coinSendNetwork, required this.coinReceive, required this.coinReceiveNetwork, required this.amountSend, required this.markup})
+ : super.post();
+
+
+ @JsonKey(name: "coin_send")
+ final String coinSend;
+ @JsonKey(name: "coin_send_network")
+ final String coinSendNetwork;
+ @JsonKey(name: "coin_receive")
+ final String coinReceive;
+ @JsonKey(name: "coin_receive_network")
+ final String coinReceiveNetwork;
+ @JsonKey(name: "amount_send")
+ final String amountSend;
+ @JsonKey(name: "markup")
+ final double markup;
+
+ @override
+ String path() => "/api/swap/get-price";
+
+ @override
+ Map<String, dynamic> toJson() => _$SwapTradeGetPriceRequestToJson(this);
+
+ @override
+ SwapTradeRateResponse decode(Object json) =>
+ SwapTradeRateResponse.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+@SwapTradeAmountConverter()
+class SwapTradeRate {
+ const SwapTradeRate({required this.price, this.symbol});
+
+ factory SwapTradeRate.fromJson(Map<String, dynamic> json) => _$SwapTradeRateFromJson(json);
+
+ @JsonKey(name: "data")
+ final double price;
+
+ @JsonKey(name: "symbol")
+ final String? symbol;
+}
+
+@JsonSerializable(createToJson: false)
+class SwapTradeRateResponse {
+ const SwapTradeRateResponse({required this.success, this.status, this.msg, this.data, this.errors});
+
+ factory SwapTradeRateResponse.fromJson(Map<String, dynamic> json) =>
+ _$SwapTradeRateResponseFromJson(json);
+
+ @JsonKey(name: "success")
+ final bool success;
+ @JsonKey(name: "status")
+ final int? status;
+ @JsonKey(name: "msg")
+ final String? msg;
+ @JsonKey(name: "data")
+ final SwapTradeRate? data;
+ @JsonKey(name: "errors")
+ final List<SwapTradeError>? errors;
+}
+
+
+@JsonSerializable()
+class SwapTradeCreateOrderRequest extends ApiRequest<SwapTradeCreateOrderResponse> {
+ const SwapTradeCreateOrderRequest({
+ required this.coinSend,
+ required this.coinSendNetwork,
+ required this.coinReceive,
+ required this.coinReceiveNetwork,
+ required this.amountSend,
+ required this.recipient,
+ this.refundAddress,
+ this.ref,
+ this.markup,
+ }) : super.post();
+
+ @JsonKey(name: "coin_send")
+ final String coinSend;
+ @JsonKey(name: "coin_send_network")
+ final String coinSendNetwork;
+ @JsonKey(name: "coin_receive")
+ final String coinReceive;
+ @JsonKey(name: "coin_receive_network")
+ final String coinReceiveNetwork;
+
+ @JsonKey(name: "amount_send")
+ final String amountSend;
+ @JsonKey(name: "recipient")
+ final String recipient;
+
+ // not in the spec, the provider sends it
+ @JsonKey(name: "refund_address", includeIfNull: false)
+ final String? refundAddress;
+ @JsonKey(name: "ref", includeIfNull: false)
+ final String? ref;
+ @JsonKey(name: "markup", includeIfNull: false)
+ final double? markup;
+
+ @override
+ String path() => "/api/swap/create-order";
+
+ @override
+ Map<String, dynamic> toJson() => _$SwapTradeCreateOrderRequestToJson(this);
+
+ @override
+ SwapTradeCreateOrderResponse decode(Object json) =>
+ SwapTradeCreateOrderResponse.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+@SwapTradeAmountConverter()
+class SwapTradeCreatedOrder {
+ const SwapTradeCreatedOrder({
+ required this.orderId,
+ required this.serverAddress,
+ this.amountReceive,
+ });
+
+ factory SwapTradeCreatedOrder.fromJson(Map<String, dynamic> json) =>
+ _$SwapTradeCreatedOrderFromJson(json);
+
+ @JsonKey(name: "order_id")
+ final String orderId;
+ @JsonKey(name: "server_address")
+ final String serverAddress;
+ @JsonKey(name: "amount_receive")
+ final double? amountReceive;
+}
+
+@JsonSerializable(createToJson: false)
+class SwapTradeCreateOrderResponse {
+ const SwapTradeCreateOrderResponse({
+ required this.success,
+ this.status,
+ this.msg,
+ this.data,
+ this.errors,
+ });
+
+ factory SwapTradeCreateOrderResponse.fromJson(Map<String, dynamic> json) =>
+ _$SwapTradeCreateOrderResponseFromJson(json);
+
+ @JsonKey(name: "success")
+ final bool success;
+ @JsonKey(name: "status")
+ final int? status;
+ @JsonKey(name: "msg")
+ final String? msg;
+ @JsonKey(name: "data")
+ final SwapTradeCreatedOrder? data;
+ @JsonKey(name: "errors")
+ final List<SwapTradeError>? errors;
+}
+
+
+@JsonSerializable()
+class SwapTradeOrderRequest extends ApiRequest<SwapTradeOrderResponse> {
+ const SwapTradeOrderRequest({required this.orderId}) : super.post();
+
+ @JsonKey(name: "order_id")
+ final String orderId;
+
+ @override
+ String path() => "/api/swap/order";
+
+ @override
+ Map<String, dynamic> toJson() => _$SwapTradeOrderRequestToJson(this);
+
+ @override
+ SwapTradeOrderResponse decode(Object json) =>
+ SwapTradeOrderResponse.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+@SwapTradeAmountConverter()
+@SwapTradeStatusConverter()
+class SwapTradeOrder {
+ const SwapTradeOrder({
+ required this.orderId,
+ required this.coinSend,
+ required this.coinReceive,
+ required this.status,
+ required this.serverAddress,
+ required this.recipient,
+ this.amountSend,
+ this.amountReceive,
+ this.memo,
+ this.createdAt,
+ this.refundAddress,
+ this.outgoingTx,
+ });
+
+ factory SwapTradeOrder.fromJson(Map<String, dynamic> json) => _$SwapTradeOrderFromJson(json);
+
+ @JsonKey(name: "order_id")
+ final String orderId;
+ @JsonKey(name: "coin_send")
+ final String coinSend;
+ @JsonKey(name: "coin_receive")
+ final String coinReceive;
+ @JsonKey(name: "status")
+ final TradeState status;
+
+ @JsonKey(name: "server_address")
+ final String serverAddress;
+
+ @JsonKey(name: "recipient")
+ final String recipient;
+ @JsonKey(name: "amount_send")
+ final double? amountSend;
+ @JsonKey(name: "amount_receive")
+ final double? amountReceive;
+
+ @JsonKey(name: "memo")
+ final String? memo;
+ @JsonKey(name: "created_at")
+ final DateTime? createdAt;
+
+ @JsonKey(name: "refund_address")
+ final String? refundAddress;
+ @JsonKey(name: "outgoing_tx")
+ final String? outgoingTx;
+}
+
+@JsonSerializable(createToJson: false)
+class SwapTradeOrderResponse {
+ const SwapTradeOrderResponse({required this.success, this.status, this.msg, this.data, this.errors});
+
+ factory SwapTradeOrderResponse.fromJson(Map<String, dynamic> json) =>
+ _$SwapTradeOrderResponseFromJson(json);
+
+ @JsonKey(name: "success")
+ final bool success;
+ @JsonKey(name: "status")
+ final int? status;
+ @JsonKey(name: "msg")
+ final String? msg;
+ @JsonKey(name: "data")
+ final SwapTradeOrder? data;
+ @JsonKey(name: "errors")
+ final List<SwapTradeError>? errors;
+}
### lib/exchange/provider/swaptrade/swaptrade_exchange_provider.dart
@@ -0,0 +1,225 @@
+import "package:cake_wallet/.secrets.g.dart" as secrets;
+import "package:cake_wallet/core/utilities.dart";
+import "package:cake_wallet/exchange/exchange_exceptions.dart";
+import "package:cake_wallet/exchange/exchange_provider_description.dart";
+import "package:cake_wallet/exchange/provider/exchange_provider.dart";
+import "package:cake_wallet/exchange/provider/swaptrade/swaptrade_api_schema.dart";
+import "package:cake_wallet/exchange/rate_request.dart";
+import "package:cake_wallet/exchange/trade.dart";
+import "package:cake_wallet/exchange/trade_not_created_exception.dart";
+import "package:cake_wallet/exchange/trade_request.dart";
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/exchange/utils/provider_api.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/exchange_limits.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/provider_rate.dart";
+import "package:cw_core/amount/exchange_rate.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/utils/print_verbose.dart";
+
+class SwapTradeExchangeProvider extends ExchangeProvider {
+ SwapTradeExchangeProvider({super.proxyWrapper});
+
+ static final markup = double.tryParse(secrets.swapTradeExchangeMarkup) ?? 0;
+
+ static const apiAuthority = "api.swaptrade.io";
+
+ late final _api = ProviderApi(
+ proxyWrapper,
+ authority: apiAuthority,
+ errorMessage: (json) => switch (json["errors"]) {
+ [{"msg": final Object msg}, ...] => msg.toString(),
+ _ => (json["msg"] ?? json["message"])?.toString(),
+ },
+ );
+
+ @override
+ bool get supportsFixedRate => false;
+
+ @override
+ ExchangeProviderDescription get description => ExchangeProviderDescription.swapTrade;
+
+ @override
+ Future<ExchangeLimits> fetchLimits({
+ required CryptoCurrency from,
+ required CryptoCurrency to,
+ required bool isFixedRateMode,
+ }) async {
+ final coins = await _fetchCoins();
+ _networkFor(from, coins);
+ _networkFor(to, coins);
+ return _limitsFor(from, coins);
+ }
+
+ @override
+ Future<ProviderRate> fetchRate(RateRequest request) async {
+ if (request is! FloatingRateRequest) {
+ throw Exception("fixed rate unsupported");
+ }
+ if (request.depositCurrency == CryptoCurrency.btcln ||
+ request.payoutCurrency == CryptoCurrency.btcln) {
+ throw Exception("lightning not supported");
+ }
+
+ final coins = await _fetchCoins();
+ final responseBody = await _api.send(
+ SwapTradeGetPriceRequest(
+ coinSend: _normalizeCurrency(request.depositCurrency),
+ coinSendNetwork: _networkFor(request.depositCurrency, coins),
+ coinReceiveNetwork: _networkFor(request.payoutCurrency, coins),
+ coinReceive: _normalizeCurrency(request.payoutCurrency),
+ amountSend: request.depositAmount.toString(),
+ markup: markup,
+ ),
+ );
+
+ if (responseBody.success == false) {
+ final error = responseBody.errors?.firstOrNull?.msg;
+ throw Exception(error ?? "rejected the quote: ${responseBody.msg}");
+ }
+
+ final payout = responseBody.data?.price;
+
+ if(payout == null) {
+ throw Exception("payout is null: ${responseBody.msg}");
+ }
+
+ return ProviderRate(
+ provider: description,
+ rate: ExchangeRate.fromAmounts(
+ request.depositAmount,
+ Money.parse(payout.toStringAsFixed(request.payoutCurrency.decimals), request.payoutCurrency),
+ ),
+ limits: _limitsFor(request.depositCurrency, coins),
+ );
+ }
+
+ @override
+ Future<Trade> createTrade({required TradeRequest request}) async {
+ final coins = await _fetchCoins();
+ final responseBody = await _api.send(
+ SwapTradeCreateOrderRequest(
+ coinSend: _normalizeCurrency(request.depositCurrency),
+ coinSendNetwork: _networkFor(request.depositCurrency, coins),
+ coinReceive: _normalizeCurrency(request.payoutCurrency),
+ coinReceiveNetwork: _networkFor(request.payoutCurrency, coins),
+ amountSend: request.depositAmount.toString(),
+ recipient: request.payoutAddress,
+ markup: markup,
+ ref: "cake",
+ refundAddress: request.refundAddress,
+ ),
+ mapError: (e) => switch (e.statusCode) {
+ 400 => TradeNotCreatedException(description, description: e.message),
+ _ => null,
+ },
+ );
+
+ if (responseBody.success == false) {
+ final error = responseBody.errors?.firstOrNull?.msg ?? responseBody.msg ?? "";
+ throw TradeNotCreatedException(description, description: error);
+ }
+
+ final responseData = responseBody.data;
+
+ final trade = Trade(
+ id: responseData!.orderId,
+ fundingAddress: responseData.serverAddress,
+ provider: description,
+ createdAt: DateTime.now(),
+ state: TradeState.created,
+ payoutAddress: request.payoutAddress,
+ refundAddress: request.refundAddress,
+ depositAmount: request.depositAmount,
+ payoutAmount: Money.safeParse(responseData.amountReceive ?? 0, request.payoutCurrency),
+ );
+
+ try {
+ // swaptrade only returns the correct amount in status check requests... for... some reason
+ return await updateTrade(trade);
+ } catch (e) {
+ printV("failed to refresh swaptrade trade ${trade.id}: $e");
+ return trade;
+ }
+ }
+
+ @override
+ Future<Trade> updateTrade(Trade trade) async {
+ final responseBody = await _api.send(
+ SwapTradeOrderRequest(orderId: trade.id),
+ mapError: (e) => switch (e.statusCode) {
+ 400 => TradeNotFoundException(trade.id, provider: description, description: e.message),
+ _ => null,
+ },
+ );
+
+ if (responseBody.success == false) {
+ final error = responseBody.errors?.firstOrNull?.msg ?? responseBody.msg ?? "";
+ throw TradeNotFoundException(trade.id, provider: description, description: error);
+ }
+
+ final responseData = responseBody.data!;
+
+ return trade.copyWith(
+ state: responseData.status,
+ memo: responseData.memo,
+ createdAt: responseData.createdAt,
+ depositAmount: Money.safeParse(
+ responseData.amountSend,
+ trade.depositCurrency,
+ ),
+ payoutAmount: Money.safeParse(
+ responseData.amountReceive,
+ trade.payoutCurrency,
+ ),
+ fundingAddress: responseData.serverAddress,
+ payoutAddress: responseData.recipient,
+ refundAddress: _nonEmpty(responseData.refundAddress),
+ outputTransaction: _nonEmpty(responseData.outgoingTx),
+ isRefund: responseData.status == TradeState.refunded,
+ );
+ }
+
+ String _normalizeCurrency(CryptoCurrency currency) {
+ switch (currency) {
+ default:
+ return currency.title.toUpperCase();
+ }
+ }
+
+ Future<List<SwapTradeCoin>> _fetchCoins() async {
+ final response = await _api.send(const SwapTradeCoinsRequest());
+
+ if (response.success == false) {
+ throw Exception(response.errors?.firstOrNull?.msg ?? response.msg ?? "coins unavailable");
+ }
+
+ return response.data ?? const [];
+ }
+
+ SwapTradeCoin? _coinFor(CryptoCurrency currency, List<SwapTradeCoin> coins) =>
+ coins.firstWhereOrNull((c) => c.id.toUpperCase() == _normalizeCurrency(currency));
+
+ String _networkFor(CryptoCurrency currency, List<SwapTradeCoin> coins) {
+ final network = currency.network.toUpperCase();
+ final supported = _coinFor(currency, coins)?.network.map((n) => n.toUpperCase()) ?? const [];
+
+ if (!supported.contains(network)) {
+ throw Exception("SwapTrade has no $network network for ${currency.title}");
+ }
+
+ return network;
+ }
+
+ ExchangeLimits _limitsFor(CryptoCurrency from, List<SwapTradeCoin> coins) {
+ final coin = _coinFor(from, coins);
+
+ if (coin == null) {
+ throw Exception("${from.title} unsupported");
+ }
+
+ return ExchangeLimits(min: Money.trySafeParse(coin.min, from), max: Money.trySafeParse(coin.max, from));
+ }
+
+ String? _nonEmpty(String? value) => (value?.isEmpty ?? true) ? null : value;
+}
### lib/exchange/provider/swaptrade_exchange_provider.dart
@@ -1,434 +0,0 @@
-import 'dart:convert';
-
-import 'package:cake_wallet/.secrets.g.dart' as secrets;
-import "package:cake_wallet/exchange/exchange_exceptions.dart";
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/limits.dart';
-import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
-import 'package:cake_wallet/exchange/trade.dart';
-import 'package:cake_wallet/exchange/trade_not_created_exception.dart';
-import 'package:cake_wallet/exchange/trade_not_found_exception.dart';
-import 'package:cake_wallet/exchange/trade_request.dart';
-import 'package:cake_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:cake_wallet/utils/exchange_provider_logger.dart';
-
-class SwapTradeExchangeProvider extends ExchangeProvider {
- SwapTradeExchangeProvider();
-
- static final markup = secrets.swapTradeExchangeMarkup;
-
- static Map<String, List<String>>? _coinNetworks;
-
- 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
- bool get supportsMemoOrDestinationTag => 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 coins = await _fetchCoins();
- if (!await _isPairSupported(from, to)) {
- return null;
- }
-
- final normalized = _normalizeCurrency(from);
- final coin = coins.firstWhere((c) => c['id'].toString().toUpperCase() == normalized);
-
- 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 (!await _isPairSupported(from, to)) 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 (responseBody['success'] != true) {
- ExchangeProviderLogger.logError(
- provider: description,
- function: 'fetchRate',
- error: ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}\n${_errorMessage(responseBody)}', response.statusCode),
- stackTrace: StackTrace.current,
- requestData: {
- 'from': from.title,
- 'to': to.title,
- 'amount': amount,
- 'isFixedRateMode': isFixedRateMode,
- 'isReceiveAmount': isReceiveAmount,
- 'body': body,
- 'url': uri.toString(),
- },
- );
- throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}\n${_errorMessage(responseBody)}', 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 {
- final sendNetwork = await _networkFor(request.fromCurrency);
- final receiveNetwork = await _networkFor(request.toCurrency);
- if (sendNetwork == null || receiveNetwork == null) {
- throw TradeNotCreatedException(
- description,
- description: "SwapTrade has no network for "
- "${request.fromCurrency.title} ${request.fromCurrency.tag ?? ""} or "
- "${request.toCurrency.title} ${request.toCurrency.tag ?? ""}",
- );
- }
-
- try {
- final params = <String, dynamic>{};
- var body = <String, dynamic>{
- 'coin_send': _normalizeCurrency(request.fromCurrency),
- 'coin_send_network': sendNetwork,
- 'coin_receive': _normalizeCurrency(request.toCurrency),
- 'coin_receive_network': receiveNetwork,
- '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 (responseBody['success'] != true) {
- final error = _errorMessage(responseBody);
-
- 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 ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}\n$description: $error', 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 (responseBody['success'] != true) {
- final error = _errorMessage(responseBody);
- throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}\n$description: $error', response.statusCode);
- }
-
- final responseData = responseBody['data'] as Map<String, dynamic>;
- final fromCurrency = responseData['coin_send'] as String;
- final fromNetwork = responseData['coin_send_network_name'] as String?;
- final from = CryptoCurrency.safeParseCurrencyFromString(fromCurrency,
- tag: fromNetwork == fromCurrency ? null : fromNetwork);
- final toCurrency = responseData['coin_receive'] as String;
- final toNetwork = responseData['coin_receive_network_name'] as String?;
- final to = CryptoCurrency.safeParseCurrencyFromString(toCurrency,
- tag: toNetwork == toCurrency ? null : toNetwork);
- final inputAddress = responseData['server_address'] as String;
- final payoutAddress = responseData['recipient'] as String;
- final status = responseData['status'] as String;
- final state = _tradeState(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?;
- final refundAddress = responseData['refund_address'] as String?;
- final payoutTx = responseData['outgoing_tx'] 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 ?? ''),
- refundAddress: refundAddress == '' ? null : refundAddress,
- isRefund: status == '12',
- outputTransaction: payoutTx == '' ? null : payoutTx,
- );
- } 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();
- }
- }
-
- Future<List<Map<String, dynamic>>> _fetchCoins() async {
- final response = await ProxyWrapper().get(clearnetUri: Uri.https(apiAuthority, getCoins));
- final responseJSON = json.decode(response.body) as Map<String, dynamic>;
- if (responseJSON['success'] != true) {
- throw Exception(_errorMessage(responseJSON));
- }
-
- final coins = (responseJSON['data'] as List).cast<Map<String, dynamic>>();
- _coinNetworks = {
- for (final coin in coins)
- coin['id'].toString().toUpperCase(): coin['network']
- .toString()
- .toUpperCase()
- .split(',')
- .map((network) => network.trim())
- .toList(),
- };
- return coins;
- }
-
- Future<bool> _isPairSupported(CryptoCurrency from, CryptoCurrency to) async =>
- await _networkFor(from) != null && await _networkFor(to) != null;
-
- Future<String?> _networkFor(CryptoCurrency currency) async {
- if (_coinNetworks == null) {
- await _fetchCoins();
- }
- final network = currency.network.toUpperCase();
- final supported = _coinNetworks![_normalizeCurrency(currency)] ?? const <String>[];
- return supported.contains(network) ? network : null;
- }
-
- String _errorMessage(Map<String, dynamic> responseBody) {
- final errors = responseBody['errors'];
- if (errors is List && errors.isNotEmpty) {
- return errors[0]['msg'].toString();
- }
- return (responseBody['msg'] ?? responseBody['message'] ?? responseBody).toString();
- }
-
- TradeState _tradeState(String status) => switch (status) {
- '1' => TradeState.waitingPayment,
- '2' => TradeState.confirming,
- '3' || '13' => TradeState.processing,
- '4' || '5' => TradeState.exchanging,
- '6' || '7' => TradeState.sending,
- '8' => TradeState.completed,
- '9' => TradeState.expired,
- '10' => TradeState.underpaid,
- '11' => TradeState.pending,
- '12' => TradeState.refunded,
- _ => TradeState.deserialize(raw: status),
- };
-}
### lib/exchange/provider/thorchain_exchange.provider.dart
@@ -1,357 +0,0 @@
-import 'dart:convert';
-
-import "package:cake_wallet/exchange/exchange_exceptions.dart";
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/limits.dart';
-import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
-import 'package:cake_wallet/exchange/trade.dart';
-import "package:cake_wallet/exchange/trade_not_created_exception.dart";
-import 'package:cake_wallet/exchange/trade_request.dart';
-import 'package:cake_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:cake_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
- bool get supportsMemoOrDestinationTag => 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 ArgumentError('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 TradeNotFoundException(id, description:'Trade not found for id: $formattedId', provider: description);
- } else if (response.statusCode != 200) {
- throw ExchangeProviderResponseCodeException('Unexpected HTTP status: ${response.statusCode}', 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 TradeNotCreatedException(description, description: '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');
- try {
- 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;
- } catch (e) {
- printV(e.toString());
- return null;
- }
- }
-
- 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: ExchangeProviderResponseCodeException('Unexpected HTTP status: ${response.statusCode}', response.statusCode),
- stackTrace: StackTrace.current,
- requestData: {
- 'params': params,
- 'url': uri.toString(),
- },
- );
- throw ExchangeProviderResponseCodeException('Unexpected HTTP status: ${response.statusCode}', response.statusCode);
- }
-
- if (response.body.contains('error')) {
- ExchangeProviderLogger.logError(
- provider: description,
- function: '_getSwapQuote',
- error: ExchangeProviderResponseException('Unexpected response: ${response.body}'),
- stackTrace: StackTrace.current,
- requestData: {
- 'params': params,
- 'url': uri.toString(),
- },
- );
- throw ExchangeProviderResponseException('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;
-}
### lib/exchange/provider/trocador/trocador_api_schema.dart
@@ -0,0 +1,503 @@
+// spec reference: https://trocador.app/en/docs/
+
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/exchange/utils/json_converters.dart";
+import "package:cake_wallet/exchange/utils/provider_api.dart";
+import "package:json_annotation/json_annotation.dart";
+
+part "trocador_api_schema.g.dart";
+
+// api uses python spelling of bools
+class TrocadorBoolConverter implements JsonConverter<bool, Object> {
+ const TrocadorBoolConverter();
+
+ @override
+ bool fromJson(Object json) {
+ if (json is bool) {
+ return json;
+ }
+ return json.toString().toLowerCase() == "true";
+ }
+
+ @override
+ Object toJson(bool value) => value ? "True" : "False";
+}
+
+// the top level amount_from, amount_to, minimum and
+// maximum come back as json numbers, while the same values inside a quote come back as strings
+class TrocadorAmountConverter implements JsonConverter<String, Object> {
+ const TrocadorAmountConverter();
+
+ @override
+ String fromJson(Object json) => json.toString();
+
+ @override
+ Object toJson(String value) => value;
+}
+
+enum TrocadorRating {
+ @JsonValue("A")
+ a,
+ @JsonValue("B")
+ b,
+ @JsonValue("C")
+ c,
+ @JsonValue("D")
+ d,
+ unknown;
+
+ String get label => switch (this) {
+ a => "A",
+ b => "B",
+ c => "C",
+ d => "D",
+ unknown => "N/A",
+ };
+}
+
+
+@JsonSerializable()
+class TrocadorCoinRequest extends ApiRequest<List<TrocadorCoin>> {
+ const TrocadorCoinRequest({this.ticker, this.name});
+
+ @JsonKey(name: "ticker", includeIfNull: false)
+ final String? ticker;
+ @JsonKey(name: "name", includeIfNull: false)
+ final String? name;
+
+ @override
+ String path() => "/coin";
+
+ @override
+ Map<String, dynamic> toJson() => _$TrocadorCoinRequestToJson(this);
+
+ @override
+ List<TrocadorCoin> decode(Object json) => (json as List<dynamic>)
+ .map((item) => TrocadorCoin.fromJson(item as Map<String, dynamic>))
+ .toList();
+}
+
+@JsonSerializable(createToJson: false)
+@TrocadorBoolConverter()
+class TrocadorCoin {
+ const TrocadorCoin({
+ required this.name,
+ required this.ticker,
+ required this.network,
+ this.memo,
+ this.image,
+ this.minimum,
+ this.maximum,
+ });
+
+ factory TrocadorCoin.fromJson(Map<String, dynamic> json) => _$TrocadorCoinFromJson(json);
+
+ @JsonKey(name: "name")
+ final String name;
+ @JsonKey(name: "ticker")
+ final String ticker;
+ @JsonKey(name: "network")
+ final String network;
+
+ @JsonKey(name: "memo")
+ final bool? memo;
+ @JsonKey(name: "image")
+ final String? image;
+ @JsonKey(name: "minimum")
+ @TrocadorAmountConverter()
+ final String? minimum;
+ @JsonKey(name: "maximum")
+ @TrocadorAmountConverter()
+ final String? maximum;
+}
+
+
+@JsonSerializable()
+@TrocadorBoolConverter()
+class TrocadorNewRateRequest extends ApiRequest<TrocadorRate> {
+ const TrocadorNewRateRequest({
+ required this.tickerFrom,
+ required this.networkFrom,
+ required this.tickerTo,
+ required this.networkTo,
+ this.amountFrom,
+ this.amountTo,
+ this.payment,
+ this.minKycrating,
+ this.minLogpolicy,
+ this.markup,
+ this.bestOnly,
+ });
+
+ @JsonKey(name: "ticker_from")
+ final String tickerFrom;
+ @JsonKey(name: "network_from")
+ final String networkFrom;
+ @JsonKey(name: "ticker_to")
+ final String tickerTo;
+ @JsonKey(name: "network_to")
+ final String networkTo;
+
+ @JsonKey(name: "amount_from", includeIfNull: false)
+ final String? amountFrom;
+ @JsonKey(name: "amount_to", includeIfNull: false)
+ final String? amountTo;
+ @JsonKey(name: "payment", includeIfNull: false)
+ final bool? payment;
+ @JsonKey(name: "min_kycrating", includeIfNull: false)
+ final TrocadorRating? minKycrating;
+ @JsonKey(name: "min_logpolicy", includeIfNull: false)
+ final TrocadorRating? minLogpolicy;
+ @JsonKey(name: "markup", includeIfNull: false)
+ final String? markup;
+ @JsonKey(name: "best_only", includeIfNull: false)
+ final bool? bestOnly;
+
+ @override
+ String path() => "/new_rate";
+
+ @override
+ Map<String, dynamic> toJson() => _$TrocadorNewRateRequestToJson(this);
+
+ @override
+ TrocadorRate decode(Object json) => TrocadorRate.fromJson(json as Map<String, dynamic>);
+}
+
+// every provider is quoted once per rate type, so the same provider can show up twice.
+// a swap quote carries amount_to, a payment quote carries amount_from instead
+@JsonSerializable(createToJson: false)
+@TrocadorBoolConverter()
+class TrocadorQuote {
+ const TrocadorQuote({required this.provider, this.fixed, this.amountFrom, this.amountTo});
+
+ factory TrocadorQuote.fromJson(Map<String, dynamic> json) => _$TrocadorQuoteFromJson(json);
+
+ @JsonKey(name: "provider")
+ final String provider;
+ @JsonKey(name: "fixed")
+ final bool? fixed;
+ @JsonKey(name: "amount_from")
+ @TrocadorAmountConverter()
+ final String? amountFrom;
+ @JsonKey(name: "amount_to")
+ @TrocadorAmountConverter()
+ final String? amountTo;
+}
+
+@JsonSerializable(createToJson: false)
+class TrocadorQuotes {
+ const TrocadorQuotes({this.quotes});
+
+ factory TrocadorQuotes.fromJson(Map<String, dynamic> json) => _$TrocadorQuotesFromJson(json);
+
+ @JsonKey(name: "quotes")
+ final List<TrocadorQuote>? quotes;
+}
+
+@JsonSerializable(createToJson: false)
+@TradeStateConverter()
+@TrocadorBoolConverter()
+class TrocadorRate {
+ const TrocadorRate({
+ required this.tradeId,
+ required this.tickerFrom,
+ required this.tickerTo,
+ required this.coinFrom,
+ required this.coinTo,
+ required this.networkFrom,
+ required this.networkTo,
+ required this.amountFrom,
+ required this.amountTo,
+ required this.provider,
+ required this.status,
+ this.date,
+ this.fixed,
+ this.payment,
+ this.quotes,
+ });
+
+ factory TrocadorRate.fromJson(Map<String, dynamic> json) => _$TrocadorRateFromJson(json);
+
+ @JsonKey(name: "trade_id")
+ final String tradeId;
+ @JsonKey(name: "date")
+ final DateTime? date;
+ @JsonKey(name: "ticker_from")
+ final String tickerFrom;
+ @JsonKey(name: "ticker_to")
+ final String tickerTo;
+ @JsonKey(name: "coin_from")
+ final String coinFrom;
+ @JsonKey(name: "coin_to")
+ final String coinTo;
+ @JsonKey(name: "network_from")
+ final String networkFrom;
+ @JsonKey(name: "network_to")
+ final String networkTo;
+ @JsonKey(name: "amount_from")
+ @TrocadorAmountConverter()
+ final String amountFrom;
+ @JsonKey(name: "amount_to")
+ @TrocadorAmountConverter()
+ final String amountTo;
+
+ @JsonKey(name: "provider")
+ final String provider;
+
+ @JsonKey(name: "fixed")
+ final bool? fixed;
+ @JsonKey(name: "status")
+ final TradeState status;
+ @JsonKey(name: "quotes")
+ final TrocadorQuotes? quotes;
+ @JsonKey(name: "payment")
+ final bool? payment;
+}
+
+
+@JsonSerializable()
+@TrocadorBoolConverter()
+class TrocadorNewTradeRequest extends ApiRequest<TrocadorTrade> {
+ const TrocadorNewTradeRequest({
+ required this.tickerFrom,
+ required this.networkFrom,
+ required this.tickerTo,
+ required this.networkTo,
+ required this.address,
+ required this.provider,
+ required this.fixed,
+ this.id,
+ this.amountFrom,
+ this.amountTo,
+ this.addressMemo,
+ this.refund,
+ this.refundMemo,
+ this.payment,
+ this.minKycrating,
+ this.minLogpolicy,
+ this.webhook,
+ this.webhookKey,
+ this.markup,
+ });
+
+ @JsonKey(name: "id", includeIfNull: false)
+ final String? id;
+ @JsonKey(name: "ticker_from")
+ final String tickerFrom;
+ @JsonKey(name: "network_from")
+ final String networkFrom;
+ @JsonKey(name: "ticker_to")
+ final String tickerTo;
+ @JsonKey(name: "network_to")
+ final String networkTo;
+ @JsonKey(name: "amount_from", includeIfNull: false)
+ final String? amountFrom;
+ @JsonKey(name: "amount_to", includeIfNull: false)
+ final String? amountTo;
+ @JsonKey(name: "address")
+ final String address;
+ @JsonKey(name: "address_memo", includeIfNull: false)
+ final String? addressMemo;
+ @JsonKey(name: "refund", includeIfNull: false)
+ final String? refund;
+ @JsonKey(name: "refund_memo", defaultValue: "0")
+ final String? refundMemo;
+ @JsonKey(name: "provider")
+ final String provider;
+ @JsonKey(name: "fixed")
+ final bool fixed;
+ @JsonKey(name: "payment", includeIfNull: false)
+ final bool? payment;
+ @JsonKey(name: "min_kycrating", includeIfNull: false)
+ final TrocadorRating? minKycrating;
+ @JsonKey(name: "min_logpolicy", includeIfNull: false)
+ final TrocadorRating? minLogpolicy;
+
+ @JsonKey(name: "webhook", includeIfNull: false)
+ final String? webhook;
+ @JsonKey(name: "webhook_key", includeIfNull: false)
+ final String? webhookKey;
+ @JsonKey(name: "markup", includeIfNull: false)
+ final String? markup;
+
+ @override
+ String path() => "/new_trade";
+
+ @override
+ Map<String, dynamic> toJson() => _$TrocadorNewTradeRequestToJson(this);
+
+ @override
+ TrocadorTrade decode(Object json) => TrocadorTrade.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createFactory: false)
+class TrocadorTradeRequest extends ApiRequest<TrocadorTrade> {
+ const TrocadorTradeRequest({required this.id});
+
+ @JsonKey(name: "id")
+ final String id;
+
+ @override
+ String path() => "/trade";
+
+ @override
+ Map<String, dynamic> toJson() => _$TrocadorTradeRequestToJson(this);
+
+ @override
+ TrocadorTrade decode(Object json) =>
+ TrocadorTrade.fromJson((json as List<dynamic>).first as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+class TrocadorTradeDetails {
+ const TrocadorTradeDetails({this.hashout});
+
+ factory TrocadorTradeDetails.fromJson(Map<String, dynamic> json) =>
+ _$TrocadorTradeDetailsFromJson(json);
+
+ @JsonKey(name: "hashout")
+ final String? hashout;
+}
+
+@JsonSerializable(createToJson: false)
+@TradeStateConverter()
+@TrocadorBoolConverter()
+class TrocadorTrade {
+ const TrocadorTrade({
+ required this.tradeId,
+ required this.tickerFrom,
+ required this.tickerTo,
+ required this.coinFrom,
+ required this.coinTo,
+ required this.networkFrom,
+ required this.networkTo,
+ required this.amountFrom,
+ required this.amountTo,
+ required this.provider,
+ required this.status,
+ required this.addressProvider,
+ required this.addressUser,
+ this.date,
+ this.fixed,
+ this.payment,
+ this.addressProviderMemo,
+ this.addressUserMemo,
+ this.refundAddress,
+ this.refundAddressMemo,
+ this.password,
+ this.idProvider,
+ this.quotes,
+ this.details,
+ });
+
+ factory TrocadorTrade.fromJson(Map<String, dynamic> json) => _$TrocadorTradeFromJson(json);
+
+ @JsonKey(name: "trade_id")
+ final String tradeId;
+ @JsonKey(name: "date")
+ final DateTime? date;
+ @JsonKey(name: "ticker_from")
+ final String tickerFrom;
+ @JsonKey(name: "ticker_to")
+ final String tickerTo;
+ @JsonKey(name: "coin_from")
+ final String coinFrom;
+ @JsonKey(name: "coin_to")
+ final String coinTo;
+ @JsonKey(name: "network_from")
+ final String networkFrom;
+ @JsonKey(name: "network_to")
+ final String networkTo;
+ @JsonKey(name: "amount_from")
+ @TrocadorAmountConverter()
+ final String amountFrom;
+ @JsonKey(name: "amount_to")
+ @TrocadorAmountConverter()
+ final String amountTo;
+ @JsonKey(name: "provider")
+ final String provider;
+ @JsonKey(name: "fixed")
+ final bool? fixed;
+ @JsonKey(name: "status")
+ final TradeState status;
+
+ @JsonKey(name: "address_provider")
+ final String addressProvider;
+ @JsonKey(name: "address_provider_memo")
+ final String? addressProviderMemo;
+
+ @JsonKey(name: "address_user")
+ final String addressUser;
+ @JsonKey(name: "address_user_memo")
+ final String? addressUserMemo;
+ @JsonKey(name: "refund_address")
+ final String? refundAddress;
+ @JsonKey(name: "refund_address_memo")
+ final String? refundAddressMemo;
+
+ @JsonKey(name: "password")
+ final String? password;
+ @JsonKey(name: "id_provider")
+ final String? idProvider;
+ @JsonKey(name: "quotes")
+ final TrocadorQuotes? quotes;
+ @JsonKey(name: "details")
+ final TrocadorTradeDetails? details;
+ @JsonKey(name: "payment")
+ final bool? payment;
+}
+
+
+@JsonSerializable(createToJson: false)
+@TrocadorBoolConverter()
+class TrocadorPartner {
+ const TrocadorPartner({
+ required this.name,
+ this.rating,
+ this.insurance,
+ this.enabledMarkup,
+ this.eta,
+ });
+
+ factory TrocadorPartner.fromJson(Map<String, dynamic> json) => _$TrocadorPartnerFromJson(json);
+
+ @JsonKey(name: "name")
+ final String name;
+ @JsonKey(name: "rating", unknownEnumValue: TrocadorRating.unknown)
+ final TrocadorRating? rating;
+ @JsonKey(name: "insurance")
+ final double? insurance;
+ @JsonKey(name: "enabledmarkup")
+ final bool? enabledMarkup;
+ @JsonKey(name: "eta")
+ final double? eta;
+}
+
+@JsonSerializable(createFactory: false)
+class TrocadorExchangesRequest extends ApiRequest<TrocadorExchangesResponse> {
+ const TrocadorExchangesRequest({required this.apiKey});
+
+ @JsonKey(name: "api_key")
+ final String apiKey;
+
+ @override
+ String path() => "/exchanges";
+
+ @override
+ Map<String, dynamic> toJson() => _$TrocadorExchangesRequestToJson(this);
+
+ @override
+ TrocadorExchangesResponse decode(Object json) =>
+ TrocadorExchangesResponse.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+class TrocadorExchangesResponse {
+ const TrocadorExchangesResponse({required this.list});
+
+ factory TrocadorExchangesResponse.fromJson(Map<String, dynamic> json) =>
+ _$TrocadorExchangesResponseFromJson(json);
+
+ @JsonKey(name: "list")
+ final List<TrocadorPartner> list;
+}
### lib/exchange/provider/trocador/trocador_exchange_provider.dart
@@ -0,0 +1,320 @@
+import "package:cake_wallet/.secrets.g.dart" as secrets;
+import "package:cake_wallet/exchange/exchange_provider_description.dart";
+import "package:cake_wallet/exchange/provider/exchange_provider.dart";
+import "package:cake_wallet/exchange/provider/trocador/trocador_api_schema.dart";
+import "package:cake_wallet/exchange/rate_request.dart";
+import "package:cake_wallet/exchange/trade.dart";
+import "package:cake_wallet/exchange/trade_request.dart";
+import "package:cake_wallet/exchange/utils/provider_api.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/exchange_limits.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/provider_rate.dart";
+import "package:cake_wallet/utils/exchange_provider_logger.dart";
+import "package:cake_wallet/wallet_type_utils.dart";
+import "package:cw_core/amount/exchange_rate.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/utils/print_verbose.dart";
+
+class TrocadorExchangeProvider extends LimitsCacheExchangeProvider {
+ TrocadorExchangeProvider({
+ this.useTorOnly = false,
+ this.providerStates = const {},
+ super.proxyWrapper,
+ });
+
+ bool useTorOnly;
+ Map<String, bool> providerStates;
+
+ static const List<String> availableProviders = [
+ "Swapter",
+ "StealthEx",
+ "Simpleswap",
+ "Swapuz",
+ "ChangeNow",
+ "Changehero",
+ "FixedFloat",
+ "LetsExchange",
+ "Exolix",
+ "Godex",
+ "Exch",
+ "CoinCraddle",
+ "Alfacash",
+ "LocalMonero",
+ "XChange",
+ "NeroSwap",
+ "Changee",
+ "BitcoinVN",
+ "EasyBit",
+ "WizardSwap",
+ "Quantex",
+ "SwapSpace",
+ ];
+
+ static final apiKey = isMoneroOnly ? secrets.trocadorMoneroApiKey : secrets.trocadorApiKey;
+ static const clearNetAuthority = "api.trocador.app";
+ static const onionApiAuthority = "65bsisadnxvw4kfz7h7a3jwcyenrhluuj3kd5toslfzxbk5q4m3wy6qd.onion";
+ static const markup = secrets.trocadorExchangeMarkup;
+
+ late final _api = ProviderApi(
+ proxyWrapper,
+ authority: clearNetAuthority,
+ onionAuthority: onionApiAuthority,
+ useTorOnly: useTorOnly,
+ headers: {"API-Key": apiKey},
+ errorMessage: (json) => switch ((json["error"], json["message"])) {
+ (null, null) => null,
+ (final error, final message) => "${error ?? "Unknown error"}\n${message ?? ""}",
+ },
+ );
+
+ static const _quoteLifetime = Duration(seconds: 30);
+
+ ({RateRequest request, TrocadorRate rate, List<TrocadorQuote> quotes, DateTime fetchedAt})?
+ _lastQuotes;
+
+ @override
+ bool get supportsFixedRate => true;
+
+ @override
+ bool get supportsOnionAddress => true;
+
+ @override
+ ExchangeProviderDescription get description => ExchangeProviderDescription.trocador;
+
+ @override
+ Future<ExchangeLimits> fetchLimits({
+ required CryptoCurrency from,
+ required CryptoCurrency to,
+ required bool isFixedRateMode,
+ }) async {
+ final coins = await _api.send(
+ TrocadorCoinRequest(ticker: _normalizeCurrency(from), name: from.name),
+ );
+
+ final coinJson = coins.first;
+
+ return ExchangeLimits(
+ min: Money.trySafeParse(coinJson.minimum, from),
+ max: Money.trySafeParse(coinJson.maximum, from),
+ );
+ }
+
+ @override
+ Future<ProviderRate> fetchRate(RateRequest request) async {
+ final (rate, quotes) = await _getQuotes(request);
+ _lastQuotes = (request: request, rate: rate, quotes: quotes, fetchedAt: DateTime.now());
+
+ return ProviderRate(
+ provider: description,
+ rate: ExchangeRate.fromAmounts(
+ Money.safeParse(quotes.first.amountFrom ?? rate.amountFrom, request.depositCurrency),
+ Money.safeParse(quotes.first.amountTo ?? rate.amountTo, request.payoutCurrency),
+ ),
+ limits: await getLimits(
+ from: request.depositCurrency,
+ to: request.payoutCurrency,
+ isFixedRateMode: request is FixedRateRequest,
+ ),
+ );
+ }
+
+ @override
+ Future<Trade> createTrade({required TradeRequest request}) async {
+ final (rate, quotes) =
+ _takeLastQuotes(request.rateRequest) ?? await _getQuotes(request.rateRequest);
+
+ final responseData = await _newTrade(request, rate.tradeId, quotes.take(3).toList());
+
+ final depositAmount = responseData.amountFrom.isEmpty
+ ? request.depositAmount
+ : Money.safeParse(responseData.amountFrom, request.depositCurrency);
+ final payoutAmount = responseData.amountTo.isEmpty
+ ? request.payoutAmount
+ : Money.safeParse(responseData.amountTo, request.payoutCurrency);
+
+ final trade = Trade(
+ id: responseData.tradeId,
+ provider: description,
+ providerName: responseData.provider,
+ fundingAddress: responseData.addressProvider,
+ refundAddress: responseData.refundAddress ?? request.refundAddress,
+ state: responseData.status,
+ password: responseData.password,
+ providerId: responseData.idProvider,
+ createdAt: responseData.date?.toLocal(),
+ payoutAddress: responseData.addressUser,
+ extraId: responseData.addressProviderMemo,
+ toAddressExtraId: request.toAddressExtraId,
+ depositAmount: depositAmount,
+ payoutAmount: payoutAmount,
+ );
+
+ try {
+ // if trocador decides to update the amounts right after, this'll show the correct amounts
+ return await updateTrade(trade);
+ } catch (e) {
+ printV("failed to refresh trocador trade ${trade.id}: $e");
+ return trade;
+ }
+ }
+
+ Future<TrocadorTrade> _newTrade(
+ TradeRequest request,
+ String rateId,
+ List<TrocadorQuote> quotes,
+ ) async {
+ try {
+ return await _api.send(TrocadorNewTradeRequest(
+ id: rateId,
+ tickerFrom: _normalizeCurrency(request.depositCurrency),
+ networkFrom: _networkFor(request.depositCurrency),
+ tickerTo: _normalizeCurrency(request.payoutCurrency),
+ networkTo: _networkFor(request.payoutCurrency),
+ address: request.payoutAddress,
+ refundMemo: "0",
+ provider: quotes.first.provider,
+ fixed: request.isFixedRate,
+ payment: request.isFixedRate,
+ minKycrating: .c,
+ markup: markup,
+ amountFrom: request.isFixedRate ? null : request.depositAmount.toString(),
+ amountTo: request.isFixedRate ? request.payoutAmount.toString() : null,
+ addressMemo: request.toAddressExtraId,
+ refund: request.refundAddress,
+ ));
+ } on ProviderHttpException catch (e, st) {
+ if (e.statusCode != 400 || quotes.length == 1) {
+ rethrow;
+ }
+
+ ExchangeProviderLogger.logError(
+ provider: description,
+ function: "createTrade",
+ error: e,
+ stackTrace: st,
+ requestData: {"rateId": rateId, "subProvider": quotes.first.provider},
+ );
+ return _newTrade(request, rateId, quotes.sublist(1));
+ }
+ }
+
+ (TrocadorRate, List<TrocadorQuote>)? _takeLastQuotes(RateRequest request) {
+ final last = _lastQuotes;
+ _lastQuotes = null;
+
+ return switch (last) {
+ (request: final quoted, :final rate, :final quotes, :final fetchedAt)
+ when quoted == request && DateTime.now().difference(fetchedAt) < _quoteLifetime =>
+ (rate, quotes),
+ _ => null,
+ };
+ }
+
+ Future<(TrocadorRate, List<TrocadorQuote>)> _getQuotes(RateRequest request) async {
+ final (amountFrom, amountTo) = switch (request) {
+ FloatingRateRequest(:final depositAmount) => (depositAmount.toString(), null),
+ FixedRateRequest(:final payoutAmount) => (null, payoutAmount.toString()),
+ };
+
+ final rate = await _api.send(TrocadorNewRateRequest(
+ tickerFrom: _normalizeCurrency(request.depositCurrency),
+ networkFrom: _networkFor(request.depositCurrency),
+ tickerTo: _normalizeCurrency(request.payoutCurrency),
+ networkTo: _networkFor(request.payoutCurrency),
+ amountFrom: amountFrom,
+ amountTo: amountTo,
+ payment: request is FixedRateRequest,
+ minKycrating: .c,
+ markup: markup,
+ ));
+
+ final quotes = (rate.quotes?.quotes ?? [])
+ .where((quote) => providerStates[quote.provider] != false)
+ .where((quote) => quote.fixed == null || quote.fixed == (request is FixedRateRequest))
+ .toList();
+
+ if (quotes.isEmpty) {
+ throw Exception("No enabled providers found for the selected trade.");
+ }
+
+ return (rate, quotes);
+ }
+
+ @override
+ Future<Trade> updateTrade(Trade trade) async {
+ final responseData = await _api.send(TrocadorTradeRequest(id: trade.id));
+
+ return trade.copyWith(
+ refundAddress: responseData.refundAddress ?? "",
+ createdAt: responseData.date?.toLocal(),
+ state: responseData.status,
+ payoutAddress: responseData.addressUser,
+ providerName: responseData.provider,
+ password: responseData.password,
+ providerId: responseData.idProvider,
+ extraId: responseData.addressProviderMemo,
+ depositAmount: Money.safeParse(responseData.amountFrom, trade.depositCurrency),
+ payoutAmount: Money.safeParse(responseData.amountTo, trade.payoutCurrency),
+ fundingAddress: responseData.addressProvider,
+ );
+ }
+
+ Future<List<TrocadorPartner>> fetchProviders() async {
+ final response = await _api.send(TrocadorExchangesRequest(apiKey: apiKey));
+
+ return response.list.where((provider) => provider.rating != TrocadorRating.d).toList()
+ ..sort(
+ (a, b) => (a.rating ?? TrocadorRating.unknown).index
+ .compareTo((b.rating ?? TrocadorRating.unknown).index),
+ );
+ }
+
+ String _networkFor(CryptoCurrency currency) {
+ switch (currency) {
+ case CryptoCurrency.eth:
+ return "ERC20";
+ case CryptoCurrency.maticpoly:
+ return "Mainnet";
+ case CryptoCurrency.usdcpoly:
+ case CryptoCurrency.usdtPoly:
+ case CryptoCurrency.usdcEPoly:
+ return "MATIC";
+ case CryptoCurrency.zec:
+ return "Mainnet";
+ case CryptoCurrency.arb:
+ return "Mainnet";
+ default:
+ return currency.tag != null ? _normalizeTag(currency.tag!) : "Mainnet";
+ }
+ }
+
+ String _normalizeCurrency(CryptoCurrency currency) {
+ switch (currency) {
+ case CryptoCurrency.zec:
+ return "zec";
+ case CryptoCurrency.usdcEPoly:
+ return "usdce";
+ default:
+ return currency.title.toLowerCase();
+ }
+ }
+
+ String _normalizeTag(String tag) {
+ if (tag.contains("ARB")) {
+ return "Arbitrum";
+ }
+
+ switch (tag) {
+ case "ETH":
+ return "ERC20";
+ case "TRX":
+ return "TRC20";
+ case "LN":
+ return "Lightning";
+ case "BSC":
+ return "BEP20";
+ default:
+ return tag.toLowerCase();
+ }
+ }
+}
### lib/exchange/provider/trocador_exchange_provider.dart
@@ -1,590 +0,0 @@
-import 'dart:convert';
-
-import 'package:cake_wallet/.secrets.g.dart' as secrets;
-import "package:cake_wallet/exchange/exchange_exceptions.dart";
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/limits.dart';
-import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
-import 'package:cake_wallet/exchange/trade.dart';
-import 'package:cake_wallet/exchange/trade_request.dart';
-import 'package:cake_wallet/exchange/trade_state.dart';
-import 'package:cake_wallet/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:cake_wallet/utils/exchange_provider_logger.dart';
-
-class TrocadorExchangeProvider extends ExchangeProvider {
- TrocadorExchangeProvider({this.useTorOnly = false, this.providerStates = const {}})
- : _lastUsedRateId = '',
- _provider = [];
-
- bool useTorOnly;
- Map<String, bool> providerStates;
-
- static const List<String> availableProviders = [
- 'Swapter',
- 'StealthEx',
- 'Simpleswap',
- 'Swapuz',
- 'ChangeNow',
- 'Changehero',
- 'FixedFloat',
- 'LetsExchange',
- 'Exolix',
- 'Godex',
- 'Exch',
- 'CoinCraddle',
- 'Alfacash',
- 'LocalMonero',
- 'XChange',
- 'NeroSwap',
- 'Changee',
- 'BitcoinVN',
- 'EasyBit',
- 'WizardSwap',
- 'Quantex',
- 'SwapSpace',
- ];
-
- static final apiKey = isMoneroOnly ? secrets.trocadorMoneroApiKey : secrets.trocadorApiKey;
- static const clearNetAuthority = 'api.trocador.app';
- static const onionApiAuthority = '65bsisadnxvw4kfz7h7a3jwcyenrhluuj3kd5toslfzxbk5q4m3wy6qd.onion';
- static const markup = secrets.trocadorExchangeMarkup;
- static const newRatePath = '/new_rate';
- static const createTradePath = '/new_trade';
- static const tradePath = '/trade';
- static const coinPath = '/coin';
- static const providersListPath = '/exchanges';
-
- String _lastUsedRateId;
- List<dynamic> _provider;
-
- @override
- String get title => 'Trocador';
-
- @override
- bool get isAvailable => true;
-
- @override
- bool get isEnabled => true;
-
- @override
- bool get supportsFixedRate => true;
-
- @override
- bool get supportsOnionAddress => true;
-
- @override
- ExchangeProviderDescription get description => ExchangeProviderDescription.trocador;
-
- @override
- Future<bool> checkIsAvailable() async => true;
-
- @override
- Future<Limits?> fetchLimits(
- {required CryptoCurrency from,
- required CryptoCurrency to,
- required bool isFixedRateMode}) async {
- final params = {
- 'ticker': _normalizeCurrency(from),
- 'name': from.name,
- };
-
- final uri = await _getUri(coinPath, params);
- final response = await ProxyWrapper().get(clearnetUri: uri, headers: {'API-Key': apiKey});
-
- if (response.statusCode != 200)
- throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
-
- final responseJSON = json.decode(response.body) as List<dynamic>;
-
- if (responseJSON.isEmpty) throw ExchangeProviderResponseException('No data');
-
- final coinJson = responseJSON.first as Map<String, dynamic>;
-
- final min = double.tryParse(coinJson['minimum']?.toString() ?? '');
- final max = double.tryParse(coinJson['maximum']?.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 params = <String, String>{
- 'ticker_from': _normalizeCurrency(from),
- 'ticker_to': _normalizeCurrency(to),
- 'network_from': _networkFor(from),
- 'network_to': _networkFor(to),
- if (!isFixedRateMode) 'amount_from': amount.toString(),
- if (isFixedRateMode) 'amount_to': amount.toString(),
- 'payment': isFixedRateMode ? 'True' : 'False',
- 'min_kycrating': 'C',
- 'markup': markup,
- };
-
- final uri = await _getUri(newRatePath, params);
- final response = await ProxyWrapper().get(clearnetUri: uri, headers: {'API-Key': apiKey});
-
- final responseJSON = json.decode(response.body) as Map<String, dynamic>;
- final fromAmount = double.tryParse(responseJSON['amount_from']?.toString() ?? '') ?? 0.0;
- final toAmount = double.tryParse(responseJSON['amount_to']?.toString() ?? '') ?? 0.0;
-
- if (fromAmount <= 0 || toAmount <= 0) return 0.0;
-
- final quotesData = responseJSON['quotes'];
- final rateId = _safeString(responseJSON, 'trade_id');
-
- if (quotesData == null || quotesData is! Map<String, dynamic>) {
- return 0.0;
- }
- final quotes = (quotesData['quotes'] as List?) ?? [];
- _provider = quotes
- .where((quote) => providerStates[quote['provider']] != false)
- .map((quote) => quote['provider'])
- .toList();
-
- if (_provider.isEmpty) {
- ExchangeProviderLogger.logError(
- provider: description,
- function: 'fetchRate',
- error: Exception('No enabled providers found for the selected trade.'),
- stackTrace: StackTrace.current,
- requestData: {
- 'from': from.title,
- 'to': to.title,
- 'amount': amount,
- 'isFixedRateMode': isFixedRateMode,
- 'isReceiveAmount': isReceiveAmount,
- 'params': params,
- 'url': uri.toString(),
- },
- );
- throw ExchangeProviderResponseException('No enabled providers found for the selected trade.');
- }
-
- if (rateId.isNotEmpty) _lastUsedRateId = rateId;
-
- final rate = isReceiveAmount ? (amount / fromAmount) : (toAmount / 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: {
- 'fromAmount': fromAmount,
- 'toAmount': toAmount,
- 'rate': rate,
- 'rateId': rateId,
- 'provider': _provider.first,
- '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());
- return 0.0;
- }
- }
-
- @override
- Future<Trade> createTrade({
- required TradeRequest request,
- required bool isFixedRateMode,
- required bool isSendAll,
- }) async {
- final params = {
- 'ticker_from': _normalizeCurrency(request.fromCurrency),
- 'ticker_to': _normalizeCurrency(request.toCurrency),
- 'network_from': _networkFor(request.fromCurrency),
- 'network_to': _networkFor(request.toCurrency),
- 'payment': isFixedRateMode ? 'True' : 'False',
- 'min_kycrating': 'C',
- 'markup': markup,
- if (!isFixedRateMode) 'amount_from': request.fromAmount,
- if (isFixedRateMode) 'amount_to': request.toAmount,
- 'address': request.toAddress,
- if (request.toAddressExtraId.isNotEmpty) 'address_memo': request.toAddressExtraId,
- 'refund': request.refundAddress,
- 'refund_memo': '0',
- };
-
- if (isFixedRateMode) {
- await fetchRate(
- from: request.fromCurrency,
- to: request.toCurrency,
- amount: double.tryParse(request.toAmount) ?? 0,
- isFixedRateMode: true,
- isReceiveAmount: true,
- );
- params['id'] = _lastUsedRateId;
- }
-
- if (_provider.isEmpty || _provider.first == null || _provider.first.toString().isEmpty) {
- ExchangeProviderLogger.logError(
- provider: description,
- function: 'createTrade',
- error: Exception('No available provider is enabled'),
- 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,
- 'params': params,
- },
- );
- throw ExchangeProviderResponseException('No available provider is enabled');
- }
-
- params['provider'] = _provider.first.toString();
-
- final uri = await _getUri(createTradePath, params);
- final response = await ProxyWrapper().get(clearnetUri: uri, headers: {'API-Key': apiKey});
-
- if (response.statusCode == 400) {
- final responseJSON = json.decode(response.body) as Map<String, dynamic>;
- final error = _safeString(responseJSON, 'error', 'Unknown error');
- final message = _safeString(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,
- 'params': params,
- 'url': uri.toString(),
- },
- );
-
- throw ExchangeProviderResponseException('${error}\n$message');
- }
-
- 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,
- 'params': params,
- 'url': uri.toString(),
- },
- );
- throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
- }
-
- final responseJSON = json.decode(response.body) as Map<String, dynamic>;
- final id = _safeString(responseJSON, 'trade_id');
- final inputAddress = _safeString(responseJSON, 'address_provider');
- final refundAddress = _safeString(responseJSON, 'refund_address');
- final status = _safeString(responseJSON, 'status');
- final payoutAddress = _safeString(responseJSON, 'address_user');
- final date = _safeString(responseJSON, 'date');
- final password = _safeString(responseJSON, 'password');
- final providerId = _safeString(responseJSON, 'id_provider');
- final providerName = _safeString(responseJSON, 'provider');
- final amount = _safeString(responseJSON, 'amount_from');
- final receiveAmount = _safeString(responseJSON, 'amount_to');
- final addressProviderMemo = _safeString(responseJSON, 'address_provider_memo');
-
- 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,
- 'url': uri.toString(),
- },
- responseData: {
- 'id': id,
- 'inputAddress': inputAddress,
- 'refundAddress': refundAddress,
- 'status': status,
- 'payoutAddress': payoutAddress,
- 'date': date,
- 'password': password,
- 'providerId': providerId,
- 'providerName': providerName,
- 'amount': amount,
- 'receiveAmount': receiveAmount,
- 'addressProviderMemo': addressProviderMemo,
- 'statusCode': response.statusCode,
- 'responseJSON': responseJSON,
- },
- );
-
- final amountToTrade = amount.isEmpty ? request.fromAmount : amount;
- final receiveAmountToTrade = receiveAmount.isEmpty ? request.toAmount : receiveAmount;
-
- return Trade(
- id: id,
- from: request.fromCurrency,
- to: request.toCurrency,
- provider: description,
- inputAddress: inputAddress,
- refundAddress: refundAddress,
- state: TradeState.deserialize(raw: status),
- password: password,
- providerId: providerId,
- providerName: providerName,
- createdAt: DateTime.tryParse(date)?.toLocal(),
- amount: amountToTrade,
- receiveAmount: receiveAmountToTrade,
- payoutAddress: payoutAddress,
- isSendAll: isSendAll,
- extraId: addressProviderMemo,
- toAddressExtraId: request.toAddressExtraId,
- );
- }
-
- @override
- Future<Trade> findTradeById({required String id}) async {
- final uri = await _getUri(tradePath, {'id': id});
- return ProxyWrapper()
- .get(clearnetUri: uri, headers: {'API-Key': apiKey}).then((response) async {
- if (response.statusCode != 200)
- throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
-
- final responseListJson = json.decode(response.body) as List;
- final responseJSON = responseListJson.first as Map<String, dynamic>;
- final id = _safeString(responseJSON, 'trade_id');
- final payoutAddress = _safeString(responseJSON, 'address_user');
- final refundAddress = _safeString(responseJSON, 'refund_address');
- final inputAddress = _safeString(responseJSON, 'address_provider');
- final fromAmount = responseJSON['amount_from']?.toString() ?? '0';
- final password = _safeString(responseJSON, 'password');
- final providerId = _safeString(responseJSON, 'id_provider');
- final providerName = _safeString(responseJSON, 'provider');
- final memoVal = _safeString(responseJSON, 'address_provider_memo');
- final addressProviderMemo = memoVal.isEmpty ? null : memoVal;
-
- final fromCurrency = _safeString(responseJSON, 'ticker_from');
- final fromNetworkVal = _safeString(responseJSON, 'network_from');
- final fromNetwork = fromNetworkVal.isEmpty ? null : fromNetworkVal;
- final _normalizedFromNetwork = _normalizeNetworkType(fromNetwork ?? '');
- final fromTag = _normalizedFromNetwork.isEmpty ||
- _normalizedFromNetwork == fromCurrency.toUpperCase() ||
- _normalizedFromNetwork == 'Mainnet'
- ? null
- : _normalizedFromNetwork;
-
- final from = CryptoCurrency.safeParseCurrencyFromString(fromCurrency, tag: fromTag);
-
- final toCurrency = _safeString(responseJSON, 'ticker_to');
- final networkToVal = _safeString(responseJSON, 'network_to');
- final networkTo = networkToVal.isEmpty ? null : networkToVal;
- final _normalizedToNetwork = _normalizeNetworkType(networkTo ?? '');
- final toTag = _normalizedToNetwork.isEmpty ||
- _normalizedToNetwork == toCurrency.toUpperCase() ||
- _normalizedFromNetwork == 'Mainnet'
- ? null
- : _normalizedToNetwork;
- final to = CryptoCurrency.safeParseCurrencyFromString(toCurrency, tag: toTag);
-
- return Trade(
- id: id,
- from: from,
- to: to,
- provider: description,
- inputAddress: inputAddress,
- refundAddress: refundAddress,
- createdAt: DateTime.tryParse(_safeString(responseJSON, 'date')),
- amount: fromAmount,
- state: TradeState.deserialize(raw: _safeString(responseJSON, 'status')),
- payoutAddress: payoutAddress,
- password: password,
- providerId: providerId,
- providerName: providerName,
- extraId: addressProviderMemo,
- );
- });
- }
-
- Future<List<TrocadorPartners>> fetchProviders() async {
- final uri = await _getUri(providersListPath, {'api_key': apiKey});
- final response = await ProxyWrapper().get(clearnetUri: uri);
-
- if (response.statusCode != 200)
- throw ExchangeProviderResponseCodeException('Unexpected http status: ${response.statusCode}', response.statusCode);
-
- final responseJSON = json.decode(response.body) as Map<String, dynamic>;
-
- final providersJsonList = responseJSON['list'] as List<dynamic>;
- final filteredProvidersList = providersJsonList
- .map((providerJson) => TrocadorPartners.fromJson(providerJson as Map<String, dynamic>))
- .where((provider) => provider.rating != 'D')
- .toList();
- filteredProvidersList.sort((a, b) => a.rating.compareTo(b.rating));
- return filteredProvidersList;
- }
-
- String _networkFor(CryptoCurrency currency) {
- switch (currency) {
- case CryptoCurrency.eth:
- return 'ERC20';
- case CryptoCurrency.maticpoly:
- return 'Mainnet';
- case CryptoCurrency.usdcpoly:
- case CryptoCurrency.usdtPoly:
- case CryptoCurrency.usdcEPoly:
- return 'MATIC';
- case CryptoCurrency.zec:
- return 'Mainnet';
- case CryptoCurrency.arb:
- return 'Mainnet';
- default:
- return currency.tag != null ? _normalizeTag(currency.tag!) : 'Mainnet';
- }
- }
-
- String _normalizeCurrency(CryptoCurrency currency) {
- switch (currency) {
- case CryptoCurrency.zec:
- return 'zec';
- case CryptoCurrency.usdcEPoly:
- return 'usdce';
- default:
- return currency.title.toLowerCase();
- }
- }
-
- String _normalizeTag(String tag) {
- if (tag.contains('ARB')) {
- return 'Arbitrum';
- }
-
- switch (tag) {
- case 'ETH':
- return 'ERC20';
- case 'TRX':
- return 'TRC20';
- case 'LN':
- return 'Lightning';
- case 'BSC':
- return 'BEP20';
- default:
- return tag.toLowerCase();
- }
- }
-
- String _normalizeNetworkType(String network) {
- return switch (network.toUpperCase()) {
- 'ERC20' => 'ETH',
- 'TRC20' => 'TRX',
- 'BEP20' => 'BSC',
- 'LIGHTNING' => 'LN',
- 'MATIC' => 'POL',
- _ => network,
- };
- }
-
- Future<Uri> _getUri(String path, Map<String, String> queryParams) async {
- final uri = Uri.http(onionApiAuthority, path, queryParams);
-
- if (useTorOnly) return uri;
-
- if (!CakeTor.instance!.started) return Uri.https(clearNetAuthority, path, queryParams);
-
- try {
- await ProxyWrapper().get(clearnetUri: uri);
-
- return uri;
- } catch (e) {
- return Uri.https(clearNetAuthority, path, queryParams);
- }
- }
-
- /// Safe string extraction from API response. Handles different data types.
- static String _safeString(Map<String, dynamic> m, String key, [String nullError = '']) {
- final v = m[key];
- if (v == null) return nullError;
- if (v is String) return v;
- return v.toString();
- }
-}
-
-class TrocadorPartners {
- final String name;
- final String rating;
- final double? insurance;
- final bool? enabledMarkup;
- final double? eta;
-
- TrocadorPartners({
- required this.name,
- required this.rating,
- required this.insurance,
- required this.enabledMarkup,
- required this.eta,
- });
-
- factory TrocadorPartners.fromJson(Map<String, dynamic> json) {
- return TrocadorPartners(
- name: json['name'] as String? ?? '',
- rating: json['rating'] as String? ?? 'N/A',
- insurance: json['insurance'] as double?,
- enabledMarkup: json['enabledmarkup'] as bool?,
- eta: json['eta'] as double?,
- );
- }
-}
### lib/exchange/provider/whynot/whynot_api_schema.dart
@@ -0,0 +1,339 @@
+// spec reference: https://api-doc.letsexchange.io/api-reference/openapi.json
+
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/exchange/utils/json_converters.dart";
+import "package:json_annotation/json_annotation.dart";
+
+part "whynot_api_schema.g.dart";
+
+class SafeBoolConverter implements JsonConverter<bool, Object> {
+ const SafeBoolConverter();
+
+ @override
+ bool fromJson(Object json) {
+ // letsexchange api docs say isFloat is a boolean
+ // the example response says isFloat: "true"
+ // a curl test showed isFloat: 1
+ // i ain't settling this
+ if (json is bool) {
+ return json;
+ }
+ if (json is int) {
+ return json == 1;
+ }
+ if (json is String) {
+ return json.toLowerCase() == "true";
+ }
+ return json != 0;
+ }
+
+ @override
+ Object toJson(bool value) => value;
+}
+
+// rate_id_expired_at comes back as the number 0 from /info and as a string of millis from
+// /info-revert, so read whatever turns up as a string
+class SafeStringConverter implements JsonConverter<String, Object> {
+ const SafeStringConverter();
+
+ @override
+ String fromJson(Object json) => json.toString();
+
+ @override
+ Object toJson(String value) => value;
+}
+
+// whynot dropped the created_at/expired_at shapes letsexchange had, so take seconds, a date string or nothing
+class SafeDateTimeConverter implements JsonConverter<DateTime?, Object?> {
+ const SafeDateTimeConverter();
+
+ @override
+ DateTime? fromJson(Object? json) => switch (json) {
+ final num seconds => DateTime.fromMillisecondsSinceEpoch((seconds * 1000).toInt(), isUtc: true),
+ final String value => switch (num.tryParse(value)) {
+ final seconds? => DateTime.fromMillisecondsSinceEpoch((seconds * 1000).toInt(), isUtc: true),
+ null => DateTime.tryParse(value),
+ },
+ _ => null,
+ };
+
+ @override
+ Object? toJson(DateTime? value) => value?.toIso8601String();
+}
+
+@JsonSerializable()
+class WhyNotInfoRequest {
+ const WhyNotInfoRequest({
+ required this.from,
+ required this.to,
+ required this.amount,
+ required this.affiliateId,
+ this.networkFrom,
+ this.networkTo,
+ this.float,
+ this.promocode,
+ this.partnerUserIp,
+ });
+
+ @JsonKey(name: "from")
+ final String from;
+ @JsonKey(name: "to")
+ final String to;
+ @JsonKey(name: "network_from", includeIfNull: false)
+ final String? networkFrom;
+ @JsonKey(name: "network_to", includeIfNull: false)
+ final String? networkTo;
+ @JsonKey(name: "amount")
+ final double amount;
+ @JsonKey(name: "affiliate_id")
+ final String affiliateId;
+ @JsonKey(name: "float", includeIfNull: false)
+ final bool? float;
+ @JsonKey(name: "promocode", includeIfNull: false)
+ final String? promocode;
+ @JsonKey(name: "partner_user_ip", includeIfNull: false)
+ final String? partnerUserIp;
+
+ Map<String, dynamic> toJson() => _$WhyNotInfoRequestToJson(this);
+}
+
+@JsonSerializable(createToJson: false)
+class WhyNotInfoResponse {
+ const WhyNotInfoResponse({
+ required this.depositMinAmount,
+ required this.depositMaxAmount,
+ required this.minAmount,
+ required this.maxAmount,
+ required this.amount,
+ this.fee,
+ this.rate,
+ this.profit,
+ this.withdrawalFee,
+ this.rateId,
+ this.rateIdExpiredAt,
+ });
+
+ factory WhyNotInfoResponse.fromJson(Map<String, dynamic> json) =>
+ _$WhyNotInfoResponseFromJson(json);
+
+ @JsonKey(name: "deposit_min_amount")
+ final String depositMinAmount;
+ @JsonKey(name: "deposit_max_amount")
+ final String depositMaxAmount;
+ @JsonKey(name: "min_amount")
+ final String minAmount;
+ @JsonKey(name: "max_amount")
+ final String maxAmount;
+ @JsonKey(name: "amount")
+ final String amount;
+ @JsonKey(name: "fee")
+ final String? fee;
+ @JsonKey(name: "rate")
+ final String? rate;
+ @JsonKey(name: "profit")
+ final String? profit;
+ @JsonKey(name: "withdrawal_fee")
+ final String? withdrawalFee;
+ @JsonKey(name: "rate_id")
+ final String? rateId;
+ @JsonKey(name: "rate_id_expired_at")
+ @SafeStringConverter()
+ final String? rateIdExpiredAt;
+}
+
+@JsonSerializable(createToJson: false)
+class WhyNotAmlSignal {
+ const WhyNotAmlSignal({
+ required this.signal,
+ required this.signalId,
+ required this.signalPercent,
+ required this.level,
+ });
+
+ factory WhyNotAmlSignal.fromJson(Map<String, dynamic> json) =>
+ _$WhyNotAmlSignalFromJson(json);
+
+ @JsonKey(name: "signal")
+ final String signal;
+ @JsonKey(name: "signalId")
+ final int signalId;
+ @JsonKey(name: "signalPercent")
+ final double signalPercent;
+ @JsonKey(name: "level")
+ final int level;
+}
+
+@JsonSerializable()
+class WhyNotCreateTransactionRequest {
+ const WhyNotCreateTransactionRequest({
+ required this.coinFrom,
+ required this.coinTo,
+ required this.withdrawal,
+ required this.withdrawalExtraId,
+ required this.affiliateId,
+ required this.float,
+ this.networkFrom,
+ this.networkTo,
+ this.depositAmount,
+ this.withdrawalAmount,
+ this.returnAddress,
+ this.returnExtraId,
+ this.rateId,
+ this.promocode,
+ this.email,
+ this.partnerUserIp,
+ });
+
+ @JsonKey(name: "coin_from")
+ final String coinFrom;
+ @JsonKey(name: "coin_to")
+ final String coinTo;
+ @JsonKey(name: "network_from", includeIfNull: false)
+ final String? networkFrom;
+ @JsonKey(name: "network_to", includeIfNull: false)
+ final String? networkTo;
+ @JsonKey(name: "deposit_amount", includeIfNull: false)
+ final String? depositAmount;
+ @JsonKey(name: "withdrawal_amount", includeIfNull: false)
+ final String? withdrawalAmount;
+ @JsonKey(name: "withdrawal")
+ final String withdrawal;
+ @JsonKey(name: "withdrawal_extra_id")
+ final String withdrawalExtraId;
+ @JsonKey(name: "return", includeIfNull: false)
+ final String? returnAddress;
+ @JsonKey(name: "return_extra_id", includeIfNull: false)
+ final String? returnExtraId;
+ @JsonKey(name: "rate_id", includeIfNull: false)
+ final String? rateId;
+ @JsonKey(name: "affiliate_id")
+ final String affiliateId;
+
+ // true = floating rate, false = fixed.
+ @JsonKey(name: "float")
+ final bool float;
+ @JsonKey(name: "promocode", includeIfNull: false)
+ final String? promocode;
+ @JsonKey(name: "email", includeIfNull: false)
+ final String? email;
+ @JsonKey(name: "partner_user_ip", includeIfNull: false)
+ final String? partnerUserIp;
+
+ Map<String, dynamic> toJson() => _$WhyNotCreateTransactionRequestToJson(this);
+}
+
+@JsonSerializable(createToJson: false)
+@TradeStateConverter()
+class WhyNotTransactionResponse {
+ const WhyNotTransactionResponse({
+ this.transactionId,
+ this.status,
+ this.coinFrom,
+ this.coinTo,
+ this.depositAmount,
+ this.withdrawalAmount,
+ this.deposit,
+ this.withdrawal,
+ this.coinFromName,
+ this.coinFromNetwork,
+ this.coinToName,
+ this.coinToNetwork,
+ this.realDepositAmount,
+ this.realWithdrawalAmount,
+ this.depositExtraId,
+ this.withdrawalExtraId,
+ this.rate,
+ this.fee,
+ this.hashIn,
+ this.hashOut,
+ this.returnAddress,
+ this.returnHash,
+ this.returnAmount,
+ this.returnExtraId,
+ this.isFloat,
+ this.coinFromExplorerUrl,
+ this.coinToExplorerUrl,
+ this.needConfirmations,
+ this.confirmations,
+ this.executionTime,
+ this.profit,
+ this.amlErrorSignals,
+ this.createdAt,
+ this.expiredAt,
+ });
+
+ factory WhyNotTransactionResponse.fromJson(Map<String, dynamic> json) =>
+ _$WhyNotTransactionResponseFromJson(json);
+
+ @JsonKey(name: "transaction_id")
+ final String? transactionId;
+ @JsonKey(name: "status")
+ final TradeState? status;
+ @JsonKey(name: "coin_from")
+ final String? coinFrom;
+ @JsonKey(name: "coin_from_name")
+ final String? coinFromName;
+ @JsonKey(name: "coin_from_network")
+ final String? coinFromNetwork;
+ @JsonKey(name: "coin_to")
+ final String? coinTo;
+ @JsonKey(name: "coin_to_name")
+ final String? coinToName;
+ @JsonKey(name: "coin_to_network")
+ final String? coinToNetwork;
+ @JsonKey(name: "deposit_amount")
+ final String? depositAmount;
+ @JsonKey(name: "withdrawal_amount")
+ final String? withdrawalAmount;
+ @JsonKey(name: "real_deposit_amount")
+ final String? realDepositAmount;
+ @JsonKey(name: "real_withdrawal_amount")
+ final String? realWithdrawalAmount;
+ @JsonKey(name: "deposit")
+ final String? deposit;
+ @JsonKey(name: "deposit_extra_id")
+ final String? depositExtraId;
+ @JsonKey(name: "withdrawal")
+ final String? withdrawal;
+ @JsonKey(name: "withdrawal_extra_id")
+ final String? withdrawalExtraId;
+ @JsonKey(name: "rate")
+ final String? rate;
+ @JsonKey(name: "fee")
+ final String? fee;
+ @JsonKey(name: "hash_in")
+ final String? hashIn;
+ @JsonKey(name: "hash_out")
+ final String? hashOut;
+ @JsonKey(name: "return")
+ final String? returnAddress;
+ @JsonKey(name: "return_hash")
+ final String? returnHash;
+ @JsonKey(name: "return_amount")
+ final String? returnAmount;
+ @JsonKey(name: "return_extra_id")
+ final String? returnExtraId;
+ @JsonKey(name: "is_float")
+ @SafeBoolConverter()
+ final bool? isFloat;
+ @JsonKey(name: "coin_from_explorer_url")
+ final String? coinFromExplorerUrl;
+ @JsonKey(name: "coin_to_explorer_url")
+ final String? coinToExplorerUrl;
+ @JsonKey(name: "need_confirmations")
+ final int? needConfirmations;
+ @JsonKey(name: "confirmations")
+ final int? confirmations;
+ @JsonKey(name: "execution_time")
+ final double? executionTime;
+ @JsonKey(name: "profit")
+ final double? profit;
+ @JsonKey(name: "aml_error_signals")
+ final List<WhyNotAmlSignal>? amlErrorSignals;
+ @JsonKey(name: "created_at")
+ @SafeDateTimeConverter()
+ final DateTime? createdAt;
+ @JsonKey(name: "expired_at")
+ @SafeDateTimeConverter()
+ final DateTime? expiredAt;
+}
### lib/exchange/provider/whynot/whynot_exchange_provider.dart
@@ -0,0 +1,256 @@
+import "dart:convert";
+
+import "package:cake_wallet/.secrets.g.dart" as secrets;
+import "package:cake_wallet/exchange/exchange_provider_description.dart";
+import "package:cake_wallet/exchange/provider/exchange_provider.dart";
+import "package:cake_wallet/exchange/provider/whynot/whynot_api_schema.dart";
+import "package:cake_wallet/exchange/rate_request.dart";
+import "package:cake_wallet/exchange/trade.dart";
+import "package:cake_wallet/exchange/trade_request.dart";
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/exchange_limits.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/provider_rate.dart";
+import "package:cw_core/amount/exchange_rate.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/crypto_currency.dart";
+
+class WhyNotExchangeProvider extends ExchangeProvider {
+ WhyNotExchangeProvider({super.proxyWrapper});
+
+ static const apiKey = secrets.whyNotBearerToken;
+ static const _baseUrl = "api.y-not.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.whyNotAffiliateId;
+
+ @override
+ bool get supportsFixedRate => true;
+
+ @override
+ ExchangeProviderDescription get description => ExchangeProviderDescription.whyNot;
+
+ @override
+ Future<ExchangeLimits> fetchLimits({
+ required CryptoCurrency from,
+ required CryptoCurrency to,
+ required bool isFixedRateMode,
+ }) async {
+ final params = WhyNotInfoRequest(
+ float: !isFixedRateMode,
+ from: from.symbol,
+ to: to.title,
+ networkFrom: _getNetworkType(from),
+ networkTo: _getNetworkType(to),
+ amount: 1,
+ affiliateId: _affiliateId,
+ );
+
+ final responseData = await _getInfo(params, isFixedRateMode);
+
+ return ExchangeLimits(
+ min: Money.safeParse(responseData.depositMinAmount, from),
+ max: Money.safeParse(responseData.depositMaxAmount, from),
+ );
+ }
+
+ @override
+ Future<ProviderRate> fetchRate(RateRequest request) async {
+
+ final params = WhyNotInfoRequest(
+ float: request is FloatingRateRequest,
+ from: request.depositCurrency.symbol,
+ to: request.payoutCurrency.title,
+ networkFrom: _getNetworkType(request.depositCurrency),
+ networkTo: _getNetworkType(request.payoutCurrency),
+ amount: double.parse(request.amount.toString()),
+ affiliateId: _affiliateId,
+ );
+
+ final responseData = await _getInfo(params, request is FixedRateRequest);
+
+ return ProviderRate(
+ provider: description,
+ rate: switch (request) {
+ FloatingRateRequest(:final depositAmount) => ExchangeRate.fromAmounts(
+ depositAmount,
+ Money.safeParse(responseData.amount, request.payoutCurrency),
+ ),
+ FixedRateRequest(:final payoutAmount) => ExchangeRate.fromAmounts(
+ Money.safeParse(responseData.amount, request.depositCurrency),
+ payoutAmount,
+ ),
+ },
+ limits: ExchangeLimits(
+ min: Money.safeParse(responseData.depositMinAmount, request.depositCurrency),
+ max: Money.safeParse(responseData.depositMaxAmount, request.depositCurrency),
+ ),
+ );
+ }
+
+ @override
+ Future<Trade> createTrade({required TradeRequest request}) async {
+ final networkFrom = _getNetworkType(request.depositCurrency);
+ final networkTo = _getNetworkType(request.payoutCurrency);
+
+ final params = WhyNotInfoRequest(
+ from: request.depositCurrency.title,
+ to: request.payoutCurrency.title,
+ networkFrom: networkFrom,
+ networkTo: networkTo,
+ amount: double.parse(
+ (request.isFixedRate ? request.payoutAmount : request.depositAmount).toString(),
+ ),
+ affiliateId: _affiliateId,
+ float: !request.isFixedRate,
+ );
+
+ final responseInfoJSON = await _getInfo(params, request.isFixedRate);
+
+ final withdrawalAddress = _normalizeBchAddress(request.payoutAddress);
+ final returnAddress = _normalizeBchAddress(request.refundAddress);
+
+ final tradeParams = WhyNotCreateTransactionRequest(
+ coinFrom: request.depositCurrency.title,
+ coinTo: request.payoutCurrency.title,
+ depositAmount: request.isFixedRate ? null : request.depositAmount.toString(),
+ withdrawalAmount: request.isFixedRate ? request.payoutAmount.toString() : null,
+ withdrawal: withdrawalAddress,
+ withdrawalExtraId: request.toAddressExtraId ?? "",
+ returnAddress: returnAddress,
+ rateId: responseInfoJSON.rateId,
+ networkFrom: networkFrom,
+ networkTo: networkTo,
+ affiliateId: _affiliateId,
+ float: !request.isFixedRate,
+ );
+
+ final headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ "Authorization": apiKey,
+ };
+
+ final uri = Uri.https(
+ _baseUrl,
+ request.isFixedRate ? _createTransactionRevertPath : _createTransactionPath,
+ );
+ final response = await proxyWrapper.post(
+ clearnetUri: uri,
+ headers: headers,
+ body: json.encode(tradeParams.toJson()),
+ );
+
+ if (response.statusCode != 200) {
+ throw Exception("WhyNot create trade failed: ${response.body}");
+ }
+ final responseData = WhyNotTransactionResponse.fromJson(
+ json.decode(response.body) as Map<String, dynamic>,
+ );
+
+ // the null checks are because api spec shows EVERY FIELD as nullable
+ return Trade(
+ id: responseData.transactionId!,
+ provider: description,
+ payoutAddress: responseData.withdrawal!,
+ fundingAddress: responseData.deposit!,
+ refundAddress: request.refundAddress,
+ payoutAmount: Money.safeParse(responseData.withdrawalAmount, request.payoutAmount.currency),
+ depositAmount: Money.safeParse(responseData.depositAmount, request.depositAmount.currency),
+ state: responseData.status!,
+ createdAt: DateTime.now(),
+ expiredAt: responseData.expiredAt,
+ extraId: responseData.depositExtraId,
+ toAddressExtraId: request.toAddressExtraId,
+ );
+ }
+
+ @override
+ Future<Trade> updateTrade(Trade trade) async {
+ final headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ "Authorization": apiKey,
+ };
+
+ final url = Uri.https(_baseUrl, "$_getTransactionPath/${trade.id}");
+ final response = await proxyWrapper.get(clearnetUri: url, headers: headers);
+
+ if (response.statusCode != 200) {
+ throw Exception("WhyNot fetch trade failed: ${response.body}");
+ }
+ final responseData = WhyNotTransactionResponse.fromJson(
+ json.decode(response.body) as Map<String, dynamic>,
+ );
+
+ return trade.copyWith(
+ payoutAddress: responseData.withdrawal,
+ refundAddress: responseData.returnAddress,
+ state: responseData.status,
+ isRefund: responseData.status == TradeState.refund,
+ extraId: responseData.depositExtraId,
+ depositAmount: Money.safeParse(
+ responseData.depositAmount,
+ trade.depositCurrency
+ ),
+ payoutAmount: Money.safeParse(
+ responseData.withdrawalAmount,
+ trade.payoutCurrency
+ ),
+ fundingAddress: responseData.deposit,
+ );
+ }
+
+ Future<WhyNotInfoResponse> _getInfo(
+ WhyNotInfoRequest params,
+ bool isFixedRateMode,
+ ) async {
+ final headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ "Authorization": apiKey,
+ };
+
+ final uri = Uri.https(_baseUrl, isFixedRateMode ? _infoRevertPath : _infoPath);
+ final response = await proxyWrapper.post(
+ clearnetUri: uri,
+ headers: headers,
+ body: json.encode(params.toJson()),
+ );
+
+ if (response.statusCode != 200) {
+ throw Exception("WhyNot fetch info failed: ${response.body}");
+ }
+ return WhyNotInfoResponse.fromJson(json.decode(response.body) as Map<String, dynamic>);
+ }
+
+ 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 _normalizeTitleToNetwork(String title) => switch (title.toUpperCase()) {
+ "ARB" => "ARBITRUM",
+ _ => title,
+ };
+
+ String _normalizeBchAddress(String address) =>
+ address.startsWith("bitcoincash:") ? address.substring(12) : address;
+}
### lib/exchange/provider/whynot_exchange_provider.dart
@@ -1,446 +0,0 @@
-import 'dart:convert';
-import 'dart:developer';
-
-import 'package:cake_wallet/.secrets.g.dart' as secrets;
-import "package:cake_wallet/exchange/exchange_exceptions.dart";
-import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/limits.dart';
-import 'package:cake_wallet/exchange/trade.dart';
-import 'package:cake_wallet/exchange/trade_not_created_exception.dart';
-import 'package:cake_wallet/exchange/trade_request.dart';
-import 'package:cake_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:cake_wallet/utils/exchange_provider_logger.dart';
-
-class WhyNotExchangeProvider extends ExchangeProvider {
- WhyNotExchangeProvider();
-
- static const apiKey = secrets.whyNotBearerToken;
- static const _baseUrl = 'api.y-not.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.whyNotAffiliateId;
-
- @override
- String get title => 'WhyNot';
-
- @override
- bool get isAvailable => true;
-
- @override
- bool get isEnabled => true;
-
- @override
- bool get supportsFixedRate => true;
-
- @override
- ExchangeProviderDescription get description => ExchangeProviderDescription.whyNot;
-
- @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 networkFrom = _getNetworkType(curFrom);
- final networkTo = _getNetworkType(curTo);
-
- try {
- final params = {
- 'from': curFrom.title,
- 'to': curTo.title,
- if (networkFrom != null) 'network_from': networkFrom,
- if (networkTo != null) 'network_to': networkTo,
- 'amount': '1',
- 'affiliate_id': _affiliateId,
- 'float': !isFixedRateMode,
- };
-
- 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 ExchangeProviderResponseException('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,
- };
-
- 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,
- };
-
- 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': request.toAddressExtraId,
- 'return': returnAddress,
- if (rateId != null) 'rate_id': rateId,
- if (networkFrom != null) 'network_from': networkFrom,
- if (networkTo != null) 'network_to': networkTo,
- 'affiliate_id': _affiliateId,
- 'float': !isFixedRateMode,
- };
-
- 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('WhyNot 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 TradeNotCreatedException(description, description: 'WhyNot 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;
- 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,
- '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,
- toAddressExtraId: request.toAddressExtraId,
- );
- } 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 ExchangeProviderResponseCodeException('WhyNot fetch trade failed: ${response.body}', response.statusCode);
- }
- 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, Object> 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 ExchangeProviderResponseCodeException('WhyNot fetch info failed: ${response.body}', response.statusCode);
- }
- return json.decode(response.body) as Map<String, dynamic>;
- } catch (e) {
- throw ExchangeProviderResponseException('WhyNot 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;
-}
### lib/exchange/provider/xoswap/xoswap_api_schema.dart
@@ -0,0 +1,274 @@
+// spec reference: https://www.xoswap.com/docs/v3
+
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/exchange/utils/json_converters.dart";
+import "package:cake_wallet/exchange/utils/provider_api.dart";
+import "package:json_annotation/json_annotation.dart";
+
+part "xoswap_api_schema.g.dart";
+
+@JsonSerializable(createToJson: false)
+class XOSwapErrorResponse {
+ const XOSwapErrorResponse({this.code, this.error, this.message, this.details});
+
+ factory XOSwapErrorResponse.fromJson(Map<String, dynamic> json) =>
+ _$XOSwapErrorResponseFromJson(json);
+
+ @JsonKey(name: "code")
+ final String? code;
+ @JsonKey(name: "error")
+ final String? error;
+ @JsonKey(name: "message")
+ final String? message;
+ @JsonKey(name: "details")
+ final String? details;
+}
+
+// /v3/pairs/{id}/rates sends amount.value as a number while
+// /v3/orders sends it as a string, so a plain double throws on every order response
+class XOSwapAmountValueConverter implements JsonConverter<double, Object> {
+ const XOSwapAmountValueConverter();
+
+ @override
+ double fromJson(Object json) {
+ if (json is num) {
+ return json.toDouble();
+ }
+ if (json is String) {
+ return double.parse(json);
+ }
+ throw ArgumentError("unexpected XOSwap amount value: $json");
+ }
+
+ @override
+ Object toJson(double value) => value;
+}
+
+@JsonSerializable(createToJson: false)
+class XOSwapAmount {
+ const XOSwapAmount({required this.value, this.assetId});
+
+ factory XOSwapAmount.fromJson(Map<String, dynamic> json) => _$XOSwapAmountFromJson(json);
+
+ @JsonKey(name: "value")
+ @XOSwapAmountValueConverter()
+ final double value;
+
+ @JsonKey(name: "assetId")
+ final String? assetId;
+}
+
+
+@JsonSerializable()
+class XOSwapAssetsRequest extends ApiRequest<List<XOSwapAsset>> {
+ const XOSwapAssetsRequest({this.networks, this.query});
+
+ @JsonKey(name: "networks", includeIfNull: false)
+ final String? networks;
+
+ @JsonKey(name: "query", includeIfNull: false)
+ final String? query;
+
+ @override
+ String path() => "/v3/assets";
+
+ @override
+ Map<String, dynamic> toJson() => _$XOSwapAssetsRequestToJson(this);
+
+ @override
+ List<XOSwapAsset> decode(Object json) => (json as List<dynamic>)
+ .map((item) => XOSwapAsset.fromJson(item as Map<String, dynamic>))
+ .toList();
+}
+
+@JsonSerializable(createToJson: false)
+class XOSwapAsset {
+ const XOSwapAsset({required this.id, this.symbol, this.meta});
+
+ factory XOSwapAsset.fromJson(Map<String, dynamic> json) => _$XOSwapAssetFromJson(json);
+
+ @JsonKey(name: "id")
+ final String id;
+
+ @JsonKey(name: "symbol")
+ final String? symbol;
+
+ @JsonKey(name: "meta")
+ final Map<String, dynamic>? meta;
+}
+
+
+@JsonSerializable(createToJson: false)
+class XOSwapRate {
+ const XOSwapRate({
+ required this.amount,
+ required this.minerFee,
+ required this.min,
+ required this.max,
+ required this.expiry,
+ });
+
+ factory XOSwapRate.fromJson(Map<String, dynamic> json) => _$XOSwapRateFromJson(json);
+
+ @JsonKey(name: "amount")
+ final XOSwapAmount amount;
+ @JsonKey(name: "minerFee")
+ final XOSwapAmount minerFee;
+ @JsonKey(name: "min")
+ final XOSwapAmount min;
+ @JsonKey(name: "max")
+ final XOSwapAmount max;
+ @JsonKey(name: "expiry")
+ @MillisDateTimeConverter()
+ final DateTime expiry;
+}
+
+
+class XOSwapPairRatesRequest extends ApiRequest<List<XOSwapRate>> {
+ const XOSwapPairRatesRequest({required this.pairId});
+
+ final String pairId;
+
+ @override
+ String path() => "/v3/pairs/$pairId/rates";
+
+ @override
+ Map<String, dynamic> toJson() => const {};
+
+ @override
+ List<XOSwapRate> decode(Object json) => (json as List<dynamic>)
+ .map((item) => XOSwapRate.fromJson(item as Map<String, dynamic>))
+ .toList();
+}
+
+@JsonSerializable()
+class XOSwapCreateOrderRequest extends ApiRequest<XOSwapOrder> {
+ const XOSwapCreateOrderRequest({
+ required this.pairId,
+ required this.fromAmount,
+ required this.fromAddress,
+ required this.toAmount,
+ required this.toAddress,
+ this.fromAddressTag,
+ this.toAddressTag,
+ this.slippage,
+ }) : super.post();
+
+ @JsonKey(name: "pairId")
+ final String pairId;
+
+ @JsonKey(name: "fromAmount")
+ final String fromAmount;
+
+ @JsonKey(name: "toAmount")
+ final String toAmount;
+
+ @JsonKey(name: "fromAddress")
+ final String fromAddress;
+ @JsonKey(name: "fromAddressTag", includeIfNull: false)
+ final String? fromAddressTag;
+
+ @JsonKey(name: "toAddress")
+ final String toAddress;
+ @JsonKey(name: "toAddressTag", includeIfNull: false)
+ final String? toAddressTag;
+
+ @JsonKey(name: "slippage", includeIfNull: false)
+ final double? slippage;
+
+ @override
+ String path() => "/v3/orders";
+
+ @override
+ Map<String, dynamic> toJson() => _$XOSwapCreateOrderRequestToJson(this);
+
+ @override
+ XOSwapOrder decode(Object json) => XOSwapOrder.fromJson(json as Map<String, dynamic>);
+}
+
+class XOSwapOrderRequest extends ApiRequest<XOSwapOrder> {
+ const XOSwapOrderRequest({required this.id});
+
+ final String id;
+
+ @override
+ String path() => "/v3/orders/$id";
+
+ @override
+ Map<String, dynamic> toJson() => const {};
+
+ @override
+ XOSwapOrder decode(Object json) => XOSwapOrder.fromJson(json as Map<String, dynamic>);
+}
+
+@JsonSerializable(createToJson: false)
+@TradeStateConverter()
+class XOSwapOrder {
+ const XOSwapOrder({
+ required this.id,
+ required this.pairId,
+ required this.status,
+ required this.amount,
+ required this.payInAddress,
+ required this.fromAddress,
+ required this.toAddress,
+ required this.createdAt,
+ this.toAmount,
+ this.payInAddressTag,
+ this.fromAddressTag,
+ this.toAddressTag,
+ this.fromTransactionId,
+ this.toTransactionId,
+ this.providerOrderId,
+ this.rateId,
+ this.message,
+ this.updatedAt,
+ this.extraFeatures,
+ });
+
+ factory XOSwapOrder.fromJson(Map<String, dynamic> json) => _$XOSwapOrderFromJson(json);
+
+ @JsonKey(name: "id")
+ final String id;
+ @JsonKey(name: "pairId")
+ final String pairId;
+
+ @JsonKey(name: "status")
+ final TradeState status;
+
+ @JsonKey(name: "amount")
+ final XOSwapAmount amount;
+ @JsonKey(name: "toAmount")
+ final XOSwapAmount? toAmount;
+
+ @JsonKey(name: "payInAddress")
+ final String payInAddress;
+ @JsonKey(name: "payInAddressTag")
+ final String? payInAddressTag;
+ @JsonKey(name: "fromAddress")
+ final String fromAddress;
+ @JsonKey(name: "fromAddressTag")
+ final String? fromAddressTag;
+ @JsonKey(name: "toAddress")
+ final String toAddress;
+ @JsonKey(name: "toAddressTag")
+ final String? toAddressTag;
+ @JsonKey(name: "fromTransactionId")
+ final String? fromTransactionId;
+ @JsonKey(name: "toTransactionId")
+ final String? toTransactionId;
+ @JsonKey(name: "providerOrderId")
+ final String? providerOrderId;
+ @JsonKey(name: "rateId")
+ final String? rateId;
+ @JsonKey(name: "message")
+ final String? message;
+ @JsonKey(name: "createdAt")
+ final DateTime createdAt;
+ @JsonKey(name: "updatedAt")
+ final DateTime? updatedAt;
+
+ // don't you love when apis just don't document some part of the json
+ @JsonKey(name: "extraFeatures")
+ final Map<String, dynamic>? extraFeatures;
+}
### lib/exchange/provider/xoswap/xoswap_exchange_provider.dart
@@ -0,0 +1,270 @@
+import "package:cake_wallet/core/utilities.dart";
+import "package:cake_wallet/exchange/exchange_provider_description.dart";
+import "package:cake_wallet/exchange/provider/exchange_provider.dart";
+import "package:cake_wallet/exchange/provider/xoswap/xoswap_api_schema.dart";
+import "package:cake_wallet/exchange/rate_request.dart";
+import "package:cake_wallet/exchange/trade.dart";
+import "package:cake_wallet/exchange/trade_not_created_exception.dart";
+import "package:cake_wallet/exchange/trade_request.dart";
+import "package:cake_wallet/exchange/utils/provider_api.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/exchange_limits.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/provider_rate.dart";
+import "package:cake_wallet/utils/package_info.dart";
+import "package:collection/collection.dart" show IterableDoubleExtension;
+import "package:cw_core/amount/exchange_rate.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/amount/money_double.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/utils/print_verbose.dart";
+
+class XOSwapExchangeProvider extends ExchangeProvider {
+ XOSwapExchangeProvider({super.proxyWrapper}) {
+ _addAppVersionHeader();
+ }
+
+ Future<void> _addAppVersionHeader() async {
+ try {
+ final packageInfo = await PackageInfo.fromPlatform();
+ final currentVersion = packageInfo.version;
+ _headers["App-Version"] = currentVersion;
+ } catch (_) {}
+ }
+
+ static const _apiAuthority = "exchange.exodus.io";
+
+ static final _headers = {"App-Name": "cake-labs"};
+
+ late final _api = ProviderApi(
+ proxyWrapper,
+ authority: _apiAuthority,
+ headers: _headers,
+ errorMessage: (json) => (json["message"] ?? json["error"])?.toString(),
+ );
+
+ 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",
+ ];
+
+ @override
+ bool get supportsFixedRate => true;
+
+ @override
+ ExchangeProviderDescription get description => ExchangeProviderDescription.xoSwap;
+
+ 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 assets = await _api.send(
+ XOSwapAssetsRequest(networks: normalizedNetwork, query: currency.title),
+ );
+
+ final asset = assets.firstWhereOrNull(
+ (asset) => removeNonAlphanumeric(asset.symbol.toString()) == currency.title,
+ );
+
+ return asset?.id;
+ } catch (e) {
+ printV(e.toString());
+ return null;
+ }
+ }
+
+ String removeNonAlphanumeric(String str) =>
+ str.toUpperCase().replaceAll(RegExp(r"[^A-Z0-9]"), "");
+
+ Future<List<XOSwapRate>> 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 [];
+ }
+ return await _api.send(XOSwapPairRatesRequest(pairId: "${curFrom}_$curTo"));
+ } catch (e) {
+ printV(e.toString());
+ return [];
+ }
+ }
+
+ ExchangeLimits _exchangeLimitsFromRateList(CryptoCurrency from, List<XOSwapRate> rates) => ExchangeLimits(
+ min: Money.trySafeParse(rates.map((rate) => rate.min.value).min, from),
+ max: Money.trySafeParse(rates.map((rate) => rate.max.value).max, from),
+ );
+
+
+ @override
+ Future<ExchangeLimits> fetchLimits({
+ required CryptoCurrency from,
+ required CryptoCurrency to,
+ required bool isFixedRateMode,
+ }) async {
+ final rates = await getRatesForPair(from: from, to: to);
+ if (rates.isEmpty) {
+ throw Exception("No rates found for $from to $to");
+ }
+
+ return _exchangeLimitsFromRateList(from, rates);
+ }
+
+ @override
+ Future<ProviderRate> fetchRate(RateRequest request) async {
+ final rates = await getRatesForPair(from: request.depositCurrency, to: request.payoutCurrency);
+ if (rates.isEmpty) {
+ throw Exception("no rate from xoswap");
+ }
+
+ return ProviderRate(
+ provider: description,
+ rate: switch (request) {
+ FloatingRateRequest(:final depositAmount) => ExchangeRate.fromAmounts(
+ depositAmount,
+ _bestPayout(rates, depositAmount).toMoney(request.payoutCurrency),
+ ),
+ FixedRateRequest(:final payoutAmount) => ExchangeRate.fromAmounts(
+ _bestDeposit(rates, payoutAmount).toMoney(request.depositCurrency),
+ payoutAmount,
+ ),
+ },
+ limits: _exchangeLimitsFromRateList(request.depositCurrency, rates),
+ );
+ }
+
+ double _bestPayout(List<XOSwapRate> rates, Money depositAmount) {
+ final deposit = double.parse(depositAmount.toString());
+ final payouts = [
+ for (final rate in rates)
+ if (deposit >= rate.min.value && deposit <= rate.max.value)
+ deposit * rate.amount.value - rate.minerFee.value,
+ ].where((payout) => payout > 0);
+
+ if (payouts.isEmpty) {
+ throw Exception("no xoswap rate accepts a deposit of $depositAmount");
+ }
+ return payouts.max;
+ }
+
+ double _bestDeposit(List<XOSwapRate> rates, Money payoutAmount) {
+ final payout = double.parse(payoutAmount.toString());
+ final deposits = [
+ for (final rate in rates)
+ if ((payout + rate.minerFee.value) / rate.amount.value case final deposit
+ when deposit >= rate.min.value && deposit <= rate.max.value)
+ deposit,
+ ];
+
+ if (deposits.isEmpty) {
+ throw Exception("no xoswap rate can pay out $payoutAmount");
+ }
+ return deposits.min;
+ }
+
+ @override
+ Future<Trade> createTrade({
+ required TradeRequest request,
+ }) async {
+ final curFrom = await _getAssets(request.depositCurrency);
+ final curTo = await _getAssets(request.payoutCurrency);
+
+ if (curFrom == null || curTo == null) {
+ throw TradeNotCreatedException(description);
+ }
+
+ final pairId = "${curFrom}_$curTo";
+
+ final responseData = await _api.send(XOSwapCreateOrderRequest(pairId: pairId,
+ fromAmount: request.depositAmount.toString(),
+ fromAddress: request.refundAddress,
+ toAmount: request.payoutAmount.toString(),
+ toAddress: request.payoutAddress,
+ toAddressTag: request.toAddressExtraId
+ ));
+
+
+ return Trade(
+ depositAmount: Money.safeParse(responseData.amount.value, request.depositCurrency),
+ payoutAmount: Money.safeParse(responseData.toAmount!.value, request.payoutCurrency),
+ id: responseData.id,
+ provider: description,
+ refundAddress: responseData.fromAddress,
+ state: responseData.status,
+ createdAt: responseData.createdAt,
+ payoutAddress: responseData.toAddress,
+ fundingAddress: responseData.payInAddress,
+ extraId: responseData.payInAddressTag,
+ toAddressExtraId: request.toAddressExtraId,
+ );
+ }
+
+ @override
+ Future<Trade> updateTrade(Trade trade) async {
+ final responseData = await _api.send(
+ XOSwapOrderRequest(id: trade.id),
+ mapError: (e) => switch (e.json) {
+ {"code": "NOT_FOUND"} => Exception("Trade not found"),
+ _ => null,
+ },
+ );
+
+
+ return trade.copyWith(
+ refundAddress: responseData.fromAddress,
+ fundingAddress: responseData.payInAddress,
+ depositAmount: Money.safeParse(responseData.amount.value, trade.depositCurrency),
+ payoutAmount: responseData.toAmount?.value != null ? Money.safeParse(
+ responseData.toAmount!.value, trade.payoutCurrency) : null,
+ state: responseData.status,
+ createdAt: responseData.createdAt,
+ payoutAddress: responseData.toAddress,
+ extraId: responseData.payInAddressTag,
+ );
+ }
+
+}
### lib/exchange/provider/xoswap_exchange_provider.dart
@@ -1,571 +0,0 @@
-import 'dart:convert';
-
-import "package:cake_wallet/exchange/exchange_exceptions.dart";
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/limits.dart';
-import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
-import 'package:cake_wallet/exchange/trade.dart';
-import 'package:cake_wallet/exchange/trade_not_created_exception.dart';
-import 'package:cake_wallet/exchange/trade_request.dart';
-import 'package:cake_wallet/exchange/trade_state.dart';
-import 'package:cake_wallet/utils/package_info.dart';
-import 'package:cw_core/crypto_currency.dart';
-import "package:cw_core/exceptions/cake_exception.dart";
-import 'package:cw_core/utils/print_verbose.dart';
-import 'package:cw_core/utils/proxy_wrapper.dart';
-import 'package:cake_wallet/utils/exchange_provider_logger.dart';
-
-class XOSwapExchangeProvider extends ExchangeProvider {
- XOSwapExchangeProvider() {
- _addAppVersionHeader();
- }
-
- void _addAppVersionHeader() async {
- try {
- final packageInfo = await PackageInfo.fromPlatform();
- final currentVersion = packageInfo.version;
- _headers['App-Version'] = currentVersion;
- } catch (_) {}
- }
-
- 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 ExchangeProviderResponseCodeException('Failed to fetch assets for ${currency.title} on ${currency.tag}', response.statusCode);
- }
-
- 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 BadCurrencyPairException('No rates found for $from to $to', from, 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 ExchangeProviderResponseException('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,
- if (request.toAddressExtraId.isNotEmpty) 'toAddressTag': request.toAddressExtraId,
- '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 ExchangeProviderResponseException('$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 ExchangeProviderResponseException('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,
- toAddressExtraId: request.toAddressExtraId,
- );
- } 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 TradeNotFoundException(id, description: 'Trade not found', provider: description);
- }
- final error = responseJSON['error'] ?? 'Unknown error';
- final message = responseJSON['message'] ?? responseJSON['details'] ?? '';
- throw ExchangeProviderResponseException('$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 ExchangeProviderResponseException('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;
- }
-}
### lib/exchange/rate_request.dart
@@ -0,0 +1,61 @@
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/crypto_currency.dart";
+
+sealed class RateRequest {
+ const RateRequest();
+
+ CryptoCurrency get depositCurrency;
+
+ CryptoCurrency get payoutCurrency;
+
+ Money get amount;
+
+ bool isSameQuery(RateRequest other) =>
+ (this is FixedRateRequest) == (other is FixedRateRequest) &&
+ depositCurrency == other.depositCurrency &&
+ payoutCurrency == other.payoutCurrency;
+
+ @override
+ bool operator ==(Object other) =>
+ other is RateRequest && isSameQuery(other) && amount == other.amount;
+
+ @override
+ int get hashCode => Object.hash(this is FixedRateRequest, depositCurrency, payoutCurrency, amount);
+
+ Map<String, dynamic> toJson() => {
+ "depositCurrency": depositCurrency.serialized,
+ "payoutCurrency": payoutCurrency.serialized,
+ "amount": amount.serialized,
+ "isFixedRate": this is FixedRateRequest,
+ };
+}
+
+final class FloatingRateRequest extends RateRequest {
+ const FloatingRateRequest({required this.depositAmount, required this.payoutCurrency});
+
+ final Money depositAmount;
+
+ @override
+ final CryptoCurrency payoutCurrency;
+
+ @override
+ CryptoCurrency get depositCurrency => depositAmount.currency as CryptoCurrency;
+
+ @override
+ Money get amount => depositAmount;
+}
+
+final class FixedRateRequest extends RateRequest {
+ const FixedRateRequest({required this.depositCurrency, required this.payoutAmount});
+
+ @override
+ final CryptoCurrency depositCurrency;
+
+ final Money payoutAmount;
+
+ @override
+ CryptoCurrency get payoutCurrency => payoutAmount.currency as CryptoCurrency;
+
+ @override
+ Money get amount => payoutAmount;
+}
### lib/exchange/trade.dart
@@ -1,325 +1,263 @@
-import 'dart:async';
-
-import 'package:cake_wallet/evm/evm.dart';
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/trade_state.dart';
-import 'package:cw_core/crypto_currency.dart';
-import 'package:cw_core/db/sqlite.dart';
-import 'package:cw_core/format_amount.dart';
-import 'package:cw_core/generate_name.dart';
-import 'package:sqflite/sqflite.dart';
+import "dart:async";
+
+import "package:cake_wallet/evm/evm.dart";
+import "package:cake_wallet/exchange/exchange_provider_description.dart";
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cake_wallet/new-ui/viewmodels/swap/util/uri_helper.dart";
+import "package:cake_wallet/utils/currency_from_serialized.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/db/sqlite.dart";
+import "package:cw_core/erc20_token.dart";
+import "package:cw_core/payment_uris.dart";
+import "package:cw_core/utils/print_verbose.dart";
+import "package:sqflite/sqflite.dart";
class Trade {
Trade({
- this.internalId = 0,
- required this.id,
- required this.amount,
- ExchangeProviderDescription? provider,
- this.from,
- this.to,
- TradeState? state,
- this.receiveAmount,
+ required this.state,
+ required this.depositAmount,
+ required this.payoutAmount,
+ required this.fundingAddress,
+ this.providerName,
+ required this.id, required this.provider, required this.payoutAddress, required this.refundAddress,
this.createdAt,
this.expiredAt,
- this.inputAddress,
+ this.accountIndex = 0,
this.extraId,
this.outputTransaction,
- this.refundAddress,
this.walletId,
- this.payoutAddress,
this.toAddressExtraId,
this.password,
this.providerId,
- this.providerName,
- this.fromWalletAddress,
this.memo,
- this.fee,
this.txId,
this.isRefund,
- this.isSendAll,
- this.router,
- // The following fields are used for SwapXyz trades only
- this.needToRegisterInSwapXyz,
- this.sourceTokenAddress,
- this.sourceTokenDecimals,
- this.routerData,
- this.routerValue,
- this.routerChainId,
- this.sourceTokenAmountRaw,
- this.requiresTokenApproval,
- this.chainId,
- }) {
- if (provider != null) providerRaw = provider.raw;
- if (state != null) stateRaw = state.raw;
- }
+ });
- static const tableName = 'Trade';
- static const selfIdColumn = 'tradeId';
+ static const tableName = "Trade";
+ static const selfIdColumn = "tradeId";
- static const boxName = 'Trades';
- static const boxKey = 'tradesBoxKey';
+ static const boxName = "Trades";
+ static const boxKey = "tradesBoxKey";
static final StreamController<void> onChanged = StreamController<void>.broadcast();
- int internalId;
-
- String id;
-
- int providerRaw = 0;
-
- ExchangeProviderDescription get provider =>
- ExchangeProviderDescription.deserialize(raw: providerRaw);
-
- CryptoCurrency? from;
- CryptoCurrency? to;
-
- String stateRaw = '';
-
- TradeState get state => TradeState.deserialize(raw: stateRaw);
-
- DateTime? createdAt;
- DateTime? expiredAt;
- String amount;
- String? receiveAmount;
- String? inputAddress;
- String? extraId;
- String? outputTransaction;
- String? refundAddress;
- String? walletId;
- String? payoutAddress;
-
- // holds the receive address memo or destination tag that was passed for this trade
- String? toAddressExtraId;
- String? password;
- String? providerId;
- String? providerName;
- String? fromWalletAddress;
- String? memo;
- String? txId;
- bool? isRefund;
- bool? isSendAll;
- String? router;
-
- // The following fields are used for SwapXyz trades only
- bool? needToRegisterInSwapXyz;
- String? sourceTokenAddress;
- int? sourceTokenDecimals;
- String? routerData;
- String? routerValue;
- int? routerChainId;
- String? sourceTokenAmountRaw;
- bool? requiresTokenApproval;
-
- int? chainId;
- double? fee;
-
- String get chainName {
- if (chainId == null) return '';
-
- return evm!.getChainNameByChainId(chainId!).capitalized();
- }
-
- // ── SQLite CRUD ──────────────────────────────────────
-
- Future<int> save() async {
- final json = toSqliteMap();
- if (json[selfIdColumn] == 0) {
- json[selfIdColumn] = null;
- }
- internalId = await db!.insert(
+ final String id;
+
+ final ExchangeProviderDescription provider;
+
+ final TradeState state;
+
+ final DateTime? createdAt;
+ final DateTime? expiredAt;
+ final Money depositAmount;
+ final Money payoutAmount;
+ final String fundingAddress;
+ final String? extraId;
+ final String? outputTransaction;
+ final String? walletId;
+ final int? accountIndex;
+ final String refundAddress;
+ final String payoutAddress;
+ final String? providerName;
+ final String? toAddressExtraId;
+ final String? password;
+ final String? providerId;
+ final String? memo;
+ final String? txId;
+ final bool? isRefund;
+
+ // legacy field. used only for migrated trades, do not use in new trades
+ String? _fromWalletAddress;
+
+ String? get fromWalletAddress => _fromWalletAddress;
+
+ CryptoCurrency get depositCurrency => depositAmount.currency as CryptoCurrency;
+ CryptoCurrency get payoutCurrency => payoutAmount.currency as CryptoCurrency;
+
+ PaymentURI? get uri =>
+ SwapUriHelper.getUri(
+ fundingAddress, depositAmount.toString(), depositAmount.currency as CryptoCurrency);
+
+ Future<void> save() async {
+ _fillMissingChainId(depositCurrency);
+ _fillMissingChainId(payoutCurrency);
+ await db!.insert(
tableName,
- json,
+ toSqliteMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
onChanged.add(null);
- return internalId;
+ }
+
+ // default evm tokens have no chainId, which would serialize as "evm^<address>^null"
+ static void _fillMissingChainId(CryptoCurrency currency) {
+ if (currency is! Erc20Token || currency.chainId != null || currency.tag == null) return;
+ currency.chainId = evm!.getChainIdByTag(currency.tag!);
}
static Future<List<Trade>> getAll({String? orderBy}) async {
final list = await db!.query(
tableName,
- orderBy: orderBy ?? 'createdAt DESC',
- );
- return List.generate(
- list.length,
- (i) => Trade.fromSqliteRow(list[i]),
+ orderBy: orderBy ?? "createdAt DESC",
);
+ return (await Future.wait(
+ list.map((row) async {
+ try {
+ return await Trade.fromSqliteRow(row);
+ } catch (e, st) {
+ printV("failed to deserialize trade ${row[selfIdColumn]}: $e\n$st");
+ return null;
+ }
+ }),
+ )).nonNulls.toList();
}
static Future<Trade?> getByTradeId(String id) async {
final list = await db!.query(
tableName,
- where: 'id = ?',
+ where: "$selfIdColumn = ?",
whereArgs: [id],
limit: 1,
);
- if (list.isEmpty) return null;
+ if (list.isEmpty) {
+ return null;
+ }
return Trade.fromSqliteRow(list.first);
}
static Future<int> deleteTrade(Trade trade) async {
final rows = await db!.delete(
tableName,
- where: '$selfIdColumn = ?',
- whereArgs: [trade.internalId],
+ where: "$selfIdColumn = ?",
+ whereArgs: [trade.id],
);
onChanged.add(null);
return rows;
}
- // ── SQLite serialization ─────────────────────────────
- void mergeFindTradeByIdResult(Trade updated) {
- if (updated.stateRaw.isNotEmpty) stateRaw = updated.stateRaw;
- if (createdAt == null && updated.createdAt != null) {
- createdAt = updated.createdAt;
- }
- if (updated.expiredAt != null) expiredAt = updated.expiredAt;
- if (updated.isRefund != null) isRefund = updated.isRefund;
-
- if (updated.receiveAmount != null) receiveAmount = updated.receiveAmount;
- if (updated.inputAddress != null) inputAddress = updated.inputAddress;
- if (updated.extraId != null) extraId = updated.extraId;
- if (updated.outputTransaction != null) {
- outputTransaction = updated.outputTransaction;
- }
- if (updated.refundAddress != null) refundAddress = updated.refundAddress;
- if (updated.payoutAddress != null) payoutAddress = updated.payoutAddress;
- if (updated.password != null) password = updated.password;
- if (updated.providerId != null) providerId = updated.providerId;
- if (updated.providerName != null) providerName = updated.providerName;
- if (updated.memo != null) memo = updated.memo;
- if (updated.txId != null) txId = updated.txId;
- }
-
- Map<String, dynamic> toSqliteMap() {
- return <String, dynamic>{
- selfIdColumn: internalId,
- 'id': id,
- 'providerRaw': providerRaw,
- 'fromTitle': from?.title,
- 'fromName': from?.name,
- 'fromTag': from?.tag,
- 'fromFullName': from?.fullName,
- 'fromDecimals': from?.decimals,
- 'fromRaw': from?.raw,
- 'fromIconPath': from?.iconPath,
- 'fromFlatIconPath': from?.flatIconPath,
- 'fromChainIconPath': from?.chainIconPath,
- 'toTitle': to?.title,
- 'toName': to?.name,
- 'toTag': to?.tag,
- 'toFullName': to?.fullName,
- 'toDecimals': to?.decimals,
- 'toRaw': to?.raw,
- 'toIconPath': to?.iconPath,
- 'toFlatIconPath': to?.flatIconPath,
- 'toChainIconPath': to?.chainIconPath,
- 'stateRaw': stateRaw,
- 'createdAt': createdAt?.millisecondsSinceEpoch,
- 'expiredAt': expiredAt?.millisecondsSinceEpoch,
- 'amount': amount,
- 'receiveAmount': receiveAmount,
- 'inputAddress': inputAddress,
- 'extraId': extraId,
- 'outputTransaction': outputTransaction,
- 'refundAddress': refundAddress,
- 'walletId': walletId,
- 'payoutAddress': payoutAddress,
- 'toAddressExtraId': toAddressExtraId,
- 'password': password,
- 'providerId': providerId,
- 'providerName': providerName,
- 'fromWalletAddress': fromWalletAddress,
- 'memo': memo,
- 'txId': txId,
- 'isRefund': isRefund == true ? 1 : 0,
- 'isSendAll': isSendAll == true ? 1 : 0,
- 'router': router,
- 'needToRegisterInSwapXyz': needToRegisterInSwapXyz == true ? 1 : 0,
- 'sourceTokenAddress': sourceTokenAddress,
- 'sourceTokenDecimals': sourceTokenDecimals,
- 'routerData': routerData,
- 'routerValue': routerValue,
- 'routerChainId': routerChainId,
- 'sourceTokenAmountRaw': sourceTokenAmountRaw,
- 'requiresTokenApproval': requiresTokenApproval == true ? 1 : 0,
- 'chainId': chainId,
- 'fee': fee,
+ Map<String, dynamic> toSqliteMap() => {
+ selfIdColumn: id,
+ "provider": provider.raw,
+ "payoutAmount": payoutAmount.serialized,
+ "depositAmount": depositAmount.serialized,
+ "state": state.raw,
+ "createdAt": createdAt?.millisecondsSinceEpoch,
+ "expiredAt": expiredAt?.millisecondsSinceEpoch,
+ "extraId": extraId,
+ "outputTransaction": outputTransaction,
+ "walletId": walletId,
+ "payoutAddress": payoutAddress,
+ "toAddressExtraId": toAddressExtraId,
+ "password": password,
+ "accountIndex": accountIndex,
+ "providerId": providerId,
+ "providerName": providerName,
+ "memo": memo,
+ "txId": txId,
+ "isRefund": isRefund == true ? 1 : 0,
+ "fundingAddress": fundingAddress,
+ "refundAddress": refundAddress,
+ "fromWalletAddress": fromWalletAddress,
};
- }
- factory Trade.fromSqliteRow(Map<String, dynamic> row) {
- final trade = Trade(
- id: row['id'] as String? ?? '',
- amount: row['amount'] as String? ?? '',
- receiveAmount: row['receiveAmount'] as String?,
- createdAt: row['createdAt'] != null
+ static Future<Trade> fromSqliteRow(Map<String, dynamic> row) async => Trade(
+ id: row[selfIdColumn] as String,
+ createdAt: row["createdAt"] != null
? DateTime.fromMillisecondsSinceEpoch(
- row['createdAt'] as int,
+ row["createdAt"] as int,
)
: null,
- expiredAt: row['expiredAt'] != null
+ expiredAt: row["expiredAt"] != null
? DateTime.fromMillisecondsSinceEpoch(
- row['expiredAt'] as int,
+ row["expiredAt"] as int,
)
: null,
- inputAddress: row['inputAddress'] as String?,
- extraId: row['extraId'] as String?,
- outputTransaction: row['outputTransaction'] as String?,
- refundAddress: row['refundAddress'] as String?,
- walletId: row['walletId'] as String?,
- payoutAddress: row['payoutAddress'] as String?,
- toAddressExtraId: row['toAddressExtraId'] as String?,
- password: row['password'] as String?,
- providerId: row['providerId'] as String?,
- providerName: row['providerName'] as String?,
- fromWalletAddress: row['fromWalletAddress'] as String?,
- memo: row['memo'] as String?,
- fee: row['fee'] as double?,
- txId: row['txId'] as String?,
- isRefund: (row['isRefund'] as int?) == 1,
- isSendAll: (row['isSendAll'] as int?) == 1,
- router: row['router'] as String?,
- from: _currencyFromRow(row, 'from'),
- to: _currencyFromRow(row, 'to'),
- needToRegisterInSwapXyz: (row['needToRegisterInSwapXyz'] as int?) == 1,
- sourceTokenAddress: row['sourceTokenAddress'] as String?,
- sourceTokenDecimals: row['sourceTokenDecimals'] as int?,
- routerData: row['routerData'] as String?,
- routerValue: row['routerValue'] as String?,
- routerChainId: row['routerChainId'] as int?,
- sourceTokenAmountRaw: row['sourceTokenAmountRaw'] as String?,
- requiresTokenApproval: (row['requiresTokenApproval'] as int?) == 1,
- chainId: row['chainId'] as int?,
- );
- trade.internalId = row[selfIdColumn] as int? ?? 0;
- trade.providerRaw = row['providerRaw'] as int? ?? 0;
- trade.stateRaw = row['stateRaw'] as String? ?? '';
- return trade;
- }
-
- static CryptoCurrency? _currencyFromRow(Map<String, dynamic> row, String prefix) {
- final title = row['${prefix}Title'] as String?;
- if (title == null || title.isEmpty) return null;
-
- final tag = row['${prefix}Tag'] as String?;
-
- final live = CryptoCurrency.safeParseCurrencyFromString(title, tag: tag);
- if (live != null) return live;
+ extraId: row["extraId"] as String?,
+ outputTransaction: row["outputTransaction"] as String?,
+ refundAddress: row["refundAddress"] as String? ?? "",
+ walletId: row["walletId"] as String?,
+ accountIndex: row["accountIndex"] as int?,
+ payoutAddress: row["payoutAddress"] as String? ?? "",
+ provider: ExchangeProviderDescription.deserialize(raw: row["provider"] as int),
+ toAddressExtraId: row["toAddressExtraId"] as String?,
+ password: row["password"] as String?,
+ providerId: row["providerId"] as String?,
+ providerName: row["providerName"] as String?,
+ state: TradeState.deserialize(raw: row["state"] as String),
+ memo: row["memo"] as String?,
+ txId: row["txId"] as String?,
+ isRefund: (row["isRefund"] as int?) == 1,
+ depositAmount: await moneyFromSerialized(row["depositAmount"] as String),
+ payoutAmount: await moneyFromSerialized(row["payoutAmount"] as String),
+ fundingAddress: row["fundingAddress"] as String,
+ ).._fromWalletAddress = row["fromWalletAddress"] as String?;
+
+ Trade copyWith({
+ TradeState? state,
+ Money? depositAmount,
+ Money? payoutAmount,
+ String? fundingAddress,
+ String? providerName,
+ String? id,
+ ExchangeProviderDescription? provider,
+ String? payoutAddress,
+ String? refundAddress,
+ int? accountIndex,
+ DateTime? createdAt,
+ DateTime? expiredAt,
+ String? extraId,
+ String? outputTransaction,
+ String? walletId,
+ String? toAddressExtraId,
+ String? password,
+ String? providerId,
+ String? memo,
+ String? txId,
+ bool? isRefund,
+ }) => Trade(
+ state: state ?? this.state,
+ depositAmount: depositAmount ?? this.depositAmount,
+ payoutAmount: payoutAmount ?? this.payoutAmount,
+ fundingAddress: fundingAddress ?? this.fundingAddress,
+ providerName: providerName ?? this.providerName,
+ id: id ?? this.id,
+ accountIndex: accountIndex ?? this.accountIndex,
+ provider: provider ?? this.provider,
+ payoutAddress: payoutAddress ?? this.payoutAddress,
+ refundAddress: refundAddress ?? this.refundAddress,
+ createdAt: createdAt ?? this.createdAt,
+ expiredAt: expiredAt ?? this.expiredAt,
+ extraId: extraId ?? this.extraId,
+ outputTransaction: outputTransaction ?? this.outputTransaction,
+ walletId: walletId ?? this.walletId,
+ toAddressExtraId: toAddressExtraId ?? this.toAddressExtraId,
+ password: password ?? this.password,
+ providerId: providerId ?? this.providerId,
+ memo: memo ?? this.memo,
+ txId: txId ?? this.txId,
+ isRefund: isRefund ?? this.isRefund,
+ ).._fromWalletAddress = _fromWalletAddress;
- return CryptoCurrency(
- title: title,
- name: row['${prefix}Name'] as String? ?? '',
- tag: tag,
- fullName: row['${prefix}FullName'] as String?,
- decimals: row['${prefix}Decimals'] as int? ?? 1,
- raw: row['${prefix}Raw'] as int? ?? -1,
- iconPath: row['${prefix}IconPath'] as String?,
- flatIconPath: row['${prefix}FlatIconPath'] as String?,
- chainIconPath: row['${prefix}ChainIconPath'] as String?,
- );
- }
+}
- String amountFormatted() => formatAmount(amount);
- String receiveAmountFormatted() => formatAmount(receiveAmount ?? '');
+class RoutableTrade extends Trade {
+ RoutableTrade({required this.routerData, required this.routerValue, required super.state, required super.depositAmount, required super.payoutAmount, required super.id, required super.provider, required super.payoutAddress, required super.refundAddress,
+
+ required super.fundingAddress, super.createdAt,
+ super.expiredAt,
+ super.extraId,
+ super.outputTransaction,
+ super.walletId,
+ super.toAddressExtraId,
+ super.password,
+ super.providerId,
+ super.memo,
+ super.txId,
+ super.isRefund, this.router,});
+
+ final String routerData;
+ final String routerValue;
+ final String? router;
}
### lib/exchange/trade_currency_snapshot.dart
@@ -24,7 +24,7 @@ class TradeCurrencySnapshot {
title: titleTag,
name: '',
raw: -1,
- decimals: 1,
+ decimals: 18,
);
}
@@ -39,7 +39,7 @@ class TradeCurrencySnapshot {
tag: tag.isNotEmpty ? tag : null,
name: '',
raw: -1,
- decimals: 1,
+ decimals: 18,
);
}
}
### lib/exchange/trade_legacy.dart
@@ -1,16 +1,18 @@
-import 'package:cake_wallet/core/secure_storage.dart';
-import 'package:cake_wallet/entities/get_encryption_key.dart';
-import 'package:cake_wallet/exchange/exchange_provider_description.dart';
-import 'package:cake_wallet/exchange/trade.dart';
-import 'package:cake_wallet/exchange/trade_currency_snapshot.dart';
-import 'package:cake_wallet/exchange/trade_state.dart';
-import 'package:cw_core/cake_hive.dart';
-import 'package:cw_core/crypto_currency.dart';
-import 'package:cw_core/hive_type_ids.dart';
-import 'package:cw_core/utils/print_verbose.dart';
-import 'package:hive/hive.dart';
+import "package:cake_wallet/core/secure_storage.dart";
+import "package:cake_wallet/entities/get_encryption_key.dart";
+import "package:cake_wallet/exchange/exchange_provider_description.dart";
+import "package:cake_wallet/exchange/trade.dart";
+import "package:cake_wallet/exchange/trade_currency_snapshot.dart";
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/cake_hive.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/db/sqlite.dart";
+import "package:cw_core/hive_type_ids.dart";
+import "package:cw_core/utils/print_verbose.dart";
+import "package:hive/hive.dart";
-part 'trade_legacy.part.dart';
+part "trade_legacy.part.dart";
Future<void> performTradeHiveMigration(SecureStorage secureStorage) async {
try {
@@ -21,7 +23,7 @@ Future<void> performTradeHiveMigration(SecureStorage secureStorage) async {
final box = await CakeHive.openBox<TradeLegacy>(Trade.boxName, encryptionKey: tradesBoxKey);
await TradeLegacy.migrateAllToSqlite(box);
} catch (e) {
- printV('Trade Hive migration error: $e');
+ printV("Trade Hive migration error: $e");
}
}
@@ -64,10 +66,14 @@ class TradeLegacy extends HiveObject {
this.requiresTokenApproval,
this.chainId,
}) {
- if (provider != null) providerRaw = provider.raw;
+ if (provider != null) {
+ providerRaw = provider.raw;
+ }
fromRaw = from?.raw ?? -1;
toRaw = to?.raw ?? -1;
- if (state != null) stateRaw = state.raw;
+ if (state != null) {
+ stateRaw = state.raw;
+ }
}
static const typeId = TRADE_TYPE_ID;
@@ -112,57 +118,54 @@ class TradeLegacy extends HiveObject {
Future<void> migrateToSqlite() async {
final trade = Trade(
id: id,
- amount: amount,
- receiveAmount: receiveAmount,
createdAt: createdAt,
expiredAt: expiredAt,
- inputAddress: inputAddress,
+ fundingAddress: inputAddress ?? "",
extraId: extraId,
outputTransaction: outputTransaction,
- refundAddress: refundAddress,
+ refundAddress: refundAddress ?? "",
walletId: walletId,
- payoutAddress: payoutAddress,
+ payoutAddress: payoutAddress ?? "",
password: password,
providerId: providerId,
providerName: providerName,
- fromWalletAddress: fromWalletAddress,
memo: memo,
- fee: fee,
txId: txId,
isRefund: isRefund,
- isSendAll: isSendAll,
- router: router,
- from:
- TradeCurrencySnapshot.fromLegacyHive(raw: fromRaw, displayTitleTag: userCurrencyFromRaw),
- to: TradeCurrencySnapshot.fromLegacyHive(raw: toRaw, displayTitleTag: userCurrencyToRaw),
- needToRegisterInSwapXyz: needToRegisterInSwapXyz,
- sourceTokenAddress: sourceTokenAddress,
- sourceTokenDecimals: sourceTokenDecimals,
- routerData: routerData,
- routerValue: routerValue,
- routerChainId: routerChainId,
- sourceTokenAmountRaw: sourceTokenAmountRaw,
- requiresTokenApproval: requiresTokenApproval,
- chainId: chainId,
+ accountIndex: fromRaw == CryptoCurrency.xmr.raw ? -1 : 0,
+ depositAmount: Money.parse(
+ amount,
+ TradeCurrencySnapshot.fromLegacyHive(raw: fromRaw, displayTitleTag: userCurrencyFromRaw)!,
+ ),
+ payoutAmount: Money.parse(
+ receiveAmount ?? "",
+ TradeCurrencySnapshot.fromLegacyHive(raw: toRaw, displayTitleTag: userCurrencyToRaw)!,
+ ),
+ state: TradeState.deserialize(raw: stateRaw),
+ provider: ExchangeProviderDescription.deserialize(raw: providerRaw),
);
- trade.providerRaw = providerRaw;
- trade.stateRaw = stateRaw;
await trade.save();
+ if (fromRaw == CryptoCurrency.xmr.raw) {
+ await db!.update(
+ Trade.tableName,
+ {"fromWalletAddress": fromWalletAddress},
+ where: "${Trade.selfIdColumn} = ?",
+ whereArgs: [id],
+ );
+ }
}
- static Future<void> migrateAllToSqlite(
- Box<TradeLegacy> box,
- ) async {
- printV('Migrating Trades to SQLite: start');
+ static Future<void> migrateAllToSqlite(Box<TradeLegacy> box) async {
+ printV("Migrating Trades to SQLite: start");
final list = box.values.toList();
for (final trade in list) {
try {
await trade.migrateToSqlite();
await trade.delete();
} catch (e) {
- printV('Error migrating trade ${trade.id}: $e');
+ printV("Error migrating trade ${trade.id}: $e");
}
}
- printV('Migrating Trades to SQLite: end');
+ printV("Migrating Trades to SQLite: end");
}
}
### lib/exchange/trade_not_found_exception.dart
[binary or diff unavailable]
### lib/exchange/trade_request.dart
@@ -1,22 +1,46 @@
-import 'package:cw_core/crypto_currency.dart';
+import "package:cake_wallet/exchange/rate_request.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/crypto_currency.dart";
class TradeRequest {
- TradeRequest(
- {required this.fromCurrency,
- required this.toCurrency,
- required this.toAddress,
- required this.refundAddress,
- required this.fromAmount,
- this.toAmount = '',
- this.toAddressExtraId = '',
- this.isFixedRate = false});
+ TradeRequest({
+ required this.refundAddress,
+ required this.payoutAddress,
+ required this.depositAmount,
+ required this.payoutAmount,
+ required this.isFixedRate,
+ this.refundInvoice,
+ this.payoutInvoice,
+ String? toAddressExtraId,
+ // providers really don't like when you send an empty extraId, so we make it null
+ }) : toAddressExtraId = toAddressExtraId?.isEmpty ?? false ? null : toAddressExtraId;
- final CryptoCurrency fromCurrency;
- final CryptoCurrency toCurrency;
- final String toAddress;
final String refundAddress;
- final String fromAmount;
- final String toAmount;
- final String toAddressExtraId;
+ final String payoutAddress;
+ // set when the address is a lightning address, for providers that can't take those
+ final String? refundInvoice;
+ final String? payoutInvoice;
+ final Money depositAmount;
+ final Money payoutAmount;
+ final String? toAddressExtraId;
final bool isFixedRate;
+
+ CryptoCurrency get depositCurrency => depositAmount.currency as CryptoCurrency;
+
+ CryptoCurrency get payoutCurrency => payoutAmount.currency as CryptoCurrency;
+
+ RateRequest get rateRequest => isFixedRate
+ ? FixedRateRequest(depositCurrency: depositCurrency, payoutAmount: payoutAmount)
+ : FloatingRateRequest(depositAmount: depositAmount, payoutCurrency: payoutCurrency);
+
+ Map<String, dynamic> toJson() => {
+ "refundAddress": refundAddress,
+ "payoutAddress": payoutAddress,
+ "refundInvoice": refundInvoice,
+ "payoutInvoice": payoutInvoice,
+ "depositAmount": depositAmount.serialized,
+ "payoutAmount": payoutAmount.serialized,
+ "toAddressExtraId": toAddressExtraId,
+ "isFixedRate": isFixedRate,
+ };
}
### lib/exchange/utils/json_converters.dart
@@ -0,0 +1,57 @@
+
+import "package:cake_wallet/exchange/trade_state.dart";
+import "package:json_annotation/json_annotation.dart";
+
+class MillisDateTimeConverter implements JsonConverter<DateTime, int> {
+ const MillisDateTimeConverter();
+
+ @override
+ DateTime fromJson(int json) => DateTime.fromMillisecondsSinceEpoch(json, isUtc: true);
+
+ @override
+ int toJson(DateTime dateTime) => dateTime.millisecondsSinceEpoch;
+}
+
+class IntStringConverter extends JsonConverter<int, String> {
+ const IntStringConverter();
+
+ @override
+ int fromJson(String json) => int.parse(json);
+
+ @override
+ String toJson(int value) => value.toString();
+}
+
+
+class TradeStateConverter implements JsonConverter<TradeState, String> {
+ const TradeStateConverter();
+
+ @override
+ TradeState fromJson(String json) => TradeState.deserialize(raw: json);
+
+ @override
+ String toJson(TradeState state) => state.serialize();
+}
+
+
+class SecondsDateTimeConverter implements JsonConverter<DateTime, int> {
+ const SecondsDateTimeConverter();
+
+ @override
+ DateTime fromJson(int json) => DateTime.fromMillisecondsSinceEpoch(json * 1000, isUtc: true);
+
+ @override
+ int toJson(DateTime value) => value.millisecondsSinceEpoch ~/ 1000;
+}
+
+
+
+class StringBoolConverter implements JsonConverter<bool, String> {
+ const StringBoolConverter();
+
+ @override
+ bool fromJson(String json) => json.toLowerCase() == "true";
+
+ @override
+ String toJson(bool value) => value.toString();
+}
### lib/exchange/utils/provider_api.dart
@@ -0,0 +1,108 @@
+import "dart:convert";
+
+import "package:cw_core/utils/proxy_wrapper.dart";
+import "package:json_annotation/json_annotation.dart";
+
+enum HttpMethod { get, post }
+
+abstract class ApiRequest<Res> {
+ const ApiRequest() : method = HttpMethod.get;
+
+ const ApiRequest.post() : method = HttpMethod.post;
+
+ @JsonKey(includeToJson: false, includeFromJson: false)
+ final HttpMethod method;
+
+ // no it can't be String get path because the json serializer would break lol
+ String path();
+
+ Map<String, dynamic> toJson();
+
+ Res decode(Object json);
+}
+
+class ProviderHttpException implements Exception {
+ ProviderHttpException(this.statusCode, this.message, {required this.body, this.json});
+
+ final int statusCode;
+ final String message;
+ final String body;
+
+ final Object? json;
+
+ @override
+ String toString() => message;
+}
+
+class ProviderApi {
+ ProviderApi(this._proxy, {required this.authority, this.onionAuthority, this.useTorOnly = false, this.headers = const {}, this.errorMessage});
+
+ final ProxyWrapper _proxy;
+ final String authority;
+ final String? onionAuthority;
+ final bool useTorOnly;
+ final Map<String, String> headers;
+
+
+ Future<Uri> _getUri(String path, Map<String, dynamic>? queryParams) async {
+ if(onionAuthority == null || !CakeTor.instance!.started) return Uri.https(authority, path, queryParams);
+
+
+ final uri = Uri.http(onionAuthority!, path, queryParams);
+
+ if (useTorOnly) {
+ return uri;
+ }
+
+ try {
+ await ProxyWrapper().get(clearnetUri: uri);
+ return uri;
+ } catch (e) {
+ return Uri.https(authority, path, queryParams);
+ }
+ }
+
+
+ // every provider has a slightly different way of providing the error message
+ // we pass in a function for this to show a meaningful error in logs instead of Instance of WhateverException
+ final String? Function(Map<String, dynamic> json)? errorMessage;
+
+ Future<Res> send<Res>(
+ ApiRequest<Res> request, {
+ Exception? Function(ProviderHttpException error)? mapError,
+ }) async {
+ final response = switch (request.method) {
+ HttpMethod.get => await _proxy.get(
+ clearnetUri: await _getUri(request.path(), request.toJson()),
+ headers: headers,
+ ),
+ HttpMethod.post => await _proxy.post(
+ clearnetUri: await _getUri(request.path(), null),
+ headers: {...headers, "Content-Type": "application/json"},
+ body: json.encode(request.toJson()),
+ ),
+ };
+
+ if (response.statusCode < 200 || response.statusCode > 299) {
+ final error = _error(response.statusCode, response.body);
+ throw mapError?.call(error) ?? error;
+ }
+
+ return request.decode(json.decode(response.body) as Object);
+ }
+
+ ProviderHttpException _error(int statusCode, String body) {
+ final decoded = _tryDecode(body);
+ final parsed = decoded is Map<String, dynamic> ? errorMessage?.call(decoded) : null;
+ final message = parsed ?? (decoded == null ? "HTTP $statusCode" : "HTTP $statusCode: $body");
+ return ProviderHttpException(statusCode, message, body: body, json: decoded);
+ }
+
+ static Object? _tryDecode(String body) {
+ try {
+ return json.decode(body);
+ } on FormatException {
+ return null;
+ }
+ }
+}
### lib/monero/cw_monero.dart
@@ -401,7 +401,7 @@ class CWMonero extends Monero {
}
@override
- List<Unspent> getUnspents(Object wallet) {
+ List<MoneroUnspent> getUnspents(Object wallet) {
final moneroWallet = wallet as MoneroWallet;
return moneroWallet.unspentCoins;
}
@@ -496,4 +496,23 @@ class CWMonero extends Monero {
@override
Map<String, dynamic> getWalletCacheDebug() => monero_wallet_api.getWalletCacheDebug();
+
+ @override
+ Future<Money> getSendingBalance(WalletBase wallet) async {
+ await updateUnspents(wallet);
+
+ Money total = Money.zero(CryptoCurrency.xmr);
+ Set<String> seen = {};
+ for (final item in getUnspents(wallet)) {
+ if (seen.contains(item.toString())) {
+ continue;
+ }
+ seen.add(item.toString());
+ if (item.isFrozen || !item.isSending || !item.isUnlocked) {
+ continue;
+ }
+ total += Money.fromInt(item.value, CryptoCurrency.xmr);
+ }
+ return total;
+ }
}
### lib/new-ui/modal_navigator.dart
@@ -47,10 +47,17 @@ class _ModalNavigatorState extends State<ModalNavigator> {
if (context == null) return;
if (_sheetHeight != null) return;
- final box = context.findRenderObject() as RenderBox;
- setState(() {
- _sheetHeight = box.size.height;
- });
+ if(widget.heightMode == .autoLock) {
+ final box = context.findRenderObject() as RenderBox;
+ setState(() {
+ _sheetHeight = box.size.height;
+ });
+ } else if(widget.heightMode == .fullScreen) {
+ setState(() {
+ _sheetHeight = MediaQuery.of(context).size.height;
+ });
+ }
+
});
}
@@ -59,8 +66,6 @@ class _ModalNavigatorState extends State<ModalNavigator> {
late final double? height;
switch (widget.heightMode) {
case ModalHeightModes.fullScreen:
- height = MediaQuery.of(context).size.height;
- break;
case ModalHeightModes.autoLock:
height = _sheetHeight;
break;
### lib/new-ui/pages/send_page.dart
@@ -26,6 +26,7 @@ import "package:cake_wallet/new-ui/widgets/anypay/select_recipient_network_sheet
import "package:cake_wallet/new-ui/widgets/currency_picker/currency_picker_args.dart";
import "package:cake_wallet/new-ui/widgets/currency_picker/currency_picker_sheet.dart";
import "package:cake_wallet/new-ui/widgets/currency_picker/fiat_currency_picker_sheet.dart";
+import "package:cake_wallet/new-ui/widgets/hardware_wallet/connect_hardware_wallet.dart";
import "package:cake_wallet/new-ui/widgets/keyboard_hide_overlay.dart";
import "package:cake_wallet/new-ui/widgets/modern_button.dart";
import "package:cake_wallet/new-ui/widgets/new_future_primary_button.dart";
@@ -43,7 +44,6 @@ import "package:cake_wallet/new-ui/widgets/send_page/send_memo_input.dart";
import "package:cake_wallet/new-ui/widgets/send_page/send_syncing_indicator.dart";
import "package:cake_wallet/reactions/wallet_connect.dart";
import "package:cake_wallet/routes.dart" show Routes;
-import "package:cake_wallet/src/screens/connect_device/connect_device_page.dart";
import "package:cake_wallet/src/widgets/alert_with_one_action.dart";
import "package:cake_wallet/src/widgets/cake_image_widget.dart";
import "package:cake_wallet/src/widgets/new_list_row/list_item_regular_row_widget.dart";
@@ -52,7 +52,6 @@ import "package:cake_wallet/store/settings_store.dart";
import "package:cake_wallet/utils/payment_request.dart";
import "package:cake_wallet/utils/show_pop_up.dart";
import "package:cake_wallet/view_model/contact_list/contact_list_view_model.dart";
-import "package:cake_wallet/view_model/hardware_wallet/trezor_connect_view_model.dart";
import "package:cake_wallet/view_model/link_view_model.dart";
import "package:cake_wallet/view_model/send/output.dart";
import "package:cake_wallet/view_model/send/send_view_model.dart";
@@ -567,15 +566,9 @@ class _NewSendPageState extends State<NewSendPage> {
FiatAmountBar(
fiatInputMode: output.isFiatEntry,
onSwitchButtonPressed: _onFiatSwitchPressed,
- fiatAmount:
- _wrapAmount(output.roundedFiatAmount(6), 20),
- cryptoAmount:
- _wrapAmount(output.roundedCryptoAmount(6), 20),
- allAmount: widget.sendViewModel.balance,
- cryptoCurrencySymbol:
- widget.sendViewModel.selectedCryptoCurrencySymbol,
- fiatCurrencySymbol:
- widget.sendViewModel.fiatCurrency.symbol,
+ fiatAmount: output.fiatAmountMoney,
+ cryptoAmount: output.cryptoAmountMoney,
+ allAmount: widget.sendViewModel.availableBalance,
onAllButtonPressed: () async {
output.setSendAll(
await widget.sendViewModel.sendingBalance,
@@ -872,48 +865,13 @@ class _NewSendPageState extends State<NewSendPage> {
return;
}
- if (widget.sendViewModel.wallet.isHardwareWallet) {
- final trezorVM = widget.sendViewModel.hardwareWalletViewModel;
- if (trezorVM is TrezorConnectViewModel &&
- widget.sendViewModel.walletType == WalletType.bitcoin &&
- trezorVM.isConnected(WalletType.bitcoin) &&
- !trezorVM.isSessionFor(widget.sendViewModel.wallet)) {
- // The live session belongs to another wallet (passphrase); open one for this wallet
- await trezorVM.dropSession();
- }
-
- if (!widget.sendViewModel.hardwareWalletViewModel!
- .isConnected(widget.sendViewModel.walletType)) {
- final hardwareWalletVM = widget.sendViewModel.hardwareWalletViewModel;
- if (hardwareWalletVM is TrezorConnectViewModel &&
- widget.sendViewModel.walletType == WalletType.bitcoin) {
- hardwareWalletVM.prepareReconnect(widget.sendViewModel.wallet);
- }
-
- await Navigator.of(context).pushNamed(
- Routes.connectDevices,
- arguments: ConnectDevicePageParams(
- walletType: widget.sendViewModel.walletType,
- hardwareWalletType: widget.sendViewModel.wallet.walletInfo.hardwareWalletType!,
- onConnectDevice: (_, __) {
- widget.sendViewModel.hardwareWalletViewModel!.initWallet(widget.sendViewModel.wallet);
- Navigator.of(context).pop();
- },
- isReconnect: false,
- ),
- );
- if (hardwareWalletVM is TrezorConnectViewModel) {
- hardwareWalletVM.cancelReconnect();
- }
-
- // Recheck to handle tap-backs
- if (!widget.sendViewModel.hardwareWalletViewModel!
- .isConnected(widget.sendViewModel.walletType)) {
- return;
- }
- } else {
- await widget.sendViewModel.hardwareWalletViewModel!.initWallet(widget.sendViewModel.wallet);
- }
+ if (widget.sendViewModel.wallet.isHardwareWallet &&
+ !await connectHardwareWallet(
+ context,
+ widget.sendViewModel.wallet,
+ widget.sendViewModel.hardwareWalletViewModel!,
+ )) {
+ return;
}
if (widget.sendViewModel.wallet.type == WalletType.monero) {
@@ -1364,9 +1322,6 @@ class _NewSendPageState extends State<NewSendPage> {
);
}
- String _wrapAmount(String amount, int maxChars) =>
- amount.length <= maxChars ? amount : "${amount.substring(0, maxChars - 3)}...";
-
// TODO: make a separate variable for memo in payment request model
void _applyNote(String note, int selectedOutput) {
if (widget.sendViewModel.hasMemos && note.length <= widget.sendViewModel.maxMemoLength) {
### lib/new-ui/pages/swap_page.dart
[binary or diff unavailable]
### lib/new-ui/services/transaction_service.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/bloc/swap_bloc.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/bloc/swap_event.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/bloc/swap_presentation_event.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/bloc/swap_state.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/currency_provider.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/provider_registry.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/rates/rate_cubit.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/rates/rate_state.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/swap_address_resolver.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/swap_wallet_list_service.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/trade_creator.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/util/exchange_limits.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/util/fees_helper.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/util/provider_rate.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/util/swap_address.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/util/swap_amount.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/util/swap_source.dart
[binary or diff unavailable]
### lib/new-ui/viewmodels/swap/util/uri_helper.dart
[binary or diff unavailable]
### lib/new-ui/widgets/anypay/anypay_flow.dart
[binary or diff unavailable]
### lib/new-ui/widgets/charts_page/chart_modal.dart
[binary or diff unavailable]
### lib/new-ui/widgets/coins_page/assets_history/history_section.dart
[binary or diff unavailable]
### lib/new-ui/widgets/coins_page/assets_history/history_trade_tile.dart
[binary or diff unavailable]
### lib/new-ui/widgets/currency_picker/picker_recents_loader.dart
[binary or diff unavailable]
### lib/new-ui/widgets/hardware_wallet/connect_hardware_wallet.dart
[binary or diff unavailable]
### lib/new-ui/widgets/send_page/fiat_amount_bar.dart
[binary or diff unavailable]
### lib/new-ui/widgets/send_page/send_confirm_bottom_widget.dart
[binary or diff unavailable]
### lib/new-ui/widgets/swap_page/anypay_swap_footer.dart
[binary or diff unavailable]
### lib/new-ui/widgets/swap_page/provider_options_page.dart
[binary or diff unavailable]
### lib/new-ui/widgets/swap_page/provider_selector_page.dart
[binary or diff unavailable]
### lib/new-ui/widgets/swap_page/swap_address_selection_modal.dart
[binary or diff unavailable]
### lib/new-ui/widgets/swap_page/swap_amount_box.dart
[binary or diff unavailable]
### lib/new-ui/widgets/swap_page/swap_confirm_sheet.dart
[binary or diff unavailable]
### lib/new-ui/widgets/swap_page/swap_limit_popup.dart
[binary or diff unavailable]
### lib/new-ui/widgets/swap_page/swap_options_page.dart
[binary or diff unavailable]
### lib/new-ui/widgets/swap_page/swap_send_external_modal.dart
[binary or diff unavailable]
### lib/new-ui/widgets/swap_page/swap_source_selector.dart
[binary or diff unavailable]
### lib/new-ui/widgets/swap_page/trocador_providers_settings.dart
[binary or diff unavailable]
### lib/routes.dart
[binary or diff unavailable]
### lib/solana/cw_solana.dart
[binary or diff unavailable]
### lib/src/screens/buy/buy_sell_page.dart
[binary or diff unavailable]
### lib/src/screens/exchange/widgets/present_provider_picker.dart
[binary or diff unavailable]
### lib/src/screens/pin_code/pin_code_widget.dart
[binary or diff unavailable]
### lib/src/widgets/bottom_sheet/swap_confirmation_bottom_sheet.dart
[binary or diff unavailable]
### lib/src/widgets/bottom_sheet/swap_details_bottom_sheet.dart
[binary or diff unavailable]
### lib/src/widgets/new_list_row/list_item_regular_row_widget.dart
[binary or diff unavailable]
### lib/store/dashboard/fiat_conversion_store.dart
[binary or diff unavailable]
### lib/store/dashboard/trade_filter_store.dart
[binary or diff unavailable]
### lib/store/dashboard/trades_store.dart
[binary or diff unavailable]
### lib/store/settings_store.dart
[binary or diff unavailable]
### lib/utils/currency_from_serialized.dart
[binary or diff unavailable]
### lib/utils/feature_flag.dart
[binary or diff unavailable]
### lib/utils/list_extension.dart
[binary or diff unavailable]
### lib/view_model/dashboard/dashboard_view_model.dart
[binary or diff unavailable]
### lib/view_model/dashboard/trade_list_item.dart
[binary or diff unavailable]
### lib/view_model/exchange/exchange_trade_view_model.dart
[binary or diff unavailable]
### lib/view_model/exchange/exchange_view_model.dart
[binary or diff unavailable]
### lib/view_model/send/output.dart
[binary or diff unavailable]
### lib/view_model/send/send_view_model.dart
[binary or diff unavailable]
### lib/view_model/settings/trocador_providers_view_model.dart
[binary or diff unavailable]
### lib/view_model/trade_details_view_model.dart
[binary or diff unavailable]
### pubspec.lock
[binary or diff unavailable]
### pubspec_base.yaml
[binary or diff unavailable]
### pubspec_description.yaml
[binary or diff unavailable]
### pubspec_overrides.yaml
[binary or diff unavailable]
### res/values/strings_en.arb
[binary or diff unavailable]
### scripts/create_overrides.sh
[binary or diff unavailable]
### test/core/trade_monitor_test.dart
[binary or diff unavailable]
### test/exchange/fixture.dart
[binary or diff unavailable]
### test/exchange/fixtures/README
[binary or diff unavailable]
### test/exchange/fixtures/chainflip/assets.json
[binary or diff unavailable]
### test/exchange/fixtures/chainflip/quotes_native.json
[binary or diff unavailable]
### test/exchange/fixtures/chainflip/quotes_native_bad_amount.json
[binary or diff unavailable]
### test/exchange/fixtures/chainflip/status_by_deposit_channel.json
[binary or diff unavailable]
### test/exchange/fixtures/chainflip/swap.json
[binary or diff unavailable]
### test/exchange/fixtures/changenow/by_id.json
[binary or diff unavailable]
### test/exchange/fixtures/changenow/create_exchange.json
[binary or diff unavailable]
### test/exchange/fixtures/changenow/estimated_amount.json
[binary or diff unavailable]
### test/exchange/fixtures/changenow/estimated_amount_below_min.json
[binary or diff unavailable]
### test/exchange/fixtures/changenow/range.json
[binary or diff unavailable]
### test/exchange/fixtures/exolix/create_transaction.json
[binary or diff unavailable]
### test/exchange/fixtures/exolix/rate.json
[binary or diff unavailable]
### test/exchange/fixtures/exolix/rate_below_min.json
[binary or diff unavailable]
### test/exchange/fixtures/exolix/rate_fixed.json
[binary or diff unavailable]
### test/exchange/fixtures/exolix/transaction.json
[binary or diff unavailable]
### test/exchange/fixtures/jupiter/order_bad_amount.json
[binary or diff unavailable]
### test/exchange/fixtures/jupiter/order_quote.json
[binary or diff unavailable]
### test/exchange/fixtures/jupiter/order_with_taker.json
[binary or diff unavailable]
### test/exchange/fixtures/nearintents/quote_bad_request.json
[binary or diff unavailable]
### test/exchange/fixtures/nearintents/quote_dry.json
[binary or diff unavailable]
### test/exchange/fixtures/nearintents/quote_live.json
[binary or diff unavailable]
### test/exchange/fixtures/nearintents/status.json
[binary or diff unavailable]
### test/exchange/fixtures/nearintents/tokens.json
[binary or diff unavailable]
### test/exchange/fixtures/sideshift/pair.json
[binary or diff unavailable]
### test/exchange/fixtures/sideshift/pair_unknown.json
[binary or diff unavailable]
### test/exchange/fixtures/sideshift/pair_with_amount.json
[binary or diff unavailable]
### test/exchange/fixtures/sideshift/permissions.json
[binary or diff unavailable]
### test/exchange/fixtures/stealthex/create_exchange.json
[binary or diff unavailable]
### test/exchange/fixtures/stealthex/exchange.json
[binary or diff unavailable]
### test/exchange/fixtures/stealthex/rates_estimated_amount.json
[binary or diff unavailable]
### test/exchange/fixtures/stealthex/rates_range.json
[binary or diff unavailable]
### test/exchange/fixtures/stealthex/rates_range_no_pair.json
[binary or diff unavailable]
### test/exchange/fixtures/swapsxyz/action.json
[binary or diff unavailable]
### test/exchange/fixtures/swapsxyz/chain_list.json
[binary or diff unavailable]
### test/exchange/fixtures/swapsxyz/error_no_api_key.json
[binary or diff unavailable]
### test/exchange/fixtures/swapsxyz/paths.json
[binary or diff unavailable]
### test/exchange/fixtures/swapsxyz/quote.json
[binary or diff unavailable]
### test/exchange/fixtures/swapsxyz/status.json
[binary or diff unavailable]
### test/exchange/fixtures/swaptrade/create_order.json
[binary or diff unavailable]
### test/exchange/fixtures/swaptrade/get_coins.json
[binary or diff unavailable]
### test/exchange/fixtures/swaptrade/get_price.json
[binary or diff unavailable]
### test/exchange/fixtures/swaptrade/get_price_below_min.json
[binary or diff unavailable]
### test/exchange/fixtures/swaptrade/get_price_invalid_coin.json
[binary or diff unavailable]
### test/exchange/fixtures/swaptrade/order.json
[binary or diff unavailable]
### test/exchange/fixtures/swaptrade/order_bad_request.json
[binary or diff unavailable]
### test/exchange/fixtures/trocador/coin.json
[binary or diff unavailable]
### test/exchange/fixtures/trocador/exchanges.json
[binary or diff unavailable]
### test/exchange/fixtures/trocador/new_rate.json
[binary or diff unavailable]
### test/exchange/fixtures/trocador/new_rate_payment.json
[binary or diff unavailable]
### test/exchange/fixtures/trocador/new_trade.json
[binary or diff unavailable]
### test/exchange/fixtures/trocador/trade.json
[binary or diff unavailable]
### test/exchange/fixtures/whynot/create_transaction.json
[binary or diff unavailable]
### test/exchange/fixtures/whynot/info.json
[binary or diff unavailable]
### test/exchange/fixtures/whynot/info_bad_request.json
[binary or diff unavailable]
### test/exchange/fixtures/whynot/info_revert.json
[binary or diff unavailable]
### test/exchange/fixtures/whynot/transaction.json
[binary or diff unavailable]
### test/exchange/fixtures/xoswap/assets.json
[binary or diff unavailable]
### test/exchange/fixtures/xoswap/create_order.json
[binary or diff unavailable]
### test/exchange/fixtures/xoswap/order.json
[binary or diff unavailable]
### test/exchange/fixtures/xoswap/pair_rates.json
[binary or diff unavailable]
### test/exchange/provider/exchange_provider_suite.dart
[binary or diff unavailable]
### test/exchange/provider/exchange_providers_test.dart
[binary or diff unavailable]
### test/exchange/provider/fakes.dart
[binary or diff unavailable]
### test/exchange/provider/jupiter_update_trade_test.dart
[binary or diff unavailable]
### test/exchange/provider/mock_proxy_wrapper.dart
[binary or diff unavailable]
### test/exchange/provider/mocks/canned_responses.dart
[binary or diff unavailable]
### test/exchange/provider/mocks/canned_responses_test.dart
[binary or diff unavailable]
### test/exchange/provider/mocks/chainflip_mock.dart
[binary or diff unavailable]
### test/exchange/provider/mocks/changenow_mock.dart
[binary or diff unavailable]
### test/exchange/provider/mocks/exolix_mock.dart
[binary or diff unavailable]
### test/exchange/provider/mocks/jupiter_mock.dart
[binary or diff unavailable]
### test/exchange/provider/mocks/near_intents_mock.dart
[binary or diff unavailable]
### test/exchange/provider/mocks/stealthex_mock.dart
[binary or diff unavailable]
### test/exchange/provider/mocks/swapsxyz_mock.dart
[binary or diff unavailable]
### test/exchange/provider/mocks/swaptrade_mock.dart
[binary or diff unavailable]
### test/exchange/provider/mocks/trocador_mock.dart
[binary or diff unavailable]
### test/exchange/provider/mocks/whynot_mock.dart
[binary or diff unavailable]
### test/exchange/provider/mocks/xoswap_mock.dart
[binary or diff unavailable]
### test/exchange/provider/swapsxyz_paths_test.dart
[binary or diff unavailable]
### test/exchange/provider/swapsxyz_registration_test.dart
[binary or diff unavailable]
### test/exchange/provider/swapsxyz_transaction_test.dart
[binary or diff unavailable]
### test/exchange/provider/swapsxyz_update_trade_test.dart
[binary or diff unavailable]
### test/exchange/provider/trocador_quote_test.dart
[binary or diff unavailable]
### test/exchange/rate_request_test.dart
[binary or diff unavailable]
### test/exchange/schema/chainflip_api_schema_test.dart
[binary or diff unavailable]
### test/exchange/schema/changenow_api_schema_test.dart
[binary or diff unavailable]
### test/exchange/schema/exolix_api_schema_test.dart
[binary or diff unavailable]
### test/exchange/schema/jupiter_api_schema_test.dart
[binary or diff unavailable]
### test/exchange/schema/near_intents_api_schema_test.dart
[binary or diff unavailable]
### test/exchange/schema/stealthex_api_schema_test.dart
[binary or diff unavailable]
### test/exchange/schema/swapsxyz_api_schema_test.dart
[binary or diff unavailable]
### test/exchange/schema/swaptrade_api_schema_test.dart
[binary or diff unavailable]
### test/exchange/schema/trocador_api_schema_test.dart
[binary or diff unavailable]
### test/exchange/schema/whynot_api_schema_test.dart
[binary or diff unavailable]
### test/exchange/schema/xoswap_api_schema_test.dart
[binary or diff unavailable]
### test/exchange/trade_sqlite_test.dart
[binary or diff unavailable]
### test/exchange/utils/json_converters_test.dart
[binary or diff unavailable]
### test/exchange/utils/provider_api_test.dart
[binary or diff unavailable]
### test/new-ui/pages/archived_accounts_page_test.dart
[binary or diff unavailable]
### test/new-ui/viewmodels/swap/trade_creator_test.dart
[binary or diff unavailable]
### test/new-ui/viewmodels/swap/util/exchange_limits_test.dart
[binary or diff unavailable]
### test/new-ui/viewmodels/swap/util/provider_rate_test.dart
[binary or diff unavailable]
### test/new-ui/viewmodels/swap/util/swap_source_test.dart
[binary or diff unavailable]
### test/store/trade_filter_store_test.dart
[binary or diff unavailable]
### test/utils/currency_from_serialized_test.dart
[binary or diff unavailable]
### test/utils/list_extension_test.dart
[binary or diff unavailable]
### tool/configure.dart
[binary or diff unavailable]
### tool/exchange_provider_check.dart
[binary or diff unavailable]
### tool/fetch_exchange_fixtures.dart
[binary or diff unavailable]Why this scored 48/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.