Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/komodo_defi_framework/pubspec_overrides.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# melos_managed_dependency_overrides: komodo_defi_rpc_methods,komodo_defi_types,komodo_wallet_build_transformer
# melos_managed_dependency_overrides: komodo_defi_rpc_methods,komodo_defi_types,komodo_wallet_build_transformer,komodo_coins
dependency_overrides:
komodo_coins:
path: ../komodo_coins
komodo_defi_rpc_methods:
path: ../komodo_defi_rpc_methods
komodo_defi_types:
Expand Down
4 changes: 3 additions & 1 deletion packages/komodo_defi_local_auth/pubspec_overrides.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# melos_managed_dependency_overrides: komodo_defi_framework,komodo_defi_rpc_methods,komodo_defi_types,komodo_wallet_build_transformer
# melos_managed_dependency_overrides: komodo_defi_framework,komodo_defi_rpc_methods,komodo_defi_types,komodo_wallet_build_transformer,komodo_coins
dependency_overrides:
komodo_coins:
path: ../komodo_coins
komodo_defi_framework:
path: ../komodo_defi_framework
komodo_defi_rpc_methods:
Expand Down
72 changes: 57 additions & 15 deletions packages/komodo_defi_sdk/lib/src/pubkeys/pubkey_manager.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,62 @@
import 'dart:async';
import 'package:komodo_defi_local_auth/komodo_defi_local_auth.dart';
import 'package:komodo_defi_sdk/src/_internal_exports.dart';
import 'package:komodo_defi_types/komodo_defi_types.dart';

