Can not send transaction on polygon network using flutter - flutter

I am using web3dart to send transaction.
I already connect wallet for polygon but can't sign transaction.
I think it's due to credential problem.
#override
Future<String?> sendAmount({
required String recipientAddress,
required double amount,
}) async {
final sender =
EthereumAddress.fromHex(_connector.connector.session.accounts[0]);
// final recipient = EthereumAddress.fromHex(address);
final recipient = EthereumAddress.fromHex(recipientAddress);
final etherAmount =
EtherAmount.fromUnitAndValue(EtherUnit.szabo, (amount).toInt());
final transaction = Transaction(
to: recipient,
from: sender,
gasPrice: EtherAmount.inWei(BigInt.one),
maxGas: 100000,
value: etherAmount,
);
final credentials = WalletConnectEthereumCredentials(provider: _provider);
// Sign the transaction
try {
final txBytes = await _polygon.sendTransaction(credentials, transaction);
return txBytes;
} catch (e) {
print('Error: $e');
}
return null;
}
This code works on ethereum network but not in polygon.

Related

Sending emails using app with flutter using SMPT

I have tried to send emails using app, that app is built using flutter framework. There is no error while it is running but emails are not sent. This is my code.
**send email function**
Future sendEmail(subject,msg) async{
final user = await GoogleAuthApi.signIn();
if(user == null) return;
final email = user.email;
final auth = await user.authentication;
final token =auth.accessToken!;
final smtpServer = gmailRelaySaslXoauth2(email, token);
final message = Message()
..from = Address(email,'test')
..recipients = ["test#gmail.com"]
..subject = subject.toString()
..text=msg.toString();
try{
await send(message,smtpServer);
showSnackBar('Sent email successfully!');
}on MailerException catch(e){
print("hi==$e");
}
}
class GoogleAuthApi{
static final _googleSignIn = GoogleSignIn(scopes: ['https://mail.google.com/']);
static Future<GoogleSignInAccount?> signIn() async{
if(await _googleSignIn.isSignedIn()){
return _googleSignIn.currentUser;
}else {
return await _googleSignIn.signIn();
}
}
}

GraphQL notification in flutter - how to catch result?

