Skip to content

Commit

Permalink
fix context issue and added onModalNetworkChange subscription
Browse files Browse the repository at this point in the history
  • Loading branch information
quetool committed Apr 5, 2024
1 parent 6f4dbaf commit 4e5f332
Show file tree
Hide file tree
Showing 13 changed files with 120 additions and 44 deletions.
18 changes: 9 additions & 9 deletions example/lib/home_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,9 @@ class _MyHomePageState extends State<MyHomePage> {

// If you want to support just one chain uncomment this line and avoid using W3MNetworkSelectButton()
// _w3mService.selectChain(W3MChainPresets.chains['137']);
// TODO this shouldn't be needed
_w3mService.addListener(_updateState);
//
_w3mService.onModalConnect.subscribe(_onModalConnect);
_w3mService.onModalNetworkChange.subscribe(_onModalNetworkChange);
_w3mService.onModalDisconnect.subscribe(_onModalDisconnect);
_w3mService.onModalError.subscribe(_onModalError);
//
Expand All @@ -97,9 +96,9 @@ class _MyHomePageState extends State<MyHomePage> {

@override
void dispose() {
_w3mService.removeListener(_updateState);
//
_w3mService.onModalConnect.unsubscribe(_onModalConnect);
_w3mService.onModalNetworkChange.unsubscribe(_onModalNetworkChange);
_w3mService.onModalDisconnect.unsubscribe(_onModalDisconnect);
_w3mService.onModalError.unsubscribe(_onModalError);
//
Expand All @@ -110,12 +109,13 @@ class _MyHomePageState extends State<MyHomePage> {
super.dispose();
}

void _updateState() {
void _onModalConnect(ModalConnect? event) {
debugPrint('[ExampleApp] _onModalConnect ${event?.toString()}');
setState(() {});
}

void _onModalConnect(ModalConnect? event) {
debugPrint('[ExampleApp] _onModalConnect ${event?.toString()}');
void _onModalNetworkChange(ModalNetworkChange? event) {
debugPrint('[ExampleApp] _onModalNetworkChange ${event?.toString()}');
setState(() {});
}

Expand Down Expand Up @@ -215,9 +215,9 @@ class _ButtonsView extends StatelessWidget {
const SizedBox.square(dimension: 8.0),
Visibility(
visible: !w3mService.isConnected,
child: W3MNetworkSelectButton(service: w3mService),
child: W3MNetworkSelectButton(service: w3mService, context: context),
),
W3MConnectWalletButton(service: w3mService),
W3MConnectWalletButton(service: w3mService, context: context),
// W3MAccountButton(service: w3mService),
const SizedBox.square(dimension: 8.0),
],
Expand Down Expand Up @@ -276,7 +276,7 @@ class _ConnectedView extends StatelessWidget {
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox.square(dimension: 12.0),
W3MAccountButton(service: w3mService),
W3MAccountButton(service: w3mService, context: context),
SessionWidget(
w3mService: w3mService,
launchRedirect: () {
Expand Down
4 changes: 2 additions & 2 deletions example/lib/widgets/logger_widget.dart
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,8 @@ class _DraggableCardState extends State<DraggableCard> {
class OverlayController extends AnimatedOverlay {
OverlayController(super.duration);
OverlayEntry? _entry;
final _defaultAlign = const Alignment(0.0, -2.0);
Alignment align = const Alignment(0.0, -2.0);
final _defaultAlign = const Alignment(0.0, -30.0);
Alignment align = const Alignment(0.0, -30.0);
Animation<Alignment>? alignAnimation;

OverlayEntry createAlignOverlay(Widget child) {
Expand Down
19 changes: 10 additions & 9 deletions lib/services/analytics_service/analytics_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ class AnalyticsService implements IAnalyticsService {
_endpoint = kDebugMode
? _debugApiEndpoint
: await coreUtils.instance.getAnalyticsUrl();
loggerService.instance.i('[$runtimeType] init enabled: $_isEnabled');
loggerService.instance.p('[$runtimeType] enabled: $_isEnabled');
} catch (e, s) {
loggerService.instance.e(
loggerService.instance.p(
'[$runtimeType] init error',
error: e,
stackTrace: s,
Expand All @@ -66,11 +66,10 @@ class AnalyticsService implements IAnalyticsService {
);
final json = jsonDecode(response.body) as Map<String, dynamic>;
final enabled = json['isAnalyticsEnabled'] as bool?;
loggerService.instance.i('[$runtimeType] fetchAnalyticsConfig $enabled');
return enabled ?? false;
} catch (e, s) {
loggerService.instance.e(
'[$runtimeType] fetchAnalyticsConfig error',
loggerService.instance.p(
'[$runtimeType] fetch remote configuration error',
error: e,
stackTrace: s,
);
Expand Down Expand Up @@ -99,11 +98,13 @@ class AnalyticsService implements IAnalyticsService {
body: body,
);
final code = response.statusCode;
loggerService.instance.i('[$runtimeType] sendEvent ::$body:: $code');
_eventsController.sink.add(analyticsEvent.toMap());
if (code == 200 || code == 202) {
_eventsController.sink.add(analyticsEvent.toMap());
}
loggerService.instance.p('[$runtimeType] send event $code: $body');
} catch (e, s) {
loggerService.instance.e(
'[$runtimeType] sendEvent error',
loggerService.instance.p(
'[$runtimeType] send event error',
error: e,
stackTrace: s,
);
Expand Down
8 changes: 8 additions & 0 deletions lib/services/logger_service/i_logger_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,14 @@ abstract class ILoggerService {
StackTrace? stackTrace,
});

/// Log a message at level private.
void p(
dynamic message, {
DateTime? time,
Object? error,
StackTrace? stackTrace,
});

/// Closes the logger and releases all resources.
Future<void> close();
}
21 changes: 20 additions & 1 deletion lib/services/logger_service/logger_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@ import 'package:web3modal_flutter/web3modal_flutter.dart';

class LoggerService implements ILoggerService {
late Logger _logger;
LoggerService({required LogLevel level, bool debugMode = true}) {
late String _projectId;
LoggerService({
required LogLevel level,
required String projectId,
bool debugMode = true,
}) {
_projectId = projectId;
_logger = Logger(
level: level.toLevel(),
printer: PrettyPrinter(methodCount: null),
Expand All @@ -20,6 +26,19 @@ class LoggerService implements ILoggerService {
debugPrint('${event.message}');
}

@override
void p(
message, {
DateTime? time,
Object? error,
StackTrace? stackTrace,
}) {
// TODO fix this
if (_projectId == 'cad4956f31a5e40a00b62865b030c6f8') {
_logger.i(message, time: time, error: error, stackTrace: stackTrace);
}
}

@override
void d(
message, {
Expand Down
8 changes: 4 additions & 4 deletions lib/services/magic_service/magic_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ class MagicService implements IMagicService {
}) : _web3app = web3app,
_key = key ?? Key('magic_service') {
isEnabled.value = enabled;
loggerService.instance.p('[$runtimeType] enabled $enabled');
if (isEnabled.value) {
_webViewController = WebViewController();
_webview = WebViewWidget(
Expand Down Expand Up @@ -142,7 +143,6 @@ class MagicService implements IMagicService {
onPageFinished: (String url) async {
_onLoadCount++;
if (_onLoadCount < 2 && Platform.isAndroid) return;
loggerService.instance.d('[$runtimeType] onPageFinished $url');
await _runJavascript(_web3app.core.projectId);
await Future.delayed(Duration(milliseconds: 200));
await _webViewController.enableZoom(false);
Expand Down Expand Up @@ -321,7 +321,7 @@ class MagicService implements IMagicService {

void _onFrameMessage(JavaScriptMessage jsMessage) async {
if (Platform.isAndroid) {
loggerService.instance.i('[$runtimeType] jsMessage ${jsMessage.message}');
loggerService.instance.p('[$runtimeType] jsMessage ${jsMessage.message}');
}
try {
final frameMessage = jsMessage.toFrameMessage();
Expand Down Expand Up @@ -469,7 +469,7 @@ class MagicService implements IMagicService {
_error(SignOutErrorEvent());
}
} catch (e, s) {
loggerService.instance.e('[$runtimeType] $jsMessage', stackTrace: s);
loggerService.instance.p('[$runtimeType] $jsMessage', stackTrace: s);
}
}

Expand Down Expand Up @@ -547,7 +547,7 @@ class MagicService implements IMagicService {

void _onDebugConsoleReceived(JavaScriptConsoleMessage message) {
if (kDebugMode && Platform.isIOS) {
loggerService.instance.d('[$runtimeType] JS Console ${message.message}');
loggerService.instance.p('[$runtimeType] JS Console ${message.message}');
}
}

Expand Down
14 changes: 14 additions & 0 deletions lib/services/w3m_service/events/w3m_events.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,20 @@ class ModalConnect extends EventArgs {
}
}

class ModalNetworkChange extends EventArgs {
final String? previous;
final String current;
ModalNetworkChange({
required this.previous,
required this.current,
});

@override
String toString() {
return 'ModalNetworkChange(previous: $previous, current: $current)';
}
}

class ModalDisconnect extends EventArgs {
final String? topic;
final int? id;
Expand Down
5 changes: 3 additions & 2 deletions lib/services/w3m_service/i_w3m_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,12 @@ abstract class IW3MService with ChangeNotifier {
/// Sets up the explorer and the web3App if they already been initialized.
Future<void> init();

Future<void> openNetworks(BuildContext context);

/// Opens the modal with the provided [startWidget] (if any).
/// If none is provided, the default state will be used based on platform.
Future<void> openModal(BuildContext context, [Widget? startWidget]);

Future<void> openNetworks(BuildContext context);

/// Connects to the relay if not already connected.
/// If the relay is already connected, this does nothing.
Future<void> reconnectRelay();
Expand Down Expand Up @@ -138,6 +138,7 @@ abstract class IW3MService with ChangeNotifier {
/* EVENTS DECLARATIONS */

abstract final Event<ModalConnect> onModalConnect;
abstract final Event<ModalNetworkChange> onModalNetworkChange;
abstract final Event<ModalDisconnect> onModalDisconnect;
abstract final Event<ModalError> onModalError;
//
Expand Down
25 changes: 18 additions & 7 deletions lib/services/w3m_service/w3m_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,11 @@ class W3MService with ChangeNotifier, CoinbaseService implements IW3MService {
}
}

loggerService.instance = LoggerService(level: logLevel, debugMode: true);
loggerService.instance = LoggerService(
level: logLevel,
projectId: projectId ?? _web3App.core.projectId,
debugMode: true,
);

_web3App = web3App ??
Web3App(
Expand Down Expand Up @@ -377,7 +381,13 @@ class W3MService with ChangeNotifier, CoinbaseService implements IW3MService {
}

void _setEthChain(W3MChainInfo chainInfo, {bool logEvent = false}) async {
loggerService.instance.i('[$runtimeType] set chain ${chainInfo.namespace}');
loggerService.instance.i(
'[$runtimeType] _setEthChain ${chainInfo.namespace}',
);
onModalNetworkChange.broadcast(ModalNetworkChange(
previous: _currentSelectedChain?.namespace,
current: chainInfo.namespace,
));
_currentSelectedChain = chainInfo;

// Store the chain for when we reload the app.
Expand Down Expand Up @@ -486,12 +496,12 @@ class W3MService with ChangeNotifier, CoinbaseService implements IW3MService {
useRootNavigator: true,
anchorPoint: Offset(0, 0),
context: _context!,
builder: (context) {
final radiuses = Web3ModalTheme.radiusesOf(context);
builder: (_) {
final radiuses = Web3ModalTheme.radiusesOf(_context!);
final maxRadius = min(radiuses.radiusM, 36.0);
final borderRadius = BorderRadius.all(Radius.circular(maxRadius));
return Dialog(
backgroundColor: Web3ModalTheme.colorsOf(context).background125,
backgroundColor: Web3ModalTheme.colorsOf(_context!).background125,
shape: RoundedRectangleBorder(borderRadius: borderRadius),
clipBehavior: Clip.hardEdge,
child: ConstrainedBox(
Expand Down Expand Up @@ -750,8 +760,6 @@ class W3MService with ChangeNotifier, CoinbaseService implements IW3MService {
// If we aren't open, then we can't and shouldn't close
_close(event: false);
if (_context != null) {
// _isOpen and notify() are handled when we call Navigator.pop()
// by the open() method
Navigator.of(_context!, rootNavigator: true).pop();
analyticsService.instance.sendEvent(ModalCloseEvent(
connected: _isConnected,
Expand Down Expand Up @@ -910,6 +918,9 @@ class W3MService with ChangeNotifier, CoinbaseService implements IW3MService {
@override
final Event<ModalConnect> onModalConnect = Event();

@override
final Event<ModalNetworkChange> onModalNetworkChange = Event();

@override
final Event<ModalDisconnect> onModalDisconnect = Event();

Expand Down
14 changes: 11 additions & 3 deletions lib/widgets/w3m_account_button.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@ class W3MAccountButton extends StatefulWidget {
required this.service,
this.size = BaseButtonSize.regular,
this.avatar,
this.context,
});

final IW3MService service;
final BaseButtonSize size;
final String? avatar;
final BuildContext? context;

@override
State<W3MAccountButton> createState() => _W3MAccountButtonState();
Expand Down Expand Up @@ -68,14 +70,17 @@ class _W3MAccountButtonState extends State<W3MAccountButton> {
});
}

void _onTap() => widget.service.openModal(context);
void _onTap() => widget.service.openModal(widget.context ?? context);

void _approveSign(MagicRequestEvent? args) async {
if (args?.request != null) {
if (widget.service.isOpen) {
widgetStack.instance.popAllAndPush(ApproveTransactionPage());
} else {
widget.service.openModal(context, ApproveTransactionPage());
widget.service.openModal(
widget.context ?? context,
ApproveTransactionPage(),
);
}
}
}
Expand All @@ -84,7 +89,10 @@ class _W3MAccountButtonState extends State<W3MAccountButton> {
if (widget.service.isOpen) {
widgetStack.instance.popAllAndPush(ConfirmEmailPage());
} else {
widget.service.openModal(context, ConfirmEmailPage());
widget.service.openModal(
widget.context ?? context,
ConfirmEmailPage(),
);
}
}

Expand Down
Loading

0 comments on commit 4e5f332

Please sign in to comment.