/// Retry utility with exponential backoff.
/// If [shouldRetry] returns true, the attempt counter is incremented.
/// If [shouldRetryNoIncrement] returns true, the attempt counter is NOT
/// incremented. Use with caution. The intended application is for
/// false positives, where the error is not a failure of the function
/// E.g. PlatformIsAlreadyActivated
Future<T> retryWithBackoff<T>(
Future<T> Function() fn, {
int maxAttempts = 5,
Duration initialDelay = const Duration(milliseconds: 200),
bool Function(Object error)? shouldRetry,
bool Function(Object error)? shouldRetryNoIncrement,
}) async {
var attempt = 0;
var delay = initialDelay;

while (true) {
final completer = Completer<T>();

// RPC calls are scheduled microtasks, so we need to run them in a zone
// to catch errors that are thrown in the microtask queue, which would
// otherwise be unhandled.
await runZonedGuarded(
() async {
final result = await fn();
if (!completer.isCompleted) {
completer.complete(result);
}
},
(error, stack) {
if (!completer.isCompleted) {
completer.completeError(error, stack);
}
},
);

try {
return await completer.future;
} catch (e) {
if (shouldRetryNoIncrement != null && shouldRetryNoIncrement(e)) {
await Future<void>.delayed(delay);
delay *= 2;
continue;
}
attempt++;
if (attempt >= maxAttempts || (shouldRetry != null && !shouldRetry(e))) {
rethrow;
}
await Future<void>.delayed(delay);
delay *= 2;
}
}
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this isn't specific to the SDK or the pubkey manager, please move this to the types utils in the types package.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 47e472e and 8d9c80a

/// Manager responsible for handling pubkey operations across different assets
class PubkeyManager {
PubkeyManager(this._client, this._auth, this._activationManager);
Expand All @@ -12,33 +67,20 @@ class PubkeyManager {

/// Get pubkeys for a given asset, handling HD/non-HD differences internally
Future<AssetPubkeys> getPubkeys(Asset asset) async {
final finalStatus = await _activationManager.activateAsset(asset).last;
if (finalStatus.isComplete && !finalStatus.isSuccess) {
throw StateError(
'Failed to activate asset ${asset.id.name}. ${finalStatus.toJson()}',
);
}

await retryWithBackoff(() => _activationManager.activateAsset(asset).last);
final strategy = await _resolvePubkeyStrategy(asset);
return strategy.getPubkeys(asset.id, _client);
}

/// Create a new pubkey for an asset if supported
Future<PubkeyInfo> createNewPubkey(Asset asset) async {
final activationStatus = await _activationManager.activateAsset(asset).last;
if (activationStatus.isComplete && !activationStatus.isSuccess) {
throw StateError(
'Failed to activate asset ${asset.id.name}. ${activationStatus.toJson()}',
);
}

await retryWithBackoff(() => _activationManager.activateAsset(asset).last);
final strategy = await _resolvePubkeyStrategy(asset);
if (!strategy.supportsMultipleAddresses) {
throw UnsupportedError(
'Asset ${asset.id.name} does not support multiple addresses',
);
}

return strategy.getNewAddress(asset.id, _client);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ class LegacyWithdrawalManager implements WithdrawalManager {
coin: result.coin,
toAddress: result.to.first,
fee: result.fee,
kmdRewardsEligible: result.kmdRewards != null &&
kmdRewardsEligible:
result.kmdRewards != null &&
Decimal.parse(result.kmdRewards!.amount) > Decimal.zero,
),
);
Expand All @@ -67,7 +68,8 @@ class LegacyWithdrawalManager implements WithdrawalManager {
coin: parameters.asset,
toAddress: parameters.toAddress,
fee: result.fee,
kmdRewardsEligible: result.kmdRewards != null &&
kmdRewardsEligible:
result.kmdRewards != null &&
Decimal.parse(result.kmdRewards!.amount) > Decimal.zero,
),
);
Expand Down Expand Up @@ -112,7 +114,7 @@ class LegacyWithdrawalManager implements WithdrawalManager {
}

return response.details as WithdrawResult;
} catch (e) {
} catch (e, s) {
if (e is WithdrawalException) {
rethrow;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'dart:async';
import 'package:decimal/decimal.dart';
import 'package:komodo_defi_rpc_methods/komodo_defi_rpc_methods.dart';
import 'package:komodo_defi_sdk/src/_internal_exports.dart';
import 'package:komodo_defi_sdk/src/withdrawals/legacy_withdrawal_manager.dart';
import 'package:komodo_defi_types/komodo_defi_types.dart';

/// Manages asset withdrawals using task-based API
Expand Down Expand Up @@ -42,6 +43,18 @@ class WithdrawalManager {
WithdrawParameters parameters,
) async {
try {
final asset =
_assetProvider.findAssetsByConfigId(parameters.asset).single;
final isTendermintProtocol = asset.protocol is TendermintProtocol;

// Tendermint assets are not yet supported by the task-based API
// and require a legacy implementation
if (isTendermintProtocol) {
final legacyManager = LegacyWithdrawalManager(_client);
return await legacyManager.previewWithdrawal(parameters);
}

// Use task-based approach for non-Tendermint assets
final stream = (await _client.rpc.withdraw.init(
parameters,
)).watch<WithdrawStatusResponse>(
Expand Down Expand Up @@ -86,6 +99,16 @@ class WithdrawalManager {
try {
final asset =
_assetProvider.findAssetsByConfigId(parameters.asset).single;
final isTendermintProtocol = asset.protocol is TendermintProtocol;

// Tendermint assets are not yet supported by the task-based API
// and require a legacy implementation
if (isTendermintProtocol) {
final legacyManager = LegacyWithdrawalManager(_client);
yield* legacyManager.withdraw(parameters);
return;
}

final activationStatus =
await _activationManager.activateAsset(asset).last;

Expand Down
10 changes: 10 additions & 0 deletions packages/komodo_defi_types/lib/src/transactions/fee_info.dart
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,16 @@ sealed class FeeInfo with _$FeeInfo {
gasPrice: Decimal.parse(json['gas_price'].toString()),
gasLimit: json['gas_limit'] as int,
);
// Legacy withdraw API returns "Tendermint" instead of "CosmosGas",
// so add this case for compatibility and as a fallback.
case 'Tendermint':
return FeeInfo.cosmosGas(
coin: json['coin'] as String? ?? '',
// The doc sometimes shows 0.05 as a number (double),
// so we convert it to string, then parse:
gasPrice: Decimal.parse(json['amount'].toString()),
gasLimit: json['gas_limit'] as int,
);
case 'CosmosGas':
return FeeInfo.cosmosGas(
coin: json['coin'] as String? ?? '',
Expand Down