Usage of PnP Flutter SDK
Logging in a User
login(LoginParams)
Trigger login flow will navigate the user to a browser model allowing the user to login into the
service. You can pass in the supported providers to the login method for specific social logins such
as GOOGLE, APPLE, FACEBOOK, etc., and do whitelabel login. The login
function takes in
LoginParams
as a required input.
Arguments
LoginParams
- Table
- Class
Parameter | Description |
---|---|
loginProvider | It sets the oAuth login method to be used. You can use any of the supported values are google , facebook , reddit , discord , twitch , apple , line , github , kakao , linkedin , twitter , email_passwordless , jwt , sms_passwordless , email_password , and farcaster . |
extraLoginOptions? | It can be used to set the OAuth login options for corresponding loginProvider . For instance, you'll need to pass user's email address as. Default value for the field is null , and it accepts ExtraLoginOptions as a value. |
redirectUrl? | Url where user will be redirected after successfull login. By default user will be redirected to same page where login will be initiated. Default value for the field is null |
appState? | It can be used to keep track of the app state when user will be redirected to app after login. Default is null , and accepts String as a value. |
mfaLevel? | Customize the MFA screen shown to the user during OAuth authentication. Default value for field is MFALevel.DEFAULT , which shows MFA screen every 3rd login. It accepts MFALevel as a value. |
dappShare? | Custom verifier logins can get a dapp share returned to them post successful login. This is useful if the dapps want to use this share to allow users to login seamlessly. It accepts String as a value. |
curve? | It will be used to determine the public key encoded in the jwt token which returned in getUserInfo function after user login. This parameter won't change format of private key returned by We3Auth. Private key returned by getPrivKey is always secp256k1. To get the ed25519 key you can use getEd25519PrivKey method. The default value is Curve.secp256k1 . |
class LoginParams {
final Provider loginProvider;
final String? dappShare;
final Curve? curve;
final ExtraLoginOptions? extraLoginOptions;
final Uri? redirectUrl;
final String? appState;
final MFALevel? mfaLevel;
LoginParams({
required this.loginProvider,
this.dappShare,
this.curve,
this.extraLoginOptions,
this.redirectUrl,
this.appState,
this.mfaLevel,
});
Map<String, dynamic> toJson() => {
"loginProvider": loginProvider.name,
"dappShare": dappShare,
"curve": curve?.name,
"extraLoginOptions": extraLoginOptions?.toJson(),
"redirectUrl": redirectUrl?.toString(),
"appState": appState,
"mfaLevel": mfaLevel?.type,
};
}
enum Provider {
google,
facebook,
reddit,
discord,
twitch,
github,
apple,
linkedin,
twitter,
line,
kakao,
email_passwordless,
jwt,
sms_passwordless,
farcaster,
}
getPrivkey()
Use getPrivkey() to get the private key of the user. The method returns an EVM compatible private key which can be used to sign transactions on EVM compatible chains.
getEd25519PrivKey()
Use getEd25519PrivKey() to get the Ed25519 private key of the user. This private key can be used to sign transactions on Solana.
getUserInfo()
Use getUserInfo() to get the user info of the user.
UserInfo Response
{
"userInfo": {
"email": "w3a-heroes@web3auth.com",
"name": "Web3Auth Heroes",
"profileImage": "https://lh3.googleusercontent.com/a/Ajjjsdsmdjmnm...",
"verifier": "torus",
"verifierId": "w3a-heroes@web3auth.com",
"typeOfLogin": "google",
"aggregateVerifier": "w3a-google-sapphire",
"dappShare": "", // 24 words of seed phrase will be sent only incase of custom verifiers
"idToken": "<jwtToken issued by Web3Auth>",
"oAuthIdToken": "<jwtToken issued by OAuth Provider>", // will be sent only incase of custom verifiers
"oAuthAccessToken": "<accessToken issued by OAuth Provider>", // will be sent only incase of custom verifiers
"isMfaEnabled": false // Returns whether the user has enabled MFA or not
}
}
- Discord
- Twitch
- Email Passwordless
- SMS Passwordless
- Farcaster
- JWT
Future<void> initWeb3Auth() async {
Uri redirectUrl;
if (Platform.isAndroid) {
redirectUrl = Uri.parse('{SCHEME}://{HOST}/auth');
// w3a://com.example.w3aflutter/auth
} else if (Platform.isIOS) {
redirectUrl = Uri.parse('{bundleId}://auth');
// com.example.w3aflutter://openlogin
} else {
throw UnKnownException('Unknown platform');
}
await Web3AuthFlutter.init(Web3AuthOptions(
clientId: "WEB3AUTH_CLIENT_ID",
network: Network.sapphire_mainnet,
redirectUrl: redirectUrl,
));
await Web3AuthFlutter.initialize();
}
// Login
final Web3AuthResponse response = await Web3AuthFlutter.login(
LoginParams(loginProvider: Provider.google)
);
Future<void> initWeb3Auth() async {
Uri redirectUrl;
if (Platform.isAndroid) {
redirectUrl = Uri.parse('{SCHEME}://{HOST}/auth');
// w3a://com.example.w3aflutter/auth
} else if (Platform.isIOS) {
redirectUrl = Uri.parse('{bundleId}://auth');
// com.example.w3aflutter://openlogin
} else {
throw UnKnownException('Unknown platform');
}
await Web3AuthFlutter.init(Web3AuthOptions(
clientId: "WEB3AUTH_CLIENT_ID",
network: Network.sapphire_mainnet,
redirectUrl: redirectUrl,
));
await Web3AuthFlutter.initialize();
}
// Login
final Web3AuthResponse response = await Web3AuthFlutter.login(
LoginParams(loginProvider: Provider.facebook)
);
Future<void> initWeb3Auth() async {
Uri redirectUrl;
if (Platform.isAndroid) {
redirectUrl = Uri.parse('{SCHEME}://{HOST}/auth');
// w3a://com.example.w3aflutter/auth
} else if (Platform.isIOS) {
redirectUrl = Uri.parse('{bundleId}://auth');
// com.example.w3aflutter://openlogin
}
await Web3AuthFlutter.init(Web3AuthOptions(
clientId: "WEB3AUTH_CLIENT_ID",
network: Network.sapphire_mainnet,
redirectUrl: redirectUrl,
));
await Web3AuthFlutter.initialize();
}
// Login
final Web3AuthResponse response = await Web3AuthFlutter.login(
LoginParams(loginProvider: Provider.discord)
);
Future<void> initWeb3Auth() async {
Uri redirectUrl;
if (Platform.isAndroid) {
redirectUrl = Uri.parse('{SCHEME}://{HOST}/auth');
// w3a://com.example.w3aflutter/auth
} else if (Platform.isIOS) {
redirectUrl = Uri.parse('{bundleId}://auth');
// com.example.w3aflutter://openlogin
} else {
throw UnKnownException('Unknown platform');
}
await Web3AuthFlutter.init(Web3AuthOptions(
clientId: "WEB3AUTH_CLIENT_ID",
network: Network.sapphire_mainnet,
redirectUrl: redirectUrl,
));
await Web3AuthFlutter.initialize();
}
// Login
final Web3AuthResponse response = await Web3AuthFlutter.login(
LoginParams(loginProvider: Provider.twitch)
);
Future<void> initWeb3Auth() async {
final additionalParams = HashMap<String, String>();
// Default is 'code'
additionalParams['flow_type'] = "link";
Uri redirectUrl;
if (Platform.isAndroid) {
redirectUrl = Uri.parse('{SCHEME}://{HOST}/auth');
// w3a://com.example.w3aflutter/auth
} else if (Platform.isIOS) {
redirectUrl = Uri.parse('{bundleId}://auth');
// com.example.w3aflutter://openlogin
} else {
throw UnKnownException('Unknown platform');
}
await Web3AuthFlutter.init(Web3AuthOptions(
clientId: "WEB3AUTH_CLIENT_ID",
network: Network.testnet,
redirectUrl: redirectUrl,
));
await Web3AuthFlutter.initialize();
}
// Login
final Web3AuthResponse response = await Web3AuthFlutter.login(
LoginParams(
loginProvider: Provider.email_passwordless,
extraLoginOptions: ExtraLoginOptions(
login_hint: "hello@web3auth.io",
additionalParams: additionalParams
)
),
);
Future<void> initWeb3Auth() async {
Uri redirectUrl;
if (Platform.isAndroid) {
redirectUrl = Uri.parse('{SCHEME}://{HOST}/auth');
// w3a://com.example.w3aflutter/auth
} else if (Platform.isIOS) {
redirectUrl = Uri.parse('{bundleId}://auth');
// com.example.w3aflutter://openlogin
} else {
throw UnKnownException('Unknown platform');
}
await Web3AuthFlutter.init(
Web3AuthOptions(
clientId: "WEB3AUTH_CLIENT_ID",
network: Network.sapphire_mainnet,
redirectUrl: redirectUrl,
),
);
}
// Login
final Web3AuthResponse response = await Web3AuthFlutter.login(
LoginParams(loginProvider: Provider.sms_passwordless,
extraLoginOptions: ExtraLoginOptions(
// The phone number should be in format of +{country_code}-{phone_number}
login_hint: "+91-9911223311",
),
),
);
Future<void> initWeb3Auth() async {
Uri redirectUrl;
if (Platform.isAndroid) {
redirectUrl = Uri.parse('{SCHEME}://{HOST}/auth');
// w3a://com.example.w3aflutter/auth
} else if (Platform.isIOS) {
redirectUrl = Uri.parse('{bundleId}://auth');
// com.example.w3aflutter://openlogin
} else {
throw UnKnownException('Unknown platform');
}
await Web3AuthFlutter.init(Web3AuthOptions(
clientId: "WEB3AUTH_CLIENT_ID",
network: Network.sapphire_mainnet,
redirectUrl: redirectUrl,
));
await Web3AuthFlutter.initialize();
}
// Login
final Web3AuthResponse response = await Web3AuthFlutter.login(
LoginParams(loginProvider: Provider.farcaster)
);
Future<void> initPlatformState() async {
final loginConfig = new HashMap<String, LoginConfigItem>();
loginConfig['jwt'] = LoginConfigItem(
// get it from web3auth dashboard
verifier: "verifier-name",
typeOfLogin: TypeOfLogin.jwt,
// Auth0, Google, Facebook, Twitch, Discord or Web3Auth Client ID
client_id: "CLIENT_ID",
);
Uri redirectUrl;
if (Platform.isAndroid) {
redirectUrl = Uri.parse('{SCHEME}://{HOST}/auth');
// w3a://com.example.w3aflutter/auth
} else if (Platform.isIOS) {
redirectUrl = Uri.parse('{bundleId}://auth');
// com.example.w3aflutter://openlogin
} else {
throw UnKnownException('Unknown platform');
}
await Web3AuthFlutter.init(Web3AuthOptions(
clientId: "WEB3AUTH_CLIENT_ID",
network: Network.testnet,
redirectUrl: redirectUrl,,
loginConfig: loginConfig
));
await Web3AuthFlutter.initialize();
}
// Login
final Web3AuthResponse response = await Web3AuthFlutter.login(
LoginParams(
loginProvider: Provider.jwt,
extraLoginOptions: ExtraLoginOptions(
id_token: "YOUR_JWT_TOKEN",
)
)
);
Logging out a user
logout()
This method will logout the user and remove the session id from the device. The user will need to login again to use the dApp next time the dApp is opened.
await Web3AuthFlutter.logout();
Get started with a sample app found here.
Enable MFA for a user
The enableMFA
method is used to trigger MFA setup flow for users. The method takes LoginParams
which will used during custom verifiers. If you are using default login providers, you don't need to
pass LoginParams
. If you are using custom jwt verifiers, you need to pass the JWT token in
loginParams
as well.
- Default Verifier
- Custom JWT Verifier
try {
await Web3AuthFlutter.enableMFA();
} on UserCancelledException {
log("User cancelled.");
} catch(e) {
log("Unknown exception occurred");
}
try {
final loginParams = LoginParams(
loginProvider: Provider.jwt,
extraLoginOptions: ExtraLoginOptions(
id_token: "YOUR_JWT_TOKEN",
),
);
await Web3AuthFlutter.enableMFA(loginParams);
} on UserCancelledException { log("User cancelled."); } catch(e) { log("Unknown exception
occurred"); }
Triggering Login exceptions
The setCustomTabsClosed
method can be used to trigger login exceptions for Android. For iOS, you
don't need this method to trigger the login exceptions. The Android SDK uses the custom tabs and
from current implementation of chrome custom tab, it's not possible to add a listener directly to
chrome custom tab close button and trigger login exceptions.
Hence, it's necessary to use setCustomTabsClosed
method in your login screen to trigger
exceptions.
Usage
class LoginScreen extends State<T> with WidgetsBindingObserver {
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
void dispose() {
super.dispose();
WidgetsBinding.instance.removeObserver(this);
}
void didChangeAppLifecycleState(final AppLifecycleState state) {
// This is important to trigger the user cancellation on Android.
if (state == AppLifecycleState.resumed) {
Web3AuthFlutter.setCustomTabsClosed();
}
}
Widget build(BuildContext context) {
// Your UI code
}
Future<void> _login() async {
try {
await Web3AuthFlutter.login(LoginParams(loginProvider: Provider.google));
} on UserCancelledException {
log("User cancelled.");
} on UnKnownException {
log("Unknown exception occurred");
} catch (e) {
log(e.toString());
}
}
}
Launch Wallet Services
The launchWalletServices
method launches a WebView which allows you to use the templated wallet UI
services. The method takes ChainConfig
as the required input. Wallet Services is currently only
available for EVM chains.
Access to Wallet Services is gated. You can use this feature in the development environment for free. The minimum pricing plan to use this feature in a production environment is the Scale Plan.
Arguments
ChainConfig
- Table
- Class
Parameter | Description |
---|---|
chainNamespace | Custom configuration for your preferred blockchain. As of now only EVM supported. Default value is ChainNamespace.eip155 . |
decimals? | Number of decimals for the currency ticker. Default value is 18, and accepts int as value. |
blockExplorerUrl? | Blockchain's explorer URL. (eg: https://etherscan.io ) |
chainId | The chain id of the selected blockchain in hex String . |
displayName? | Display Name for the chain. |
logo? | Logo for the selected chainNamespace & chainId . |
rpcTarget | RPC Target URL for the selected chainNamespace & chainId . |
ticker? | Default currency ticker of the network (e.g: ETH ) |
tickerName? | Name for currency ticker (e.g: Ethereum ) |
class ChainConfig {
final ChainNamespace chainNamespace;
final int? decimals;
final String? blockExplorerUrl;
final String chainId;
final String? displayName;
final String? logo;
final String rpcTarget;
final String? ticker;
final String? tickerName;
ChainConfig({
this.chainNamespace = ChainNamespace.eip155,
this.decimals = 18,
this.blockExplorerUrl,
required this.chainId,
this.displayName,
this.logo,
required this.rpcTarget,
this.ticker,
this.tickerName,
});
Map<String, dynamic> toJson() {
return {
'chainNamespace': chainNamespace.name,
'decimals': decimals,
'blockExplorerUrl': blockExplorerUrl,
'chainId': chainId,
'displayName': displayName,
'logo': logo,
'rpcTarget': rpcTarget,
'ticker': ticker,
'tickerName': tickerName
};
}
}
Usage
try {
await Web3AuthFlutter.launchWalletServices(
ChainConfig(
chainId: "0x1",
rpcTarget: "https://mainnet.infura.io/v3/$key",
),
);
} on UserCancelledException {
log("User cancelled.");
} catch(e) {
log("Unknown exception occurred");
}
Request signature
The request
method facilitates the use of templated transaction screens for signing transactions.
Upon successful completion, you can retrieve the signature for the request using the
getSignResponse
static method.
Please check the list of JSON RPC methods, noting that the request method currently supports only the signing methods.
Arguments
Arguments | Description |
---|---|
chainConfig | Defines the chain to be used for signature. |
method | JSON RPC method name in String . Currently, the request method only supports the singing methods. |
requestParams | Parameters for the corresponding method. The parameters should be in the list and correct sequence. Take a look at RPC methods to know more. |
Usage
try {
List<dynamic> params = [];
// Message to be signed
params.add("Hello, Web3Auth from Flutter!");
// User's EOA address
params.add("<User Address in Hex>");
await Web3AuthFlutter.request(
ChainConfig(
chainId: "0x1",
rpcTarget: "https://mainnet.infura.io/v3/$key",
),
"personal_sign",
params,
);
} on UserCancelledException {
log("User cancelled.");
} catch(e) {
log("Unknown exception occurred");
}
final signResponse = await Web3AuthFlutter.getSignResponse();
log(signResponse.toString())