I subscribe to a graphql document:
// Dart imports:
import 'dart:async';
// Package imports:
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:phoenix_socket/phoenix_socket.dart';
// Project imports:
import 'package:core/util/confirmations/phoenix_link.dart';
class SubscriptionChannel {
PhoenixSocket? socket;
PhoenixChannel? channel;
GraphQLClient? client;
final StreamController<Map> _onMessageController = StreamController<Map>();
Stream<Map> get onMessage => _onMessageController.stream;
Future<void> connect(
String phoenixHttpLinkEndpoint, String websocketUriEndpoint) async {
final HttpLink phoenixHttpLink = HttpLink(
phoenixHttpLinkEndpoint,
);
channel =
await PhoenixLink.createChannel(websocketUri: websocketUriEndpoint);
final phoenixLink = PhoenixLink(
channel: channel!,
);
var link = Link.split(
(request) => request.isSubscription, phoenixLink, phoenixHttpLink);
client = GraphQLClient(
link: link,
cache: GraphQLCache(),
);
}
void addSubscriptionTransactionConfirmed(
String address, Function(QueryResult) function) {
final subscriptionDocument = gql(
'subscription { transactionConfirmed(address: "$address") { nbConfirmations } }',
);
Stream<QueryResult> subscription = client!.subscribe(
SubscriptionOptions(document: subscriptionDocument),
);
subscription.listen(function);
}
Future<Message> onPushReply(Push push) async {
final Completer<Message> completer = Completer<Message>();
final Message result = await channel!.onPushReply(push.replyEvent);
completer.complete(result);
return completer.future;
}
void close() {
_onMessageController.close();
if (socket != null) {
socket!.close();
}
}
}
The goal is, after a api request, to wait a notification with a nb of confirmations:
{
...
await subscriptionChannel.connect(
'https://mainnet.archethic.net/socket/websocket',
'ws://mainnet.archethic.net/socket/websocket');
subscriptionChannel.addSubscriptionTransactionConfirmed(
transaction.address!, waitConfirmations);
transactionStatus = sendTx(signedTx); // API Request
...
}
void waitConfirmations(QueryResult event) {
if (event.data != null &&
event.data!['transactionConfirmed'] != null &&
event.data!['transactionConfirmed']['nbConfirmations'] != null) {
EventTaxiImpl.singleton().fire(TransactionSendEvent(
response: 'ok',
nbConfirmations: event.data!['transactionConfirmed']
['nbConfirmations']));
} else {
EventTaxiImpl.singleton().fire(
TransactionSendEvent(nbConfirmations: 0, response: 'ko'),
);
}
subscriptionChannel.close();
}
My code works in a StatefulWidget but doesn't work in a class
Have you got some examples in a class where you subscribe to a grapqhql notification please to understand how to code this in a class
NB: i'm using Phoenix link
// Dart imports:
import 'dart:async';
// Package imports:
import 'package:gql_exec/gql_exec.dart';
import 'package:gql_link/gql_link.dart';
import 'package:phoenix_socket/phoenix_socket.dart';
/// a link for subscriptions (or also mutations/queries) over phoenix channels
class PhoenixLink extends Link {
/// the underlying phoenix channel
final PhoenixChannel channel;
final RequestSerializer _serializer;
final ResponseParser _parser;
/// create a new [PhoenixLink] using an established PhoenixChannel [channel].
/// You can use the static [createChannel] method to create a [PhoenixChannel]
/// from a websocket URI and optional parameters (e.g. for authentication)
PhoenixLink(
{required PhoenixChannel channel,
ResponseParser parser = const ResponseParser(),
RequestSerializer serializer = const RequestSerializer()})
: channel = channel,
_serializer = serializer,
_parser = parser;
/// create a new phoenix socket from the given websocketUri,
/// connect to it, and create a channel, and join it
static Future<PhoenixChannel> createChannel(
{required String websocketUri, Map<String, String>? params}) async {
final socket = PhoenixSocket(websocketUri,
socketOptions: PhoenixSocketOptions(params: params));
await socket.connect();
final channel = socket.addChannel(topic: '__absinthe__:control');
final push = channel.join();
await push.future;
return channel;
}
#override
Stream<Response> request(Request request, [NextLink? forward]) async* {
assert(forward == null, '$this does not support a NextLink (got $forward)');
final payload = _serializer.serializeRequest(request);
String? phoenixSubscriptionId;
StreamSubscription<Response>? websocketSubscription;
StreamController<Response>? streamController;
final push = channel.push('doc', payload);
try {
final pushResponse = await push.future;
//set the subscription id in order to cancel the subscription later
phoenixSubscriptionId =
pushResponse.response['subscriptionId'] as String?;
if (phoenixSubscriptionId != null) {
//yield all messages for this subscription
streamController = StreamController();
websocketSubscription = channel.socket
.streamForTopic(phoenixSubscriptionId)
.map((event) => _parser.parseResponse(
event.payload!['result'] as Map<String, dynamic>))
.listen(streamController.add, onError: streamController.addError);
yield* streamController.stream;
} else if (pushResponse.isOk) {
yield _parser
.parseResponse(pushResponse.response as Map<String, dynamic>);
} else if (pushResponse.isError) {
throw _parser.parseError(pushResponse.response as Map<String, dynamic>);
}
} finally {
await websocketSubscription?.cancel();
await streamController?.close();
//this will be called once the caller stops listening to the stream
// (yield* stops if there is no one listening)
if (phoenixSubscriptionId != null) {
channel.push('unsubscribe', {'subscriptionId': phoenixSubscriptionId});
}
}
}
}

How to get data from the CurrentUser on flutter Firebase Authentification

I have this Firebase Authentication Providers with who I can create an user, Sign In and Sign Out with the methods (only with email and password)
My problem I that in the UI I want to show data from the current User once the user has Sign In and I don't know how.
For example showing the email in a TextWidget or get the email as a variable for other stuff.
final firebaseAuthProvider = Provider<FirebaseAuth>((ref) {
return FirebaseAuth.instance;
});
class AuthenticationService {
final FirebaseAuth _firebaseAuth;
final Reader read;
AuthenticationService(this._firebaseAuth, this.read);
Stream<User?> get authStateChange => _firebaseAuth.authStateChanges();
Future<String> signIn({required String email, required String constrasena, required String nombreUsuario}) async {
try {
await _firebaseAuth.signInWithEmailAndPassword(
email: email,
password: constrasena,
);
return "Login Successful";
} on FirebaseAuthException catch (e) {
return e.message ?? 'Error';
}
}
Future<String> signUp({required String email, required String constrasena, required String nombreUsuario}) async {
try {
await _firebaseAuth.createUserWithEmailAndPassword(
email: email,
password: constrasena,
);
read(addPerson(Person(nombre_de_usuario: nombreUsuario, email: email, videosVistos: 0)));
return "Signup Successful";
} on FirebaseAuthException catch (e) {
print(e.message);
return e.message ?? 'Error';
}
}
Future<void> signout() async {
await _firebaseAuth.signOut();
}
}
final authServicesProvider = Provider<AuthenticationService>((ref) {
return AuthenticationService(ref.read(firebaseAuthProvider), ref.read);
});
final authStateProvider = StreamProvider<User?>((ref) {
return ref.watch(authServicesProvider).authStateChange;
});
Thanks You!
You can use FirebaseAuth.instance.currentUser.
Example:
Get the user on your initState.
_user = FirebaseAuth.instance.currentUser;
And on your build method:
Text(_user?.email ?? 'No email')

