Connect Metamask with a native mobile app built with Flutter - flutter

I want to connect the app to Metamask to get the user account and signature from the user to confirm the transaction. But the problem is that when I enter Metamask from the app, I am not asked any questions to confirm the connection and nothing happens inside Metamask, it is like only the Metamask app is opened and when I back up and return to the app, the null account is returned.
_walletConnect() async {
final connector = WalletConnect(
bridge: 'https://bridge.walletconnect.org',
clientMeta: const PeerMeta(
name: 'WalletConnect',
description: 'WalletConnect Developer App',
url: 'https://walletconnect.org',
icons: [
'https://gblobscdn.gitbook.com/spaces%2F-LJJeCjcLrr53DcT1Ml7%2Favatar.png?alt=media'
],
),
);
// Subscribe to events
connector.on('connect', (session) => print(session));
connector.on('session_update', (payload) => print(payload));
connector.on('disconnect', (session) => print(session));
// Create a new session
if (!connector.connected) {
session = await connector.createSession(
chainId: 97,
onDisplayUri: (uri) async => {print(uri), await launch(uri)});
}
setState(() {
account = session.accounts[0];
print(account);
});
if (account != null) {
final client = Web3Client(rpc, Client());
EthereumWalletConnectProvider provider =
EthereumWalletConnectProvider(connector);
credentials = WalletConnectEthereumCredentials(provider: provider);
yourContract = ethUtils.getDeployedContract(myAddress, client);
}

It sometimes happened to me as well.
I had just closed the MetaMask app and clicked on the button (Which triggered this function) and it worked fine.

I made a library for this, web3_connect, uses the same code and it gets the address back just fine for me

Related

TrustWallet doesn't show confirmation popup after few minutes of closing app "Flutter"

I am using walletconnect_dart package to connect with metamask/trustwallet and send transaction
for metamask it's working but for TrustWallet when user close app and come back after few minutes session is still connected but it doesn't show transaction confirm popup when user send transaction, it only work for first few minutes until user close app
final session = await UserDataUtils.sessionStorage.getSession();
// Create a connector
_twConnector = WalletConnect(
bridge: 'https://bridge.walletconnect.org',
session: session,
sessionStorage: sessionStorage,
clientMeta: const PeerMeta(
name: 'WalletConnect',
description: 'WalletConnect Developer App',
url: 'https://walletconnect.org',
icons: [
'https://gblobscdn.gitbook.com/spaces%2F-LJJeCjcLrr53DcT1Ml7%2Favatar.png?alt=media'
],
),
);
code for sending transaction with trustwallet
await launchUrl(Uri.parse(uri), mode: LaunchMode.externalApplication);
return await _twConnector.sendCustomRequest(
method: 'eth_sendTransaction',
params: [trxParams],
);

Firebase auth web SDK not working on Ionic iOS?

My issue is the login with the email and password function works fine on android but on iOS, the promise is never returned ( nor failed ) when correct credentials are provided but it fails if I provide incorrect credentials. The login works on iOS with live reload simulating on an iOS device, but when installed with test-flight or via xCode promise is never returned nor rejected.
How can I debug it further or know what the underlying issue is?
onSubmit: async (values) => {
try {
const auth = getAuth(firebaseApp);
auth.setPersistence(browserSessionPersistence);
// Never called on IOS
auth.onAuthStateChanged(() => {
console.log('I am here', auth.currentUser);
if (auth.currentUser) {
updateIsAuthenticated(true);
}
});
const userCred = await signInWithEmailAndPassword(auth, values.email, values.password);
//Never runs
console.log('After Success', userCred);
} catch (error) {
// Runs when provided with false credentials
setError('Error: Authentication failed');
console.error('An error Occurred');
} finally {
console.log('Running Finally');
}
},
});

flutter_facebook_auth plugin not clearing the data when logging out

