Flutter - Connect trust wallet using wallet connect - flutter

I am trying to create a mobile app that can connect to mobile wallets (ex: Metamask, TrustWalet,...) via WalletConnect, but i can't find anything.
Is there any way to implement walletconnect on flutter app yet?

You need walletconnect_dart and url_launcher
import 'package:url_launcher/url_launcher_string.dart';
import 'package:walletconnect_dart/walletconnect_dart.dart';
// Create a connector
final connector = WalletConnect(
bridge: 'https://bridge.walletconnect.org',
clientMeta: 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) {
final session = await connector.createSession(
onDisplayUri: (uri) async {
_uri = uri;
await launchUrlString(uri, mode: LaunchMode.externalApplication);
}
);
}
For more information please visit walletconnect_dart

dependencies:
wallet_connect: ^1.0.2
final wcClient = WCClient(
onConnect: () {
// Respond to connect callback
},
onDisconnect: (code, reason) {
// Respond to disconnect callback
},
onFailure: (error) {
// Respond to connection failure callback
},
onSessionRequest: (id, peerMeta) {
// Respond to connection request callback
},
onEthSign: (id, message) {
// Respond to personal_sign or eth_sign or eth_signTypedData request callback
},
onEthSendTransaction: (id, tx) {
// Respond to eth_sendTransaction request callback
},
onEthSignTransaction: (id, tx) {
// Respond to eth_signTransaction request callback
},
);
For More Check : Link

Related

which is best practice for flutter push notifications?

