moonx_flutter 0.1.0-beta.7
moonx_flutter: ^0.1.0-beta.7 copied to clipboard
MoonX embedded wallets and authentication for Flutter apps on iOS and Android. Headless, so your app owns the UI, with native passkeys and MPC signing.
moonx_flutter #
Headless MoonX SDK for Flutter (iOS and Android). It follows the behavior of
@moon-x/react-native-sdk, and CI compares the two on every change.
The SDK hosts the MoonX secure iframe in a hidden WebView, the same model as
the React Native SDK. Refresh tokens, the wallet data-encryption key, and MPC
keyshares stay inside that WebView. getSessionTokens() explicitly returns
access and identity tokens to Dart. Your app owns every
screen. The only UI the SDK shows is a sheet around the WebView, used for key
export and for an hCaptcha challenge that escalates to interactive.
Install #
flutter pub add moonx_flutter
Requirements #
| Minimum | Tested | |
|---|---|---|
| Flutter / Dart | 3.35.0 / 3.9.0 | 3.35.0 and 3.47.5 |
| iOS | 16.0 | 16.0, 16.4, 17.5, 18.5, 18.6, 26.5 simulators |
| Android OS | API 27 (Android 8.1) | API 27, 35, 36, 37 emulators |
| Android WebView | Chromium 111 | 124 on API 27, and each image's own WebView |
| Android compile SDK | 36 (lowest tested) | 36 |
| Android Gradle Plugin | 8.x or 9.x | 8.13.2 and 9.1.0 |
| Native Android passkeys | API 28 |
The WebView comes from Flutter's webview_flutter. On iOS, every dependency
supports Swift Package Manager. On Android, the package includes a small Java
plugin that reads the WebView version and keeps the app alive if the WebView
renderer crashes.
Android's OS version does not determine its WebView version. On older
devices, users update Android System WebView through the Play Store. If the
installed WebView is too old, the SDK reports unsupported_webview instead
of loading the wallet page (see Startup failures).
Full guides: MoonX Flutter SDK documentation.
Set up #
final moonx = MoonXClient(
publishableKey: 'moon_pk_live_...',
config: const MoonXConfig(oauthRedirectUri: 'myapp://oauth-callback'),
);
MaterialApp(
builder: (context, child) => MoonXHost(client: moonx, child: child!),
home: const HomeScreen(),
);
MoonXClient is a ChangeNotifier. Listen to it for ready,
initializationError, sessionStatus, isAuthenticated, user and
revalidatedAt.
Use exactly one MoonXHost per app. Put it in MaterialApp.builder, above
the Navigator, so the export and CAPTCHA sheet covers every route. A host
inside one route is covered by any route pushed on top of it.
A secret key (moon_sk_*) passed as the publishable key throws before any
WebView loads.
Session status #
ready means the WebView answers. It does not mean session restoration is
complete. Use sessionStatus to tell restoration apart from a confirmed
sign-out:
| Status | Meaning |
|---|---|
SessionStatus.restoring |
The first session check or a revalidation is pending. |
SessionStatus.authenticated |
A check or login confirmed a session. The profile can still be loading. |
SessionStatus.signedOut |
Logout succeeded or repeated checks confirmed no session. |
SessionStatus.error |
The bounded restoration attempts failed. isAuthenticated and user keep their last confirmed values. |
sessionError holds the last exhausted restoration error, or null.
retrySession() starts a new bounded check once the WebView is ready.
Repeated calls during a check share it, and calls during an interactive
sign-in wait until it finishes. It does not reload the WebView or retry
signing or other mutations. revalidatedAt advances only when a check or
login confirms the session state, so a network failure never reads as a
sign-out.
ListenableBuilder(
listenable: moonx,
builder: (context, _) {
if (!moonx.ready) return const Text('Connecting...');
if (moonx.isAuthenticated) return const WalletScreen();
return switch (moonx.sessionStatus) {
SessionStatus.restoring => const Text('Restoring session...'),
SessionStatus.error => TextButton(
onPressed: moonx.retrySession,
child: const Text('Retry'),
),
_ => const SignInScreen(),
};
},
);
Keep sessions when the OS clears WebView storage #
iOS can delete the hidden WebView's storage, including the refresh token,
while the session is still valid on the server. Users then appear signed out
after reopening the app. Pass sessionResumeStorage to restore such sessions
silently:
final moonx = MoonXClient(
publishableKey: 'moon_pk_live_...',
sessionResumeStorage: SecureKvStorage(
storage: const FlutterSecureStorage(
iOptions: IOSOptions(
accessibility: KeychainAccessibility.unlocked_this_device,
),
),
),
);
The SDK stores a P-256 private key there. After each login it binds the
key's public half to the session. When a later check finds the WebView's
session gone, it signs a single-use server challenge with the key and the
iframe stores the restored session. sessionStatus stays restoring
throughout, so the user never sees a sign-out.
Treat the stored key as a credential. Anything that can read it, including your app's own Dart code and its dependencies, can resume the bound session until the session expires or is revoked. Unlike the web SDK's non-extractable WebCrypto key, the Flutter SDK holds the raw key.
- Use device-only storage:
KeychainAccessibility.unlocked_this_device(resume runs while the app is in use), no iCloud Keychain sync, and exclude theflutter_secure_storagepreferences from Android Auto Backup. - A resumed session keeps its original expiry. Resume never extends it.
- Logout deletes the key before revoking the session, and nothing resumes again until the next successful login, even if the logout itself fails. Signing in replaces the recorded session first, so an interrupted account switch never resumes the previous account.
- A key left in the Keychain by a previous installation never resumes: the
SDK ties it to this installation through
shared_preferences, which an uninstall clears. - Session resume must be enabled for the app. Without it, the key is never bound and nothing changes.
Startup failures #
Check initializationError before showing a connecting screen or enabling SDK actions.
On Android, MoonXHost checks the installed WebView provider before loading the wallet page.
The check has a three-second timeout.
| Error code | Meaning | Next step |
|---|---|---|
unsupported_webview |
The installed WebView is older than Chromium 111. | Update Android System WebView or Chrome, then reopen the app. |
webview_version_unavailable |
The provider lookup failed or returned no usable version. | Check that an enabled WebView provider is installed, then reopen the app. |
webview_load_failed |
The native WebView rejected the initial load command. | Reopen the app and check the iframe configuration. |
webview_return_failed |
The home page did not respond after closing the export sheet. | Reopen the app before another SDK action. The export result keeps its original outcome. |
These failures keep ready false. Transport calls reject with the same MoonXException instead of waiting for a response.
The SDK does not install or update a device's WebView provider.
Use #
// Email one-time code.
await moonx.sendCode(email: 'ada@example.com');
await moonx.loginWithCode(code: '123456');
// Google / Apple through ASWebAuthenticationSession / Custom Tabs.
await moonx.loginWithOAuth(OAuthProvider.google);
// A passkey, optionally creating wallets off the same prompt.
await moonx.passkeys.register(createWallets: const [
RegisterCreateWalletSpec(WalletChain.ethereum),
]);
final wallet = await moonx.wallets.create(WalletChain.solana);
// Or reuse the first existing wallet, creating one only if there is none.
final reused = await moonx.wallets.findOrCreate(WalletChain.solana);
final signature = await moonx.solana.signMessage(message: 'hi', wallet: wallet);
final hash = await moonx.ethereum.sendTransaction(
transaction: {'to': '0x…', 'value': '0.01', 'chainId': 8453},
wallet: evmWallet,
rpcUrl: 'https://mainnet.base.org',
);
// Shows the key inside the secure sheet; resolves when the user closes it.
final result = await moonx.wallets.exportKey(wallet);
Method groups: wallets, passkeys, accountRecovery, ephemeralSigners,
funding, ethereum, solana, tron, bitcoin. Session methods live on
the client itself: logout, getUser, getSessionTokens,
getPresenceToken and getAppConfig. Errors are MoonXExceptions whose
message uses the same codes as the web and React Native SDKs, for example
passkey_required and no_session.
wallets.create always creates a new wallet. wallets.findOrCreate returns
the first existing wallet for the chain (Bitcoin matches on addressType,
default p2tr) or creates one, and shares concurrent calls for the same login.
It rejects with wallets_unavailable instead of creating when the wallet list
can't be read, and with session_changed if a different login replaces the
session mid-call. After session_changed, a wallet may already exist on the
earlier login: confirm the account, then retry with findOrCreate, not
create.
KMS (identity-backed) users #
If your app lets users hold wallets without a passkey, register a prompt for the email code that confirms lifecycle operations (passkey removal, key export):
registerPresenceOtpCodeProvider(publishableKey, (request) => showCodeSheet(request));
Platform setup #
iOS. Add an Associated Domains entitlement for your WebAuthn RP ID
(webcredentials:<rp_id>) and host the apple-app-site-association file on
that domain. For OAuth, no Info.plist entry is needed.
Android. Serve /.well-known/assetlinks.json on your RP ID with the app's
signing certificate, and add the fingerprint to the app's
webauthn.android_apk_key_hashes setting in MoonX. For OAuth, declare
flutter_web_auth_2's CallbackActivity with the scheme of
MoonXConfig.oauthRedirectUri inside <application>:
<activity
android:name="com.linusu.flutter_web_auth_2.CallbackActivity"
android:exported="true">
<intent-filter android:label="flutter_web_auth_2">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" />
</intent-filter>
</activity>
Testing your app #
package:moonx_flutter/testing.dart exports SoftwarePasskeys, an in-memory
WebAuthn authenticator. It lets integration tests run real passkey
ceremonies against a MoonX environment without the OS prompt. Do not use it
in production builds.
Working on the SDK itself? See CONTRIBUTING.md in the package.
Not included #
- WalletConnect transport.
ExternalWalletsControllerprovides the orchestration. ImplementExternalWalletConnectorwith the Reown Flutter SDK. - UI components. Like the React Native SDK, this package is headless.