I'm making use of the flutter_facebook_auth 3.5.0 plugin to enable users to log into my app using their Facebook account.
Everything is working as expected. But when I log out and try to login again, it isn't prompting me to enter the credentials and directly logs me in.
I want it to prompt the user to enter their Facebook account credentials and then log into the app only if the authentication was successful.
Below is the SignIn code:
Future<void> signInWithFacebook(BuildContext context) async {
User? firebaseUser;
LoginResult response = await FacebookAuth.instance.login();
AuthCredential facebookCredential = FacebookAuthProvider.credential(response.accessToken!.token);
final UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(facebookCredential);
firebaseUser = userCredential.user;
switch (response.status) {
case LoginStatus.success:
final userData = await FacebookAuth.instance.getUserData();
facebookUserData = userData;
firestoreInstance.collection("users").doc(firebaseUser!.uid).set({
"userID": firebaseUser.uid,
"name": facebookUserData["name"],
"photo": facebookUserData["picture"]["data"]["url"],
"emailAddress": facebookUserData["email"],
"signUpMethod": "facebook",
"accountCreatedOn": Timestamp.now(),
"receiveOffers": true,
"isAdmin": false,
"isAuth": false,
"isSubscribed": false,
});
Navigator.of(context).pushReplacement(ScaledAnimationPageRoute(HomePage()));
break;
case LoginStatus.cancelled:
print("Facebook: User cancelled login");
break;
case LoginStatus.failed:
print("Facebook: Login error!");
break;
case LoginStatus.operationInProgress:
// TODO: Handle this case.
break;
}
}
Below is the method for logout:
await FacebookAuth.instance.logOut();
facebookUserData = {};
await authInstance.signOut().then((value) => Navigator.of(context).pushReplacement(ScaledAnimationPageRoute(SignIn())));
I think the AuthCredential needs to be cleared when the user is logging out. I'm not sure how to do it.
I'm new to Flutter. How can I fix this?
There is already an issue on the github project of the flutter_facebook_auth 3.5.0 here.
It looks like an lmitation of Facebook and not the plugin itself.
Use package named flutter_facebook_login instead...I am using this package and it is working well

I'm getting a Web Push Error Code Status 403, which is driving me nuts, because its telling me to use firebase. What's going on?

I keep getting a WebPush Error (Status Code 403) fro Chrome for a PWA I'm building and the body says that I need to use the VAPID server key from the 'firebase console' but I used nodes Web-Push library to generate the VAPID Keys, whats going on? Do I have to use firebase to build PWAs in Chrome?
Here's the Error Message I'm getting from the browser when I send a push notification:
name: 'WebPushError',
message: 'Received unexpected response code',
statusCode: 403,
headers:
{ 'content-type': 'text/plain; charset=utf-8',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '0',
date: 'Thu, 31 Oct 2019 19:59:02 GMT',
'content-length': '194',
'alt-svc':
'quic=":443"; ma=2592000; v="46,43",h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000',
connection: 'close' },
body:
'the key in the authorization header does not correspond to the sender ID used to subscribe this user. Please ensure
you are using the correct sender ID and server Key from the Firebase console.\n',
endpoint:
'https://fcm.googleapis.com/fcm/send/exXmW3OFOTY:APA91bEKW_vxnvOZohog34pprDH6XvBsxtfnUpBdYY7z_7q4GZGa4wrmtBBg4kTRwLtgy3lNpCs8SMlvOr4nY-Fu_4zUus6zEJh69581Ier14QZxkEEVXyZHKRaZcmHa3zmbZRB4VD7Z
and here's the code that is running my node server:
//Handle imports
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const webPush = require('web-push')
const vapidKeys = require('./vapid.json')
const path = require('path')
//Setup application
const app = express()
app.use(cors())
app.use(bodyParser.json())
app.use('/static', express.static(path.join(__dirname,'frontend')))
const port = 8080
//Set up webpush
webPush.setVapidDetails(
'mailto: <email>',
vapidKeys.publicKey,
vapidKeys.privateKey
)
const pushOptions = {
proxy: '<proxy>'
}
//setup Push Notification
const sendNotification = (subscription, dataToSend='') => {
webPush.sendNotification(subscription, dataToSend, pushOptions).catch(error => { console.log('Damn it: ', error.message, '||', error)
})
}
//Server Routes Defined
app.get('/', (req, res) => res.sendFile('index.html', { root: './' }))
//Setup Database Methods
const dummyDb = {subscription: null}
const saveToDatabase = async subscription => {
dummyDb.subscription = subscription
}
//Other Server Routes
app.post('/save-subscription', async (req, res) => {
const subscription = req.body
await saveToDatabase(subscription)
console.log('subscribed!')
res.json({message: 'success'})
})
app.get('/send-notification', (req, res) => {
const subscription = dummyDb.subscription
const message = 'hello world'
sendNotification(subscription, message)
res.json({message: dummyDb.subscription})
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
I have node.js express, postgres, angular 8 app.
I had the same problem and I got it working by adding the "gcm_sender_id": in the manifest.webmanifest file (or manifest.json I also used firebase generated public and private keys.
your gcm_sender_id is your project id in google cloud or firebase sender id
Same situation and almost lost my sanity. I tried inserting gcm_sender_id with a Firebase senderId and worked finally. I didn't have a Firebase account, but I was able to create a project in seconds and my senderId was ready to be used in the messaging settings.
But a caveat: After my modification in the manifest.json (in my case) in the root's folder, it was needed to uninstall the current service worker and restart my React project. Then I followed again all steps back by asking permissions and subscribe the user and finally trigger a push notification.
During my heat researches for a solution, I found that gcm_sender_id is also used to send and validate push messages from other browsers. According to Google Web Updates:
For Chrome prior to version 52, Opera Android and the Samsung Browser,
you're also still required to include a 'gcm_sender_id' in your web
app's manifest.json. The API key and sender ID are used to check
whether the server making the requests is actually allowed to send
messages to the receiving user.

403 on Google Action push notification request

I'm trying to perform a push notification for Google Actions Intent.
Thus far, I've followed the instructions here: https://developers.google.com/actions/assistant/updates/notifications#send_notifications
This is my resulting code:
const {google} = require('googleapis');
var request = require('request');
const key = require('./bot.json');
module.exports = async function (context, myQueueItem) {
context.log('JavaScript queue trigger function processed work item', myQueueItem);
let jwtClient = new google.auth.JWT(
key.client_email, null, key.private_key,
['https://www.googleapis.com/auth/actions.fulfillment.conversation'],
null
);
jwtClient.authorize((err, tokens) => {
// code to retrieve target userId and intent
let notif = {
userNotification: {
title: [message],
},
target: {
userId:[obtained from permission request],
intent: [name of intent],
// Expects a IETF BCP-47 language code (i.e. en-US)
locale: 'en-US'
},
};
request.post('https://actions.googleapis.com/v2/conversations:send', {
'auth': {
'bearer': tokens.access_token,
},
'json': true,
'body': {'customPushMessage': notif},
}, (err, httpResponse, body) => {
console.log(body);
console.log(httpResponse.statusCode + ': ' + httpResponse.statusMessage);
});
});
};
//module.exports(console, "Test");
This results in a 403 from the notification service. Is this because of the user id, intent name or jwtoken that was generated?
Following are the steps we need to check before sending the push notification
Check your Google permission settings
In order to test the Action, you need to enable the necessary permissions.
Go to the ‘Activity Controls' page (https://myaccount.google.com/activitycontrols).
Sign in with your Google account, if you have not already done so.
Ensure that the following permissions are enabled:
a.Web & App Activity
b.Device Information
c.Voice & Audio Activity
2.Target intent name should be added into the Implicit invocation field.
with enabled push notification.
3.use the same email id in your google assistant which you had used for login in GCP.