Created
April 4, 2023 11:14
-
-
Save rtang03/5e84dc4332159ce4c70fcc7df6002fd0 to your computer and use it in GitHub Desktop.
web3auth in flutter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:collection'; | |
import 'dart:io'; | |
import 'package:flutter/material.dart'; | |
import 'package:web3auth_flutter/enums.dart'; | |
import 'package:web3auth_flutter/input.dart'; | |
import 'package:web3auth_flutter/output.dart'; | |
import 'dart:async'; | |
import 'package:web3auth_flutter/web3auth_flutter.dart'; | |
// ignore: depend_on_referenced_packages | |
import 'package:http/http.dart'; | |
import 'package:web3dart/web3dart.dart'; | |
import 'package:shared_preferences/shared_preferences.dart'; | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatefulWidget { | |
@override | |
MyAppState createState() => MyAppState(); | |
} | |
class MyAppState extends State<MyApp> { | |
String _result = ''; | |
bool logoutVisible = false; | |
String rpcUrl = 'https://rpc.ankr.com/eth_goerli'; | |
@override | |
void dispose() { | |
super.dispose(); | |
} | |
@override | |
void initState() { | |
super.initState(); | |
initPlatformState(); | |
} | |
Future<void> initPlatformState() async { | |
final themeMap = HashMap<String, String>(); | |
themeMap['primary'] = "#eb5424"; | |
Uri redirectUrl; | |
if (Platform.isAndroid) { | |
redirectUrl = Uri.parse('w3a://com.example.myfirstflutter/auth'); | |
} else if (Platform.isIOS) { | |
redirectUrl = Uri.parse('com.example.myfirstflutter://openlogin'); | |
} else { | |
throw UnKnownException('Unknown platform'); | |
} | |
final loginConfig = HashMap<String, LoginConfigItem>(); | |
loginConfig['jwt'] = LoginConfigItem( | |
verifier: "auth0-livi-project", | |
typeOfLogin: TypeOfLogin.jwt, | |
name: "Web3Auth Flutter Auth0 Example", | |
clientId: "lM6HM2jZhsUD8YnTJkM2eVVGHvONY8wT"); // auth0 | |
await Web3AuthFlutter.init(Web3AuthOptions( | |
clientId: | |
"BD3kNB72TCWXf1HFq-aKCrgL9KqJGhavj_fXZjyFZSj9bdaTjLweKDxoKoCCwTiv7t74An2h6DVjvjyw8uqrEl8", | |
network: Network.testnet, | |
redirectUrl: redirectUrl, | |
whiteLabel: WhiteLabelData( | |
dark: false, | |
name: "Web3Auth Flutter Auth0 Example", | |
theme: themeMap), | |
loginConfig: loginConfig)); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
home: Scaffold( | |
appBar: AppBar( | |
title: const Text('Web3Auth Flutter Auth0 Example'), | |
), | |
body: SingleChildScrollView( | |
child: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
const Padding( | |
padding: EdgeInsets.all(8.0), | |
), | |
Visibility( | |
visible: !logoutVisible, | |
child: Column( | |
children: [ | |
const Icon(Icons.flutter_dash, | |
size: 80, color: Color(0xFF1389fd)), | |
const SizedBox( | |
height: 40, | |
), | |
const Text('Web3Auth', | |
style: TextStyle( | |
fontWeight: FontWeight.bold, | |
fontSize: 36, | |
color: Color(0xFF0364ff))), | |
const SizedBox(height: 10), | |
const Text( | |
'Welcome to Web3Auth Flutter Auth0 Example', | |
style: TextStyle(fontSize: 14), | |
), | |
const SizedBox(height: 20), | |
const Text('Login With', style: TextStyle(fontSize: 12)), | |
const SizedBox(height: 20), | |
ElevatedButton( | |
style: ElevatedButton.styleFrom( | |
backgroundColor: const Color(0xFFeb5424)), | |
onPressed: _login(_withAuth0), | |
child: const Text('Auth0')) | |
], | |
), | |
), | |
Visibility( | |
// ignore: sort_child_properties_last | |
child: Column( | |
children: [ | |
Center( | |
child: ElevatedButton( | |
style: ElevatedButton.styleFrom( | |
backgroundColor: Colors.red[600]), | |
onPressed: _logout(), | |
child: Column( | |
children: const [Text('Logout')], | |
), | |
)), | |
const Text( | |
'Blockchain calls', | |
style: TextStyle(fontSize: 20), | |
), | |
ElevatedButton( | |
style: ElevatedButton.styleFrom( | |
backgroundColor: const Color.fromARGB( | |
255, 195, 47, 233) // This is what you need! | |
), | |
onPressed: _getAddress, | |
child: const Text('Get Address')), | |
ElevatedButton( | |
style: ElevatedButton.styleFrom( | |
backgroundColor: const Color.fromARGB( | |
255, 195, 47, 233) // This is what you need! | |
), | |
onPressed: _getBalance, | |
child: const Text('Get Balance')), | |
ElevatedButton( | |
style: ElevatedButton.styleFrom( | |
backgroundColor: const Color.fromARGB( | |
255, 195, 47, 233) // This is what you need! | |
), | |
onPressed: _sendTransaction, | |
child: const Text('Send Transaction')), | |
], | |
), | |
visible: logoutVisible, | |
), | |
Padding( | |
padding: const EdgeInsets.all(8.0), | |
child: Text(_result), | |
) | |
], | |
))))); | |
} | |
VoidCallback _login(Future<Web3AuthResponse> Function() method) { | |
return () async { | |
try { | |
final Web3AuthResponse response = await method(); | |
final prefs = await SharedPreferences.getInstance(); | |
await prefs.setString('privateKey', response.privKey.toString()); | |
setState(() { | |
_result = response.toString(); | |
logoutVisible = true; | |
}); | |
} on UserCancelledException { | |
print("User cancelled"); | |
} on UnKnownException { | |
print("Unknown exception occurred"); | |
} | |
}; | |
} | |
VoidCallback _logout() { | |
return () async { | |
try { | |
setState(() { | |
_result = ''; | |
logoutVisible = false; | |
}); | |
await Web3AuthFlutter.logout(); | |
} on UserCancelledException { | |
print("User cancelled."); | |
} on UnKnownException { | |
print("Unknown exception occurred"); | |
} | |
}; | |
} | |
Future<Web3AuthResponse> _withAuth0() { | |
return Web3AuthFlutter.login(LoginParams( | |
loginProvider: Provider.jwt, | |
extraLoginOptions: ExtraLoginOptions( | |
domain: 'https://tangross.auth0.com', verifierIdField: 'sub'))); | |
} | |
Future<String> _getAddress() async { | |
final prefs = await SharedPreferences.getInstance(); | |
final privateKey = prefs.getString('privateKey') ?? '0'; | |
// const String rpcUrl = 'https://rpc.ankr.com/eth_goerli'; | |
// final client = Web3Client(rpcUrl, Client()); | |
final credentials = EthPrivateKey.fromHex(privateKey); | |
final address = credentials.address; | |
debugPrint("Account, ${address.hexEip55}"); | |
setState(() { | |
_result = address.hexEip55.toString(); | |
}); | |
return address.hexEip55; | |
} | |
Future<EtherAmount> _getBalance() async { | |
final prefs = await SharedPreferences.getInstance(); | |
final privateKey = prefs.getString('privateKey') ?? '0'; | |
final client = Web3Client(rpcUrl, Client()); | |
final credentials = EthPrivateKey.fromHex(privateKey); | |
final address = credentials.address; | |
final balance = await client.getBalance(address); | |
debugPrint(balance.toString()); | |
setState(() { | |
_result = balance.toString(); | |
}); | |
return balance; | |
} | |
Future<String> _sendTransaction() async { | |
final prefs = await SharedPreferences.getInstance(); | |
final privateKey = prefs.getString('privateKey') ?? '0'; | |
final client = Web3Client(rpcUrl, Client()); | |
final credentials = EthPrivateKey.fromHex(privateKey); | |
final address = credentials.address; | |
try { | |
final receipt = await client.sendTransaction( | |
credentials, | |
Transaction( | |
from: address, | |
to: EthereumAddress.fromHex('0xfdkljfkl'), | |
value: EtherAmount.fromInt(EtherUnit.gwei, 5000000), | |
), | |
chainId: 5); | |
debugPrint(receipt); | |
setState(() { | |
_result = receipt; | |
}); | |
return receipt; | |
} catch (e) { | |
setState(() { | |
_result = e.toString(); | |
}); | |
return e.toString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment