cake_wallet/cw_mweb/lib/cw_mweb.dart

73 lines
2.3 KiB
Dart
Raw Normal View History

2024-09-03 18:05:55 +00:00
import 'dart:io';
2024-09-05 18:02:16 +00:00
import 'dart:typed_data';
2024-09-03 18:05:55 +00:00
2024-04-20 23:20:52 +00:00
import 'package:grpc/grpc.dart';
2024-04-21 18:58:45 +00:00
import 'package:path_provider/path_provider.dart';
2024-04-20 23:20:52 +00:00
import 'cw_mweb_platform_interface.dart';
import 'mwebd.pbgrpc.dart';
class CwMweb {
2024-07-25 14:03:40 +00:00
static RpcClient? _rpcClient;
static ClientChannel? _clientChannel;
static int? _port;
2024-07-25 14:03:40 +00:00
static Future<void> _initializeClient() async {
2024-04-21 18:58:45 +00:00
final appDir = await getApplicationSupportDirectory();
_port = await CwMwebPlatform.instance.start(appDir.path);
if (_port == null || _port == 0) {
throw Exception("Failed to start server");
}
print("Attempting to connect to server on port: $_port");
2024-07-25 14:03:40 +00:00
_clientChannel = ClientChannel('127.0.0.1',
port: _port!,
2024-07-25 14:03:40 +00:00
options: const ChannelOptions(
credentials: ChannelCredentials.insecure(),
keepAlive: ClientKeepAliveOptions(permitWithoutCalls: true),
));
_rpcClient = RpcClient(_clientChannel!);
}
static Future<RpcClient> stub({int maxRetries = 3}) async {
for (int i = 0; i < maxRetries; i++) {
try {
if (_rpcClient == null) {
await _initializeClient();
}
final status = await _rpcClient!
.status(StatusRequest(), options: CallOptions(timeout: const Duration(seconds: 3)));
if (status.blockTime == 0) {
throw Exception("blockTime shouldn't be 0! (this connection is likely broken)");
}
return _rpcClient!;
} catch (e) {
print("Attempt $i failed: $e");
await stop(); // call stop so we create a new instance before retrying
await Future.delayed(const Duration(seconds: 2)); // wait before retrying
}
}
throw Exception("Failed to connect after $maxRetries attempts");
2024-07-17 16:27:31 +00:00
}
static Future<void> stop() async {
await CwMwebPlatform.instance.stop();
2024-07-25 14:03:40 +00:00
await cleanup();
}
2024-09-05 18:02:16 +00:00
static Future<String?> address(Uint8List scanSecret, Uint8List spendPub, int index) async {
2024-09-04 22:50:56 +00:00
// try {
// return (await CwMwebPlatform.instance.address(scan, spendPub, index))!;
// } catch (e) {
// print("error generating address!: $e");
// }
return CwMwebPlatform.instance.address(scanSecret, spendPub, index);
}
2024-07-25 14:03:40 +00:00
static Future<void> cleanup() async {
await _clientChannel?.terminate();
_rpcClient = null;
_clientChannel = null;
_port = null;
2024-04-20 23:20:52 +00:00
}
}