Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[AppKit] bug fixes for social logins #38

Merged
merged 2 commits into from
Nov 20, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion packages/reown_appkit/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
## 1.2.0-beta01
## 1.2.0-beta02

- Non-EVM Chains support
- Social Logins
- Bug fixes

## 1.0.1

Expand Down
2 changes: 1 addition & 1 deletion packages/reown_appkit/example/base/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -587,7 +587,7 @@ class _MyHomePageState extends State<MyHomePage> {
},
enabled: enabled,
signOutOnDisconnect: true,
signOutOnAccountChange: true,
signOutOnAccountChange: false,
signOutOnNetworkChange: false,
// nonceRefetchIntervalMs: 300000,
// sessionRefetchIntervalMs: 300000,
Expand Down
22 changes: 9 additions & 13 deletions packages/reown_appkit/lib/modal/appkit_modal_impl.dart
Original file line number Diff line number Diff line change
Expand Up @@ -330,10 +330,6 @@ class ReownAppKitModal with ChangeNotifier implements IReownAppKitModal {
}
}

_appKit.core.logger.d('[$runtimeType] wcSessions ${wcSessions.length}');
_appKit.core.logger
.d('[$runtimeType] _currentSession ${_currentSession?.toJson()}');

// There's a session stored
if (wcSessions.isNotEmpty) {
await _storeSession(ReownAppKitModalSession(
Expand Down Expand Up @@ -1629,8 +1625,7 @@ class ReownAppKitModal with ChangeNotifier implements IReownAppKitModal {
final walletId = storedWalletId?['walletId'];
await _deleteStorage();
await _explorerService.storeRecentWalletId(walletId);
} catch (e, s) {
_appKit.core.logger.e('[$runtimeType] _cleanSession $e', stackTrace: s);
} catch (_) {
await _deleteStorage();
}
if (event) {
Expand Down Expand Up @@ -1659,6 +1654,10 @@ class ReownAppKitModal with ChangeNotifier implements IReownAppKitModal {
if (_siweService.config?.enabled != true) return;
try {
if (_siweService.signOutOnNetworkChange) {
final caip2chain = ReownAppKitModalNetworks.getCaip2Chain(
_currentSelectedChainId!,
);
await _magicService.getUser(chainId: caip2chain, isUpdate: true);
await _siweService.signOut();
_disconnectOnClose = true;
widgetStack.instance.push(ApproveSIWEPage(
Expand All @@ -1667,7 +1666,8 @@ class ReownAppKitModal with ChangeNotifier implements IReownAppKitModal {
}
} catch (e, s) {
_appKit.core.logger.e(
'[$runtimeType] _onNetworkChainRequireSIWE error: $e',
'[$runtimeType] _onNetworkChainRequireSIWE',
error: e,
stackTrace: s,
);
}
Expand Down Expand Up @@ -1833,12 +1833,8 @@ extension _EmailConnectorExtension on ReownAppKitModal {
chainId: newChainId,
);
final session = (_currentSession != null)
? _currentSession!.copyWith(
magicData: magicData,
)
: ReownAppKitModalSession(
magicData: magicData,
);
? _currentSession!.copyWith(magicData: magicData)
: ReownAppKitModalSession(magicData: magicData);
await _setSesionAndChainData(session);
onModalUpdate.broadcast(ModalConnect(session));
} catch (e, s) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,28 @@ class ReownAppKitModalSession {
MagicData? magicData,
SIWESession? siweSession,
}) {
final newCoinbaseData = _coinbaseData?.copytWith(
address: coinbaseData?.address,
chainName: coinbaseData?.chainName,
chainId: coinbaseData?.chainId,
self: coinbaseData?.self,
peer: coinbaseData?.peer,
);
final newMagicData = _magicData?.copytWith(
email: magicData?.email,
address: magicData?.address,
chainId: magicData?.chainId,
userName: magicData?.userName,
smartAccountDeployed: magicData?.smartAccountDeployed,
preferredAccountType: magicData?.preferredAccountType,
self: magicData?.self,
peer: magicData?.peer,
provider: magicData?.provider,
);
return ReownAppKitModalSession(
sessionData: sessionData ?? _sessionData,
coinbaseData: coinbaseData ?? _coinbaseData,
magicData: magicData ?? _magicData,
coinbaseData: newCoinbaseData ?? _coinbaseData,
magicData: newMagicData ?? _magicData,
siweSession: siweSession ?? _siweSession,
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ class SIWEConfig {
this.nonceRefetchIntervalMs = 300000,
this.sessionRefetchIntervalMs = 300000,
});

@override
String toString() {
return 'SIWEConfig(enabled: $enabled, signOutOnDisconnect: $signOutOnDisconnect, signOutOnAccountChange: $signOutOnAccountChange, signOutOnNetworkChange: $signOutOnNetworkChange, nonceRefetchIntervalMs: $nonceRefetchIntervalMs, sessionRefetchIntervalMs: $sessionRefetchIntervalMs)';
}
}

@freezed
Expand Down
8 changes: 4 additions & 4 deletions packages/reown_appkit/lib/modal/pages/approve_siwe.dart
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,9 @@ class _ApproveSIWEPageState extends State<ApproveSIWEPage> {
);
//
final siweSession = await _siweService.getSession();
final newSession =
_appKitModal!.session!.copyWith(siweSession: siweSession);
final newSession = _appKitModal!.session!.copyWith(
siweSession: siweSession,
);
//
widget.onSiweFinish(newSession);
//
Expand All @@ -113,8 +114,7 @@ class _ApproveSIWEPageState extends State<ApproveSIWEPage> {
}

void _handleError(String? error) {
debugPrint('[$runtimeType] _handleError $error');
String chainId = _appKitModal!.selectedChain?.chainId ?? '1';
final chainId = _appKitModal!.selectedChain?.chainId ?? '1';
_analyticsService.sendEvent(SiweAuthError(network: chainId));
GetIt.I<IToastService>().show(ToastMessage(
type: ToastType.error,
Expand Down
16 changes: 15 additions & 1 deletion packages/reown_appkit/lib/modal/pages/connet_network_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,21 @@ class _ConnectNetworkPageState extends State<ConnectNetworkPage>
final newCaip2Chain = ReownAppKitModalNetworks.getCaip2Chain(
widget.chainInfo.chainId,
);
await _magicService.switchNetwork(chainId: newCaip2Chain);
final success = await _magicService.switchNetwork(chainId: newCaip2Chain);
if (success) {
final siweEnabled = _siweService.config?.enabled != true;
final signOutOnNetworkChange = _siweService.signOutOnNetworkChange;
if (!siweEnabled || !signOutOnNetworkChange) {
final newCaip2Chain = ReownAppKitModalNetworks.getCaip2Chain(
widget.chainInfo.chainId,
);
await _magicService.getUser(
chainId: newCaip2Chain,
isUpdate: true,
);
widgetStack.instance.pop();
}
}
} else {
try {
_appKitModal!.launchConnectedWallet();
Expand Down
4 changes: 2 additions & 2 deletions packages/reown_appkit/lib/modal/pages/social_login_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ class _SocialLoginPageState extends State<SocialLoginPage> {
final caip2Chain = ReownAppKitModalNetworks.getCaip2Chain(
_service?.selectedChain?.chainId ?? '1',
);
await _magicService.getUser(chainId: caip2Chain);
await _magicService.getUser(chainId: caip2Chain, isUpdate: false);
_analyticsService.sendEvent(SocialLoginSuccess(
provider: widget.socialOption.name.toLowerCase(),
));
Expand Down Expand Up @@ -218,7 +218,7 @@ class _SocialLoginPageState extends State<SocialLoginPage> {
final caip2Chain = ReownAppKitModalNetworks.getCaip2Chain(
_service?.selectedChain?.chainId ?? '1',
);
await _magicService.getUser(chainId: caip2Chain);
await _magicService.getUser(chainId: caip2Chain, isUpdate: false);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ abstract class IMagicService {
Future<void> connectOtp({required String otp});
Future<void> syncTheme(ReownAppKitModalTheme? theme);
Future<String?> getChainId();
Future<bool> getUser({required String? chainId});
Future<bool> getUser({required String? chainId, required bool isUpdate});
Future<bool> switchNetwork({required String chainId});
Future<dynamic> request({
String? chainId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -407,19 +407,32 @@ class MagicService implements IMagicService {
}

Completer<bool> _getUserCompleter = Completer<bool>();
bool _isUpdateUser = false;
@override
Future<bool> getUser({required String? chainId}) async {
Future<bool> getUser({
required String? chainId,
required bool isUpdate,
}) async {
if (_serviceNotReady) {
throw Exception('Service is not ready');
}
//
_getUserCompleter = Completer<bool>();
await _getUser(chainId);
await _getUser(chainId, isUpdate);
return await _getUserCompleter.future;
}

Future<void> _getUser(String? chainId) async {
final message = GetUser(chainId: chainId ?? _connectionChainId).toString();
Future<void> _getUser(String? chainId, bool isUpdate) async {
_isUpdateUser = isUpdate;
_getUserCompleter = Completer<bool>();
String? cid = chainId ?? _connectionChainId;
if (cid != null && !NamespaceUtils.isValidChainId(cid)) {
try {
cid = ReownAppKitModalNetworks.getCaip2Chain(cid);
} catch (_) {
cid = null;
}
}
final message = GetUser(chainId: cid).toString();
return await _webViewController.runJavaScript('sendMessage($message)');
}

Expand Down Expand Up @@ -572,7 +585,7 @@ class MagicService implements IMagicService {
}
onMagicConnect.broadcast(MagicConnectEvent(isConnected.value));
if (isConnected.value) {
await _getUser(_connectionChainId);
await _getUser(_connectionChainId, false);
}
}
if (messageData.getSocialRedirectUriSuccess) {
Expand All @@ -581,7 +594,9 @@ class MagicService implements IMagicService {
}
// ****** CONNECT_SOCIAL_SUCCESS
if (messageData.connectSocialSuccess) {
_socialUsername = messageData.getPayloadMapKey<String?>('userName');
final username = messageData.getPayloadMapKey<String?>('userName');
final email = messageData.getPayloadMapKey<String?>('email');
_socialUsername = username ?? email;
_connectSocial.complete(true);
}
// ****** GET_FARCASTER_URI_SUCCESS
Expand All @@ -591,7 +606,9 @@ class MagicService implements IMagicService {
}
// ****** CONNECT_FARCASTER_SUCCESS
if (messageData.connectFarcasterSuccess) {
_socialUsername = messageData.getPayloadMapKey<String?>('userName');
final username = messageData.getPayloadMapKey<String?>('userName');
final email = messageData.getPayloadMapKey<String?>('email');
_socialUsername = username ?? email;
_connectFarcaster.complete(true);
}
// ****** CONNECT_EMAIL
Expand All @@ -613,7 +630,7 @@ class MagicService implements IMagicService {
if (messageData.connectOtpSuccess) {
_analyticsService.sendEvent(EmailVerificationCodePass());
step.value = EmailLoginStep.idle;
await _getUser(_connectionChainId);
await _getUser(_connectionChainId, false);
}
// ****** UPDAET_EMAIL
if (messageData.updateEmailSuccess) {
Expand All @@ -635,7 +652,7 @@ class MagicService implements IMagicService {
step.value = EmailLoginStep.idle;
setEmail(newEmail.value);
setNewEmail('');
await _getUser(_connectionChainId);
await _getUser(_connectionChainId, true);
}
// ****** SWITCH_NETWORK_SUCCESS
if (messageData.switchNetworkSuccess) {
Expand All @@ -650,11 +667,7 @@ class MagicService implements IMagicService {
));
_connectionChainId = chainId?.toString();
}
final newCaip2Chain = ReownAppKitModalNetworks.getCaip2Chain(
_connectionChainId ?? '1',
);
final success = await getUser(chainId: newCaip2Chain);
_switchNetworkCompleter.complete(success);
_switchNetworkCompleter.complete(true);
}
// ****** GET_CHAIN_ID
if (messageData.getChainIdSuccess) {
Expand Down Expand Up @@ -695,6 +708,15 @@ class MagicService implements IMagicService {
);
onMagicUpdate.broadcast(event);
_isConnectedCompleter.complete(isConnected.value);
} else if (_isUpdateUser) {
final event = MagicSessionEvent(
email: magicData.email,
userName: magicData.userName,
address: magicData.address,
chainId: magicData.chainId,
provider: magicData.provider,
);
onMagicUpdate.broadcast(event);
} else {
final session = magicData.copytWith(
peer: _peerMetadata.copyWith(
Expand All @@ -707,7 +729,10 @@ class MagicService implements IMagicService {
);
onMagicLoginSuccess.broadcast(MagicLoginEvent(session));
}
_getUserCompleter.complete(true);
// TODO this try/catch is a temporary workaround
try {
_getUserCompleter.complete(true);
} catch (_) {}
}
// ****** SIGN_OUT_SUCCESS
if (messageData.signOutSuccess) {
Expand Down Expand Up @@ -787,8 +812,8 @@ class MagicService implements IMagicService {
}
// GET_USER_ERROR
if (messageData.getUserError) {
// final message = messageData.getPayloadMapKey<String?>('message');
_error(GetUserErrorEvent());
final message = messageData.getPayloadMapKey<String?>('message');
_error(GetUserErrorEvent(message: message));
_getUserCompleter.complete(false);
}
if (messageData.switchNetworkError) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,8 @@ class ConnectOtpErrorEvent extends MagicErrorEvent {
}

class GetUserErrorEvent extends MagicErrorEvent {
GetUserErrorEvent() : super('Error getting user');
final String? message;
GetUserErrorEvent({this.message}) : super('Error getting user');
}

class SwitchNetworkErrorEvent extends MagicErrorEvent {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ class SiweService implements ISiweService {
Future<String> getNonce() async {
if (!enabled) throw Exception('siweConfig not enabled');
//
_appKit.core.logger.d('[$runtimeType] getNonce() called');
return await _siweConfig!.getNonce();
}

Expand All @@ -80,6 +81,7 @@ class SiweService implements ISiweService {
type: messageParams.type ?? CacaoHeader(t: 'eip4361'),
);

_appKit.core.logger.d('[$runtimeType] createMessage() called');
return _siweConfig!.createMessage(createMessageArgs);
}

Expand All @@ -96,6 +98,7 @@ class SiweService implements ISiweService {
final bytes = utf8.encode(message);
final encoded = hex.encode(bytes);
//
_appKit.core.logger.d('[$runtimeType] signMessageRequest() called');
if (session.sessionService.isMagic) {
return await _magicService.request(
chainId: caip2Chain,
Expand Down Expand Up @@ -139,6 +142,7 @@ class SiweService implements ISiweService {
cacao: cacao,
clientId: clientId,
);
_appKit.core.logger.d('[$runtimeType] verifyMessage() called');
final isValid = await _siweConfig!.verifyMessage(verifyArgs);
if (!isValid) {
throw ReownAppKitModalException('Error verifying SIWE signature');
Expand All @@ -151,6 +155,7 @@ class SiweService implements ISiweService {
if (!enabled) throw Exception('siweConfig not enabled');
//
try {
_appKit.core.logger.d('[$runtimeType] getSession() called');
final siweSession = await _siweConfig!.getSession();
if (siweSession == null) {
throw ReownAppKitModalException('Error getting SIWE session');
Expand All @@ -167,6 +172,7 @@ class SiweService implements ISiweService {
Future<void> signOut() async {
if (!enabled) throw Exception('siweConfig not enabled');

_appKit.core.logger.d('[$runtimeType] signOut() called');
final success = await _siweConfig!.signOut();
if (!success) {
throw ReownAppKitModalException('signOut() from siweConfig failed');
Expand All @@ -182,6 +188,7 @@ class SiweService implements ISiweService {
'aud': params.uri,
'type': params.type?.t,
});
_appKit.core.logger.d('[$runtimeType] formatMessage() called');
return _appKit.formatAuthMessage(
iss: 'did:pkh:${params.address}',
cacaoPayload: CacaoRequestPayload.fromSessionAuthPayload(authPayload),
Expand Down
2 changes: 1 addition & 1 deletion packages/reown_appkit/lib/version.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading