I am trying to develop a dApp using truffle and ganache. deployed() is returning undefined so I cannot use that for creating an instance of the contract.
Here is the code:
App = {
web3Provider: null,
contracts: {},
init: async function() {
$('#category').append('<option value="Clothing">Clothing</option>');
return await App.initWeb3();
},
initWeb3: async function() {
if (window.ethereum) {
App.web3Provider = window.ethereum;
try {
await window.ethereum.request({ method: "eth_requestAccounts" });
} catch (error) {
console.error("User denied account access");
}
}
else if (window.web3) {
App.web3Provider = window.web3.currentProvider;
}
else {
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:8545');
}
web3 = new Web3(App.web3Provider);
return await App.initContract();
},
initContract: function() {
$.getJSON('Marketplace.json', function(data) {
// Get the necessary contract artifact file and instantiate it with #truffle/contract
var MarketplaceArtifact = data;
App.contracts.Marketplace = TruffleContract(MarketplaceArtifact);
// Set the provider for our contract
App.contracts.Marketplace.setProvider(App.web3Provider);
});
return App.initUI();
},
initUI: function() {
var marketplaceInstance;
App.contracts.Marketplace.deployed().then(function(instance) {
marketplaceInstance = instance;
return marketplaceInstance.getCategories.call();
}).then(function(categories) {
alert(categories[1]);
for(i = 0; i < categories.length; i++) {
$('#category').append('<option value="' + categories[i] + '">' + categories[i] + '</option>');
}
}).catch(function(err) {
console.log(err.message);
});
}
};
$(function() {
$(window).load(function() {
App.init();
});
});
I am getting an exception as follows in this line:
App.contracts.Marketplace.deployed().then(function(instance)
The exception is:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'deployed')
at Object.initUI (register-nonprofit.js:49:31)
the deployed() function should return the contract instance, but it is not. Please help.
i am new to ionic4/angular4.i need to upload the profile pic to database.i wrote code but i don't know whether it is correct or not and when i am uploading it i am getting the above mentioned error. backed i am using Django and sorry for the bad indentation.i just beginner to programming.
.ts
async sendPictureToSomewhere() {
const fileuri = await this.getPicture();
const blobinfo = await this.b64toBlob(fileuri);
await this.upload(blobinfo);
alert("done");
}
async getPicture() {
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
// targetWidth: 200
};
let fileuri = await this.camera.getPicture(options);
return fileuri;
}
b64toBlob(_imagePath) {
return new Promise((resolve, reject) => {
let fileName = "";
this.file
.resolveLocalFilesystemUrl(_imagePath)
.then(fileEntry => {
let { name, nativeURL } = fileEntry;
// get the path..
let path = nativeURL.substring(0, nativeURL.lastIndexOf("/"));
console.log("path", path);
console.log("fileName", name);
fileName = name;
// we are provided the name, so now read the file into
// a buffer
return this.file.readAsArrayBuffer(path, name);
})
.then(buffer => {
// get the buffer and make a blob to be saved
let imgBlob = new Blob([buffer], {
type: "image/jpeg"
});
console.log(imgBlob.type, imgBlob.size);
resolve({
fileName,
imgBlob
});
})
.catch(e => reject(e));
});
}
upload(_Blobinfo) {
this.profileService.postInfluencerProfile(_Blobinfo, null,
null).subscribe(
response => {
console.log(response);
},
(error: MavinError) => {
if (error instanceof NotFoundError) {
alert("Not found");
} else {
console.log(error);
}
}
);
}
}
I am trying to write and read to /temp dir in lambda during function execution, I know the best way would be to use S3, but for this project, I have to use node file system
const fs = require('fs');
exports.handler = async (event) => {
const path = '/tem/hi.json';
const write = (file) => {
fs.writeFile(file, "Hello World!", function(err) {
if (err) return console.log(err);
return {
statusCode:200,
body:JSON.stringify('data was written')
};
});
};
return write(path);
};
You have a typo on your file path.
Change
const path = '/tem/hi.json';
to
const path = '/tmp/hi.json';
Also, fs.writeFile is an asynchronous operation. Promisify it so you can await on it:
const write = file => {
return new Promise((res, rej) => {
fs.writeFile(file, JSON.stringify({ message: 'hello world' }), (err) => {
if (err) {
return rej(err)
}
return res({
statusCode: 200,
body: JSON.stringify({message: 'File written successfully'})
})
})
})
}
Finally, on your client (last line of your handler), just invoke it like this:
return await write(path)
fs.writeFile is an asynchronous operation, so the lambda ends before it finishes. You can use fs.writeFileSync to block the lambda execution until the file is sucessfuly written:
const write = (file) => {
try {
fs.writeFileSync(file, "Hello World!");
return {
statusCode: 200,
body: 'data was written'
};
} catch (err) {
console.log(err);
return {
statusCode: 500,
body: 'data was not written'
};
}
};
I tried sending the command from cloud functions, I am getting Error: The service is currently unavailable.
Package.JSON
"dependencies": {
"firebase-admin": "~6.0.0",
"firebase-functions": "^2.0.3",
"googleapis": "34.0.0"
}
const parentName = `projects/${projectId}/locations/${cloudRegion}`;
const registryName = `${parentName}/registries/${reqData.registryId}`;
const binaryData = Buffer.from(JSON.stringify(reqData.message)).toString('base64');
const request = {
name: `${registryName}/devices/${reqData.deviceId}`,
binaryData: binaryData
};
google.auth.getClient().then((authClient) => {
const discoveryUrl =
`${DISCOVERY_API}?version=${API_VERSION}`;
if (authClient.createScopedRequired && authClient.createScopedRequired()) {
// Scopes can be specified either as an array or as a single,
// space-delimited string.
authClient = authClient.createScoped([
'https://www.googleapis.com/auth/cloud-platform'
]);
}
google.options({
auth: authClient
});
google.discoverAPI(discoveryUrl).then((client, err) => {
if (err) {
console.log('Error during API discovery', err);
return undefined;
}
client.projects.locations.registries.devices.sendCommandToDevice(request,
(err, data) => {
if (err) {
console.log('Could not send command:', request);
console.log('Message: ', err);
} else {
console.log('Success :', data.statusText);
}
});
});
});
Logs:
{ Error: The service is currently unavailable. at createError (/user_code/node_modules/googleapis/node_modules/axios/lib/core/createError.js:16:15) at settle (/user_code/node_modules/googleapis/node_modules/axios/lib/core/settle.js:18:12) at Unzip.handleStreamEnd (/user_code/node_modules/googleapis/node_modules/axios/lib/adapters/http.js:201:11) at emitNone (events.js:91:20) at Unzip.emit (events.js:185:7) at endReadableNT (_stream_readable.js:974:12) at _combinedTickCallback (internal/process/next_tick.js:80:11) at process._tickDomainCallback (internal/process/next_tick.js:128:9)
The problem is that subfolder MUST be specified, and MUST not be an empty string.
As I was using this in a Firebase function, I just use the firebase subfolder for any commands being sent that do not have a specific subfolder
const request = {
name: `${registryName}/devices/${deviceId}`,
binaryData: Buffer.from(JSON.stringify(commandMessage)).toString("base64"),
subfolder: 'firebase'
}
Here's functions deps:
"dependencies": {
"firebase-admin": "^6.4.0",
"firebase-functions": "^2.1.0",
"fs-extra": "^7.0.0",
"googleapis": "^36.0.0",
},
This is probably due to
bug in the node library
bug in Google's endpoint
Lack of testing on Google's part
Seems that Google's "IoT" is still very young and needs a lot of work
I'm not too familiar with Firebase cloud functions, but I didn't get the error using the inline editor for Cloud Functions (https://console.cloud.google.com/functions). Can you tell me when you started getting this error (and if you're still encountering it)?
For reference, here was the code that I used (basically what you had but with more explicit definitions for projectId, cloudRegion.
const {google} = require('googleapis');
const API_VERSION = 'v1';
const DISCOVERY_API = 'https://cloudiot.googleapis.com/$discovery/rest';
exports.sendCommand = (req, res) => {
let reqData = req.body;
const projectId = reqData.projectId || process.env.GCLOUD_PROJECT;
const cloudRegion = reqData.cloudRegion || process.env.GCLOUD_REGION;
const parentName = `projects/${projectId}/locations/${cloudRegion}`;
const registryName = `${parentName}/registries/${reqData.registryId}`;
const binaryData = Buffer.from(JSON.stringify(reqData.message)).toString('base64');
const request = {
name: `${registryName}/devices/${reqData.deviceId}`,
binaryData: binaryData
};
google.auth.getClient().then((authClient) => {
const discoveryUrl =
`${DISCOVERY_API}?version=${API_VERSION}`;
if (authClient.createScopedRequired && authClient.createScopedRequired()) {
// Scopes can be specified either as an array or as a single,
// space-delimited string.
authClient = authClient.createScoped([
'https://www.googleapis.com/auth/cloud-platform'
]);
}
google.options({
auth: authClient
});
google.discoverAPI(discoveryUrl).then((client, err) => {
if (err) {
console.log('Error during API discovery', err);
return undefined;
}
client.projects.locations.registries.devices.sendCommandToDevice(request,
(err, data) => {
if (err) {
console.log('Could not send command:', request);
console.log('Message: ', err);
} else {
console.log('Success :', data.statusText);
}
});
});
});
res.status(200).send(reqData.message);
};
I read the document, both on github and Facebook developers docs.
There is only sample, nothing more. No API document.
The code to make a Graph API request is
const infoRequest = new GraphRequest(
'/me',
null,
this._responseInfoCallback,
);
And the callback
_responseInfoCallback(error: ?Object, result: ?Object) {
if (error) {
alert('Error fetching data: ' + error.toString());
} else {
alert('Success fetching data: ' + result.toString());
}
}
And here is the function to make a Graph API request
testRequestGraphAPI(){
const infoRequest = new GraphRequest(
'/me',
null,
this._responseInfoCallback,
);
new GraphRequestManager().addRequest(infoRequest).start();
}
However, I can't find any further document. I have no idea what each parameters do.
The result for these codes above is this.
I also don't know how to get the result.
However, when I try to modify '\me' to 'me?fields=id,name', It failed.
Although I have asked for permission
<LoginButton
publishPermissions={["publish_actions,user_birthday, user_religion_politics, user_relationships, user_relationship_details, user_hometown, user_location, user_likes, user_education_history, user_work_history, user_website, user_managed_groups, user_events, user_photos, user_videos, user_friends, user_about_me, user_status, user_games_activity, user_tagged_places, user_posts, user_actions.video, user_actions.news, user_actions.books, user_actions.music, user_actions.fitness, public_profile, basic_info"]}
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
meow_accesstoken = data.accessToken
alert(meow_accesstoken.toString())
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
But it does not print out what error, just object Object.
So, the problem is that I don't understand the sample code which Facebook provide with no explanation.
Here is my question that I really need you help me:
First at all, please check the javascript code that I currently looking at?
How to use graph API in react-native-fbsdk to retrieve some user information (example: full name) and successfully display it (use alert) ?
What each parameters in GraphRequest() do ?
What is the structure of error object and result object in _responseInfoCallback ?
SOLUTION
Thanks to #Samuel answer, I have updated my code
testRequestGraphAPI: function(){
const infoRequest = new GraphRequest(
'/me',
{
parameters: {
fields: {
string: 'email,name,first_name,middle_name,last_name' // what you want to get
},
access_token: {
string: meow_accesstoken.toString() // put your accessToken here
}
}
},
this._responseInfoCallback // make sure you define _responseInfoCallback in same class
);
new GraphRequestManager().addRequest(infoRequest).start();
}
And the callback
_responseInfoCallback: function(error: ?Object, result: ?Object) {
alert("meow response");
if (error) {
alert('Error fetching data: ' + error.toString());
console.log(Object.keys(error));// print all enumerable
console.log(error.errorMessage); // print error message
// error.toString() will not work correctly in this case
// so let use JSON.stringify()
meow_json = JSON.stringify(error); // error object => json
console.log(meow_json); // print JSON
} else {
alert('Success fetching data: ' + result.toString());
console.log(Object.keys(result));
meow_json = JSON.stringify(result); // result => JSON
console.log(meow_json); // print JSON
}
}
*Note: For console.log(), you need to use "Debug JS remotely" then open Chrome developer tools to see the log.
Unfortunately the react-native-fbsdk documentation is not updated and the examples do not work well.
I got the same problem and I solved it by try and error.
To solve your problem you'll need to change your GraphRequest adding params and fields to it like this:
<LoginButton
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
let accessToken = data.accessToken
alert(accessToken.toString())
const responseInfoCallback = (error, result) => {
if (error) {
console.log(error)
alert('Error fetching data: ' + error.toString());
} else {
console.log(result)
alert('Success fetching data: ' + result.toString());
}
}
const infoRequest = new GraphRequest(
'/me',
{
accessToken: accessToken,
parameters: {
fields: {
string: 'email,name,first_name,middle_name,last_name'
}
}
},
responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start()
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
You'll need to enable the Remote JS Debug to see the console.log() info.
https://facebook.github.io/react-native/docs/debugging.html
And probably you need to get some permissions to get more info than names and email so it's a good idea to look the Facebook Graph API Documentation: https://developers.facebook.com/docs/graph-api/overview/
Reference:
https://github.com/facebook/react-native-fbsdk/issues/105#issuecomment-206501550
Here is an example of a custom button if you want to make one :)
FbLoginButton() {
LoginManager
.logInWithReadPermissions(['public_profile'])
.then(function (result) {
if (result.isCancelled) {
alert('Login cancelled');
} else {
AccessToken
.getCurrentAccessToken()
.then((data) => {
let accessToken = data.accessToken
alert(accessToken.toString())
const responseInfoCallback = (error, result) => {
if (error) {
console.log(error)
alert('Error fetching data: ' + error.toString());
} else {
console.log(result)
alert('Success fetching data: ' + result.toString());
}
}
const infoRequest = new GraphRequest('/me', {
accessToken: accessToken,
parameters: {
fields: {
string: 'email,name,first_name,middle_name,last_name'
}
}
}, responseInfoCallback);
// Start the graph request.
new GraphRequestManager()
.addRequest(infoRequest)
.start()
})
}
}, function (error) {
alert('Login fail with error: ' + error);
});
}
Thank you #Samuel.
I finally succeed to get user information from Facebook login because of your help!
But I struggled to figure out how can I get username and email literally from the result object cause I am a newbie in React & Javascript.
P.S. result["name"] is the point because it is object!!
So I added some code to yours for other people like me.
If you don't like using your code, just tell me that.
<LoginButton
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
let accessToken = data.accessToken
alert(accessToken.toString())
const responseInfoCallback = (error, result) => {
if (error) {
console.log(error)
alert('Error fetching data: ' + error.toString());
} else {
console.log(result)
// Here's my code
alert('Success fetching data: ' + result["name"].toString() +
", " + result["email"].toString());
/*
if(your DB already got this email or something unique) {
// SignIn()
}
// when your DB doesn't have this email
else {
// Do signUp() with this infomation and SignIn()
}
*/
}
}
const infoRequest = new GraphRequest(
'/me',
{
accessToken: accessToken,
parameters: {
fields: {
string: 'email,name,first_name,middle_name,last_name'
}
}
},
responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start()
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
My code was not retriving the user email, if you are having the same problem, just put 'email' in parameter's logInWithPermission
Not Working
LoginManager.logInWithPermissions(['public_profile']).then(...)
Working
LoginManager.logInWithPermissions(['public_profile', 'email']).then(...)
All Function
loginWithFacebook = () => {
LoginManager.logInWithPermissions(['public_profile', 'email']).then(
login => {
if (login.isCancelled) {
console.log('Login Cancelado');
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
const accessToken = data.accessToken.toString()
this.getInfoFromToken(accessToken)
})
}
},
error => {
console.log('Erro no login ', console.error(error)
)
}
)
}
getInfoFromToken = token => {
const PROFILE_REQUEST_PARAMS = {
fields: {
string: 'id, name, first_name, last_name, birthday, email'
},
}
const profileRequest = new GraphRequest('/me', { token, parameters: PROFILE_REQUEST_PARAMS },
(error, result) => {
if (error) {
console.log('Login Info has an error:', error)
} else {
console.log(result)
}
},
)
new GraphRequestManager().addRequest(profileRequest).start()
}
try this
import { GraphRequest, GraphRequestManager } from 'react-native-fbsdk';
export const GetInfoUSer = () => {
return new Promise((resolve, reject) => {
const infoRequest = new GraphRequest('/me', null, ((error, result) => {
if (error) {
reject(error)
} else {
resolve(result)
}
}))
new GraphRequestManager().addRequest(infoRequest).start();
})
}
and then
onLoginConFacebook = () => {
LoginManager.logInWithReadPermissions(['public_profile']).then(result => {
if (result.isCancelled) {
console.log(':(')
} else {
AccessToken.getCurrentAccessToken().then((data) => {
let myAccessToken = data.accessToken.toString();
GetInfoUSer().then(response => {
console.log(response)
}).catch(error => {
console.log(error)
})
}
).catch(error => {
console.log(':(')
})
}
})
}