am devloping a chat app with flutter and want to know which is best practice when creating a new room should i create a new topic and subscribe to this topic from the client app , or to use message trigger with devices token using sendtodevice method and sendmulticast
exports.messageTrigger = functions.firestore.document('/Messages/{messageID}').onCreate(
async (snapshot, context) => {
var currentRoomUsers = snapshot.data().members;
currentRoomUsers.forEach( (userID) => {
db.collection('Users').doc(userID).get().then(async(doc)=>{
if(doc.exists){
const message = {
notification: {
title: `New message from ${snapshot.data().room}`,
body: snapshot.data().body
},
data: {
click_action: 'FLUTTER_NOTIFICATION_CLICK'
},
tokens: doc.data()['Device_token'],
android: {
priority: "high"
},
priority: 10
}
const response2 = await admin.messaging().sendMulticast(message);
}else {
console.log("No such document!");
}
}).catch((error)=>{
console.log("Error getting document:", error);
});
}
);
i think there is a better way rather than what am actually doing maybe subscribing to topics but how to create a new topic and subscribe users when creating a new room

Stripe Connect firebase functions for creating seller account

I'm using Firebase functions for creating seller account but I don't know how to create seller account and what to put in the redirect_url
I followed some tutorials and wrote the below code
Let me know what changes should I do to open seller account registration with url_launcher
Thanks
const stripeAccount = functions.https.onRequest(async (req, res) => {
const { method } = req
if (method === "GET") {
// CREATE CONNECTED ACCOUNT
const { mobile } = req.query
const account = await stripe.accounts.create({
type: "express",
})
const accountLinks = await stripe.accountLinks.create({
account: account.id,
refresh_url:, <-- What to put here
return_url:, <-- What to put here
type: "account_onboarding",
})
if (mobile) {
// In case of request generated from the flutter app, return a json response
res.status(200).json({ success: true, url: accountLinks.url })
} else {
// In case of request generated from the web app, redirect
res.redirect(accountLinks.url)
}
} else if (method === "DELETE") {
// Delete the Connected Account having provided ID
const {
query: { id },
} = req
console.log(id)
const deleted = await stripe.accounts.del(id)
res.status(200).json({ message: "account deleted successfully", deleted })
} else if (method === "POST") {
// Retrieve the Connected Account for the provided ID
// I know it shouldn't be a POST call. Don't judge :D I had a lot on my plate
const account = await stripe.accounts.retrieve(req.query.id)
res.status(200).json({ account })
}
const stripeReAuth = async (req, res) => {
const { account_id: accountId } = req.query
const accountLinks = await stripe.accountLinks.create({
account: accountId,
refresh_url: <-- Here
return_url: , <-- Here
type: "account_onboarding",
})
res.redirect(accountLinks.url)
}
})
This is my flutter code, I'm retrieving the return_url and launching it with url_launcher
class StripeBackendService {
static String apiBase = '{function address}/stripeAccount';
static String createAccountUrl =
'$apiBase/account?mobile=true';
static String checkoutSessionUrl =
'${StripeBackendService.apiBase}/checkout-session?mobile=true';
static Map<String, String> headers = {'Content-Type': 'application/json'};
void createSellerAccount() async {
var url = Uri.parse(StripeBackendService.createAccountUrl);
var response = await http.get(url, headers: StripeBackendService.headers);
Map<String, dynamic> body = jsonDecode(response.body.toString());
await canLaunch(body['url']) ? await launch(body['url']) : throw 'Error'
}
}
The refresh url should point to an address that retries the creation of the stripe connect account, in case your current http function returns an expired link. The return url is the address that the potential stripe connect user gets sent to after the stripe onboarding is complete. In knowing that address you can use the webview controller to jump back to the app when reaching that return-url endpoint.

flutter getx web sockets - stream data to be cascaded to provider and controller

Objective is simple
flutter app makes a call to graphql api over websockets
app view calls the controller, controller calls the provider, provider calls the AWS appsync api over websockets or over HTTP api socket call
we receive a stream of data from appsync api or HTTP api socket call over websockets every now and then from backend
streams need to be cascaded back to provider , and then to controller (this is the critical step)
controller (not the provider) would update the obs or reactive variable, make the UI reflect the changes
problem : data is recieved via websockets in the caller, but never passed back as stream to provider or controller to reflect the changes
sample code
actual caller
orderdata.dart
#override
Stream<dynamic> subscribe({
String query,
Map<String, dynamic> variables,
}) async* {
debugPrint('===->subscribe===');
// it can be any stream here, http or file or image or media
final Stream<GraphQLResponse<String>> operation = Amplify.API.subscribe(
GraphQLRequest<String>(
document: query,
variables: variables,
),
onEstablished: () {
debugPrint(
'===->subscribe onEstablished ===',
);
},
);
operation.listen(
(event) async* {
final jsonData = json.decode(event.data.toString());
debugPrint('===->subscription data $jsonData');
yield jsonData;
},
onError: (Object e) => debugPrint('Error in subscription stream: $e'),
);
}
in the provider
orderprovider.dart
Stream<Order> orderSubscription(String placeId) async* {
debugPrint('===->=== $placeId');
subscriptionResponseStream = orderData.subscribe(
query: subscribeToMenuOrder,
variables: {"place_id": placeId},
);
subscriptionResponseStream.listen((event) async* {
debugPrint(
"===->=== yielded $event",
);
yield event;
});
debugPrint('===->=== finished');
}
in the controller
homecontroller.dart
Future<void> getSubscriptionData(String placeId) async {
debugPrint('===HomeController->getSubscriptionData===');
OrderProvider().orderSubscription(placeId).listen(
(data) {
//this block is executed when data event is receivedby listener
debugPrint('Data: $data');
Get.snackbar('orderSubscription', data.toString());
},
onError: (err) {
//this block is executed when error event is received by listener
debugPrint('Error: $err');
},
cancelOnError:
false, //this decides if subscription is cancelled on error or not
onDone: () {
//this block is executed when done event is received by listener
debugPrint('Done!');
},
);
}
homeview calls homecontroller
Try using map for transforming Streams:
#override
Stream<dynamic> subscribe({
String query,
Map<String, dynamic> variables,
}) {
debugPrint('===->subscribe===');
// it can be any stream here, http or file or image or media
final Stream<GraphQLResponse<String>> operation = Amplify.API.subscribe(
GraphQLRequest<String>(
document: query,
variables: variables,
),
onEstablished: () {
debugPrint(
'===->subscribe onEstablished ===',
);
},
);
return operation.map((event) {
return json.decode(event.data);
});
}
// elsewhere
final subscription = subscribe(
query: 'some query',
variables: {},
);
subscription.listen(
(jsonData) {
debugPrint('===->subscription data $jsonData');
},
onError: (Object e) => debugPrint('Error in subscription stream: $e'),
);

Flutter websocket onOpen?

I'm trying to create a websocket connection in Flutter.
I followed this tutorial and this
My query is that how can we know once the websocket connection is established? Like there is onOpen event in Javascript.
My code in flutter is:
void main() async {
final channel = IOWebSocketChannel.connect('wss://my.server.org');
channel.stream.listen(
(dynamic message) {
debugPrint('message $message');
},
onDone: () {
debugPrint('ws channel closed');
},
onError: (error) {
debugPrint('ws error $error');
},
);
}
This is what I used in one project to connect to AWS AppSync service. The communication is implemented over websockets.
What you do is parse the messages you receive through web socket. Messages will carry the data, but also there are messages to tell you that the connection was established, keep alive message etc.
I don't remember if the messages below are AppSync specific, or are applicable to any websocket server - but it should at least give you an idea how this could work.
var channel=IOWebSocketChannel.connect(url, protocols: ['graphql-ws']);
channel.sink.add(json.encode({"type": "connection_init"}));
channel.stream.listen((event) {
var e = json.decode(event);
switch (e['type']) {
case 'connection_ack':
wsTimeoutInterval = e['payload']['connectionTimeoutMs'];
var register = {
'id': uniqueKey,
'payload': {
'data': json.encode(query),
'extensions': {'authorization': header}
},
'type': 'start'
};
var payload = json.encode(register);
channel.sink.add(payload);
break;
case 'data':
// calling a callback function Function(Map<String, dynamic>) listener
listener(e);
break;
case 'ka':
print('Keep alive message received!!!');
break;
case 'start_ack':
print('Ws Channel: Subscription started');
break;
default:
print('Unimplemented event received $event');
}
}, onError: (error, StackTrace stackTrace) {
// error handling
print('Ws Channel: $error');
}, onDone: () {
// communication has been closed
channel.sink.close();
print('Ws Channel: Done!');
});

Sending onesignal notification from flutter

I have an android app created with Unity, I can send notifications to this app from OneSignal web site and from my php website successfully. Now I want to send notifications from a flutter app (android). I tried the onesignal sdk for flutter example but it sends the notification to the flutter app and not to Unity app. I don't know where am I wrong :
Future<void> initPlatformState() async {
if (!mounted) return;
var settings = {
OSiOSSettings.autoPrompt: false,
OSiOSSettings.promptBeforeOpeningPushUrl: true
};
// NOTE: Replace with your own app ID from https://www.onesignal.com
await OneSignal.shared
.init("9a98990f-40fa-455e-adda-ccd474594f41", iOSSettings: settings);
OneSignal.shared
.setInFocusDisplayType(OSNotificationDisplayType.notification);
bool requiresConsent = await OneSignal.shared.requiresUserPrivacyConsent();
this.setState(() {
_enableConsentButton = requiresConsent;
});
}
void _handleSendNotification() async {
var status = await OneSignal.shared.getPermissionSubscriptionState();
var playerId = status.subscriptionStatus.userId;
var imgUrlString =
"https://vaars.000webhostapp.com/MrNutella/logonutella.png";
var notification = OSCreateNotification(
playerIds: [playerId],
content: "this is a test from OneSignal's Flutter SDK",
heading: "Test Notification",
iosAttachments: {"id1": imgUrlString},
bigPicture: imgUrlString,
buttons: [
OSActionButton(text: "test1", id: "id1"),
OSActionButton(text: "test2", id: "id2")
]);
var response = await OneSignal.shared.postNotification(notification);
this.setState(() {
_debugLabelString = "Sent notification with response: $response";
});
}
It sounds like you're looking for P2P (user-user) notifications. You will need a way to get the player id of the target app (Unity) from the Flutter app.