Getting incorrect username and password exception by using `gmailSaslXoauth2`

I am using mailer package from dart pub. I created a service account and copied the content of json file into class variable CLIENT_JSON. You can see some fields of CLIENT_JSON in getAccessToken() function.
Whenever I try to email someone, an exception is thrown
SmtpClientAuthenticationException (Incorrect username / password / credentials)
Here are two functions I am calling from UI.
Future<AccessCredentials> getAccessToken() async {
var accountCredentials = ServiceAccountCredentials.fromJson({
"private_key_id": CLIENT_JSON["private_key_id"],
"private_key": CLIENT_JSON["private_key"],
"client_email": CLIENT_JSON["client_email"],
"client_id": CLIENT_JSON['client_id'],
"type": "service_account"
});
AccessCredentials accessCredentials;
final client = http.Client();
try {
accessCredentials = await obtainAccessCredentialsViaServiceAccount(
accountCredentials, ["https://mail.google.com/"], client);
print("[EMAIL_SERVICE] Access Token Fetched");
} on Exception catch (err) {
print("[EMAIL_SERVICE] Error in fetching access token. Error: $err");
}
client.close();
return accessCredentials;
}
Future<void> sendEmailFromConfibuddy({
#required String receiverEmail,
#required String subject,
#required String body,
}) async {
final credentials = await getAccessToken();
if (credentials == null) {
print("[EMAIL_SERVICE] Credentials are null.");
return;
}
final smtpServer = gmailSaslXoauth2(
CLIENT_JSON["client_email"], credentials.accessToken.data);
final message = Message()
..from = Address(CLIENT_JSON["client_email"], 'Confibuddy')
..recipients.add("example#gmail.com")
..subject = subject
..html = body;
try {
final sendReport = await send(message, smtpServer);
print('Message sent: ' + sendReport.toString());
} on MailerException catch (e) {
print('Message not sent.');
for (var p in e.problems) {
print('Problem: ${p.code}: ${p.msg}');
}
}
}
}
Right now, I can generate an access token using the googleapis_auth package. But I am confused about which email to put in the gmailSaslXoauth2 function as the userEmail parameter. I have two emails, one is my personal account in which I created the project and created a service account and an email generated in json file named as client_email.
client_email looks like this example#example.iam.gserviceaccount.com.

Flutter can''t send sms using fluttersms

I'm trying to send sms after my app scanned a qrcode that contains a phone number.
I'm using FlutterSMS package for this but it seems doesn't work as supposed to do, it is not sending the sms. any help?
void _sendSMS(String message, List<String> recipents) async {
String _result =
await FlutterSms.sendSMS(message: message, recipients: recipents)
.catchError((onError) {
print(onError);
});
print(_result);
}
Future _scan() async {
String barcode = await scanner.scan();
List data = barcode.split("|");
String id = data[0];
String phoneNumber = data[1];
String message = "Halo! Pakaian anda sudah selesai di proses, silahkan ambil di gerai kami -LaundryKu";
setState(() {
this.id = id;
this.barcode = barcode;
this.phoneNumber = phoneNumber;
});
_sendSMS(message, data[1]);
}
Brother there is little mistake
second argument is List
_sendSMS(message, recipents);
So you need to Add you Contact Number to List
List<String> recipents = new List();
recipents.add(data[1].toString());
/// then the Msg in Variable
String message = "This is a test message!";
Final pass both variable as parameters in function
_sendSMS(message, recipents);
Finally you are Done ;)