I want to interact with my smart contract to use their functions. I am using the ethereum-react-native-boilerplate example and I’m trying to execute a smart contract function using the useWeb3ExecuteFunction hook. I run this example and its works fine but when I try to interact smart contract with react-moralis it's not working and only redirecting to metamask and not calling the function of the smart contract. Below code is called on button click for calling smart contract function.
const ops = {
contractAddress: "0x878......",
functionName: "add_data",
abi: [{"inputs": [{"internalType": "uint256","name": "amount","type": "uint256"},{"internalType": "uint256","name": "total_user","type": "uint256"},{"internalType": "address","name": "token","type": "address"},{"internalType": "string","name": "_value","type": "string"},{"internalType": "string","name": "symbol","type": "string"}],"name": "add_data","outputs": [],"stateMutability": "nonpayable","type": "function"}],
params: {
amount: 123333,
total_user: 6,
token: "0x34EE........",
_value: "ABC Coin",
symbol: "ABC",
},
};
await contractProcessor.fetch({
params: ops,
onSuccess: () => {
console.log("Approval Received");
},
onError: (error) => {
},
});
I followed the official documentation of react-moralis
https://github.com/MoralisWeb3/react-moralis#useweb3executefunction
Use Moralis npm module contains for React Native environments.
npm i moralis
const Moralis = require('moralis');
Related
Here's a simple example on the forgot password reset page of my app, I would want to bypass the server side and just have the password reset to succeed on click so I would write a test and use the custom test store like so:
const customStore = {
state() {
return {
Authentication: {
passwordResetSuccess: false,
},
};
},
mutations: {
SET_RESET_PASSWORD_SUCCESS(state) {
state.Authentication.passwordResetSuccess = true;
},
},
actions: {
forgotPasswordResetPassword() {
this.commit('SET_RESET_PASSWORD_SUCCESS');
},
},
};
Then I could include the custom store in my beforeEach() and it worked great. I've tried everything I can think of to get this to work with pinia, but it doesn't seem to work.
I'm using jest along with vue/test-utils.
I basically tried just creating the test pinia store, but I can't figure out how to get the component to use the custom test store.
const useCustomStore = defineStore('AuthenticationStore', {
state: () => ({
passwordResetSuccess: false,
}),
actions: {
forgotPasswordResetPassword() {
this.passwordResetSuccess = true;
},
},
});
const authenticationStore = useCustomStore();
I can't directly add it as a plugin because it can't find an active instance of pinia.
I went through this guide: https://pinia.vuejs.org/cookbook/testing.html#unit-testing-a-store
and I also tried using jest mock as described here: https://stackoverflow.com/a/71407557/4697639
But it still failed.
If anyone has any idea how to create a custom store that can be used by the component and actually hits the custom actions, I could really use some help figuring this out. Thank you!!
Tao mentioned in the comments that this isn't a good way to do unit tests. I will mark this as resolved and fix how I do the testing.
I'm currently working on an app in react native using the expo framework.
I'm trying to send a notification from the client that contains a stopwatch in the notification body.
I'm looking to do something like this: stopwatch notification
My problem is that I didn't have much success trying to find the way to update the notification body in expo. I found a different package using react-native called notifee, but I haven't been able to connect it to my project.
The error it gave me while trying to import notifee after installing it was-
Error: Notifee native module not found.
I tried to search how to fix it but I couldn't find a solution.
I wanted to know if there is a way to update notification body in expo, or connect notifee with expo framework.
If there isn't, what would you recommend? (e.g. stop using expo and use other framework, or use pure react native etc).
Thanks for any suggestions!
The Code
import * as Notifications from 'expo-notifications';
export default async function NotificationPage(title, minute, second, author, notificationListener) {
await schedulePushNotification(title, author, minute);
}
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: false,
shouldSetBadge: false,
}),
});
async function schedulePushNotification(title, author, minute) {
await Notifications.scheduleNotificationAsync({
content: {
title,
categoryIdentifier: 'timer_notification',
subtitle: author,
body: 'stopwatch goes here,
data: { data: 'goes here' },
},
trigger: {
seconds: 1,
},
});
}
I am implementing it .
react-native-google-pay
It is installed and showing a login popup as expected but i am not able to get how can i test it. As there is no way to test it.
this is my code
const requestData = {
cardPaymentMethod: {
tokenizationSpecification: {
type: 'PAYMENT_GATEWAY',
gateway: 'stripe',
gatewayMerchantId: '',
stripe: {
publishableKey: '',
version: '2018-11-08',
}
},
allowedCardNetworks,
allowedCardAuthMethods,
},
transaction: {
totalPrice: amount_to_add,
totalPriceStatus: 'FINAL',
currencyCode: 'USD',
},
merchantName: 'Merchant',
};
In this what is the value of gatewayMerchantId,type.
And Let me know if someone have dummy cards or a way to test it. As it is showing error, as well as no trasaction response of 200 or rejection.
I haven't done a Google Pay integration with Stripe, but react-native-google-pay looks like a thin wrapper around the Google Pay API. I'd suggest looking at Google Pay's documentation to supplement the holes in the library's documentation.
In this case, I'd suggest changing the values in the tokenizationSpecification to match Google Pay's docs:
const requestData = {
cardPaymentMethod: {
tokenizationSpecification: {
type: 'PAYMENT_GATEWAY',
parameters: {
gateway: "stripe"
"stripe:version": "2018-10-31"
"stripe:publishableKey": "YOUR_PUBLIC_STRIPE_KEY"
}
},
allowedCardNetworks,
allowedCardAuthMethods,
},
transaction: {
totalPrice: amount_to_add,
totalPriceStatus: 'FINAL',
currencyCode: 'USD',
},
merchantName: 'Merchant',
};
When I integrated to Google Pay, I used my real credit card number (I was unable to get anything fake into Google Pay) and enabled test mode. The library seems to support that test mode like this:
// Set the environment before the payment request
GooglePay.setEnvironment(GooglePay.ENVIRONMENT_TEST);
I'm trying to get Local Notifications working in an Ionic Vue app (using capacitor).
I did get scheduling notifications working, but now i want to listen to clicks on the notification.
in main.js I bind LocalNotifications to this.$LocalNotifications:
import { Plugins } from '#capacitor/core';
const { LocalNotifications } = Plugins;
Vue.prototype.$LocalNotifications = LocalNotifications;
in my Root component App I have this:
created() {
console.log('Created!')
document.addEventListener('deviceready', () => {
console.log('ready');
this.$LocalNotifications.addListener('localNotificationReceived', (notification) => {
console.log('Notification action received', notification);
});
}, false);
}
When I build and run on the ios-emulator, i get the following output in my log:
APP ACTIVE
To Native Cordova -> Badge load Badge1248600129 ["options": []]
⚡️ [log] - onscript loading complete
To Native Cordova -> Device getDeviceInfo Device1248600130 ["options": []]
⚡️ To Native -> Storage get 90127150
⚡️ TO JS {"value":null}
⚡️ [log] - Created!
To Native Cordova -> LocalNotification launch LocalNotification1248600131 ["options": []]
To Native Cordova -> LocalNotification ready INVALID ["options": []]
⚡️ To Native -> LocalNotifications addListener ⚡️ [log] - ready
90127151
⚡️ WebView loaded
⚡️ To Native -> App addListener 90127152
When I schedule a Notification, the notification does show up, but I think something doesn't go quite well when i'm adding the listener:
INVALID ["options":[]]
Does anyone have any idea how to solve this?
Or does anyone have a code example of working notifications in an Ionic Vue app?
Kind regards,
Bram
To sum up:
You should use localNotificationActionPerformed instead of localNotificationReceived. The latter is called when notifications are displayed, while the other is listening to actions performed on a notification (as it's stated in the docs), that of course includes clicking / tapping on it.
So your code would look like this:
this.$LocalNotifications.addListener('localNotificationActionPerformed', (notification) => {
console.log('Notification action received', notification.actionId);
});
...which would output "tap". Since you did write 'Notification action received', I assume you wanted to get the action, so I added .actionId after 'notification', which only by itself would be logged as [object Object] or as the object tree.
You also asked for code example, so here it comes:
// 1.
import { LocalNotifications } from '#capacitor/local-notifications';
// 2.
await LocalNotifications.requestPermissions();
// 3.
await LocalNotifications.registerActionTypes({
types: [
{
id: 'your_choice',
actions: [
{
id: 'dismiss',
title: 'Dismiss',
destructive: true
},
{
id: 'open',
title: 'Open app'
},
{
id: 'respond',
title: 'Respond',
input: true
}
]
}
]
});
// 4.
LocalNotifications.schedule({
notifications: [
{
id: 1,
title: 'Sample title',
body: 'Sample body',
actionTypeId: 'your_choice'
}
]
});
// 5.
LocalNotifications.addListener('localNotificationActionPerformed', (notification) => {
console.log(`Notification ${notification.notification.title} was ${notification.actionId}ed.`);
});
1: Since your question, plugins have been placed into their own npm packages, so one needs to install #capacitor/local-notifications and import from there.
2: You should make sure that notifications are allowed, ask for permissions if needed.
3: Tapping was your question's topic, but you can define a lot more than that.
4: This is how you actually create & send a notification at once.
5: Logs "Notification Sample title was taped / opened / dismissed / responded.", according to the given action (but not always according to grammar).
Finally, if someone's just getting into local notifications, check out the really nice documentation on what else (a whole lot more!) can be done and also watching this video might give one a head start. At least that's what I did.
I am developing an Apple Pay with react-native. I configured everything and I used react-native-payment component. Here is my code:
onPressApplePay=()=>{
console.log("1- start Apple Pay");
if (!DataManager.getInstance().isConnected()) {
this.myAlert(I18n.t("NoInternetConnectionState"));
return;
}
const DETAILS = {
id: 'basic-example',
displayItems: [
{
label: 'items',
amount: { currency: 'EUR', value: '2' },
},
],
total: {
label: 'MyApp',
amount: { currency: 'EUR', value: '2' },
},
};
const METHOD_DATA = [{
supportedMethods: ['apple-pay'],
data: {
merchantIdentifier: 'merchant.com.myapp',
supportedNetworks: [ 'mastercard', 'visa'],
countryCode: 'IT',
currencyCode: 'EUR'
}
}];
const paymentRequest = new PaymentRequest(METHOD_DATA, DETAILS);
console.log("2- paymentRequest.show", paymentRequest);
paymentRequest.show()
.then((paymentResponse) => {
const { paymentToken } = paymentResponse.details; // On Android, you need to invoke the `getPaymentToken` method to receive the `paymentToken`.
paymentRequest.canMakePayments()
.then(canMakePayments => {
console.log("canMakePayments", canMakePayments);
console.log("paymentToken", paymentToken);
// Show fallback payment method
});
})
.catch((err) => {
console.log("4- err", err);
console.log("5- paymentRequest", err);
//alert("The apple pay cancel");
// The API threw an error or the user closed the UI
});
The problem is that as I try to execute the Apple Pay, it says that the 'Payment is not completed' and the token becomes undefined. Can you please ket me know where the problem might be hiden.
I should mention that I tried this code on a real device using both real card and sandBox and in all cases it was failed. Thanks in advance.
This component is also working with stripe and Braintree. The problem was that I needed to add a gateway and a public key which in my case it provided from stripe.
const METHOD_DATA = [{
supportedMethods: ['apple-pay'],
data: {
merchantIdentifier: 'merchant.yyyy.xxxx',
supportedNetworks: [ 'mastercard'],
countryCode: 'IT',
currencyCode: 'EUR',
paymentMethodTokenizationParameters: {
parameters: {
gateway: 'stripe',
'stripe:publishableKey': 'pk_test_XXXXXXX',
'stripe:version': '5.0.0' // Only required on Android
}
}
}
}];
Then I installed the following add on:
yarn add react-native-payments-addon-stripe
yarn add react-native-payments-cli
yarn react-native-payments-cli -- link stripe
(You also need the Carthage update there to make them work)
Then I made an account in stripe.com and use the publish key of that and finally it works!!
Also I have added paymentResponse.complete('success'); to show the successful payment at the end. Without that it sucks in a loop of waiting and finally shows 'Payment is not complete'.
Now I have a successful message with a nice token!
I should mention that in the case that you don't use stripe or Braintree, you will not see any token and it will be always undefined. It is natural, so don't worry. You just need to pass paymentResponse.details as a JSON to your bank provider and it will work. Because in that case the transactionid will be important which you have it.
After that, you go through these steps of installing from this link . You also need to do these steps regarded to certificates for Apple Pay:
1- First on your App ID in your apple developer account you should enable the Apple Pay with the merchant ID.
2- Then you need to ask from your bank for a certificate on you merchant which is a file that looks like this:
XXXXX.certSigningRequest.txt
3- Then select your app ID and go to Apple Pay section which was enabled in step one and upload the certificate there.
Done! Your Apple Pay will work.
The mention saved me! I didn't realize that it was normal the token would be nil if you aren't using Stripe/Braintree!