Skip to content

Instantly share code, notes, and snippets.

@elkattan
Last active January 10, 2023 20:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save elkattan/1168831889c1a9ac3c6fdf72a4078505 to your computer and use it in GitHub Desktop.
Save elkattan/1168831889c1a9ac3c6fdf72a4078505 to your computer and use it in GitHub Desktop.
Moralis wallet authentication using flutter and Parse SDK
import 'dart:typed_data';
import 'package:parse_server_sdk_flutter/parse_server_sdk.dart';
import 'package:web3dart/crypto.dart';
import 'package:web3dart/web3dart.dart';
final Wallet? wallet = Wallet(); // User wallet should be initialized
authenticate() async {
if (wallet == null) {
throw Exception('Wallet is not initialized');
}
// Address is required for authentication
final address = wallet.privateKey.address;
// Grabbing Moralis servicer time
final getServerTime = ParseCloudFunction('getServerTime');
final serverTimeResponse = await getServerTime.execute();
final serverTime = Map<String, dynamic>.from(serverTimeResponse.result)['dateTime'];
// Grabbing Moralis Application ID, should be provided in Parse().initialize()
final appId = ParseCoreData().applicationId;
// Defining your signing message
final anyMessageToSign = "Welcome to my awesome DApp";
final data = "$anyMessageToSign\n\nId: $appId:$serverTime";
// Using web3dart .signPersonalMessage(...) to sign the message
// this methood retuns a EIP-191 compliant signeture as ethersJs .signMessage(...)
// Check https://docs.ethers.io/v5/api/signer/#Signer-signMessage
final signedMessage = await wallet.privateKey
.signPersonalMessage(Uint8List.fromList(data.codeUnits));
final signature = bytesToHex(signedMessage, include0x: true);
// Composing the payload moralis expect
final authData = {
"id": address!.hex,
"signature": signature,
"data": data,
};
// Logging with moralis custom authentication
final response = await ParseUser.loginWith("moralisEth", authData);
// In case of errors you can check the `response`
if (!response.success) {
throw Exception('Authentication failed');
}
// According to ParsePlatform docs in case loginWith was a success ParseUser.currentUser()
// Will hold the authenticated user
final user = ParseUser.currentUser() as ParseObject;
// Setting up the user in case of registration as Moralis JS SDK does
user.setACL(user);
user.setAddAllUnique('accounts', [address.hex]);
user.set('ethAddress', address.hex);
await user.save();
return user;
}
@4xMafole
Copy link

Good gist it helped out!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment