I am getting the error data: { success: false, error: 'Not logged in: Invalid signature' } for /wallet/balances. Interestingly, the same code runs for /wallet/coins and /markets for FTX REST API. The code is in JS
PLEASE HELP!!
const url = "https://ftx.us/api/wallet/balances"
const path = "/api/wallet/balances"
const timestamp = Date.now()
const method = "GET"
const payload = `{timestamp}{method}{url}`
const hash = CryptoJS.HmacSHA256(payload, process.env.FTX_API_SECRET)
// var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, "Secret Passphrase");
// hmac.update(JSON.stringify(timestamp));
// hmac.update(method);
// hmac.update(path);
// var hash = hmac.finalize();
const hash2 = crypto.createHmac('sha256', process.env.FTX_API_SECRET).update(payload).digest("hex")
console.log("API KEY ", process.env.FTX_API_KEY)
axios({
method: "get",
headers: {
"FTXUS-SIGN": CryptoJS.enc.Hex.stringify(hash),
// "FTXUS-SIGN": hash2,
"FTXUS-KEY": process.env.FTX_API_KEY,
"FTXUS-TS": timestamp,
},
url: url
})
.then( (response) => {
if (response.data.success) {
callback(null, response.data.result)
} else {
// error handling here for the api
callback(result.data.error)
}
})
.catch ( (e) => {
console.log("exception in request ", e)
})
add these 2 lines in headers,
{
"FTXUS-SIGN": CryptoJS.enc.Hex.stringify(hash),
"FTXUS-KEY": process.env.FTX_API_KEY,
"FTXUS-TS": timestamp,
"Content-Type": "application/json",
"Accepts": "application/json",
}
It worked for me
Related
I got following error at file.getSignedUrl. I have other function to copy the file and create new file on Cloud Storage. Why this function need permission and where do I need to set?
Error: The caller does not have permission at Gaxios._request (/layers/google.nodejs.yarn/yarn_modules/node_modules/gaxios/build/src/gaxios.js:129:23) at runMicrotasks () at processTicksAndRejections (node:internal/process/task_queues:96:5) at async Compute.requestAsync (/layers/google.nodejs.yarn/yarn_modules/node_modules/google-auth-library/build/src/auth/oauth2client.js:368:18) at async GoogleAuth.signBlob (/layers/google.nodejs.yarn/yarn_modules/node_modules/google-auth-library/build/src/auth/googleauth.js:662:21) at async sign (/layers/google.nodejs.yarn/yarn_modules/node_modules/#google-cloud/storage/build/src/signer.js:103:35) { name: 'SigningError' }
const functions = require("firebase-functions");
const axios = require("axios");
const { Storage } = require("#google-cloud/storage");
const storage = new Storage();
// Don't forget to replace with your bucket name
const bucket = storage.bucket("projectid.appspot.com");
async function getAlbums() {
const endpoint = "https://api.mydomain.com/graphql";
const headers = {
"content-type": "application/json",
};
const graphqlQuery = {
query: `query Albums {
albums {
id
album_cover
}
}`,
};
const response = await axios({
url: endpoint,
method: "post",
headers: headers,
data: graphqlQuery,
});
if (response.errors) {
functions.logger.error("API ERROR : ", response.errors); // errors if any
} else {
return response.data.data.albums;
}
}
async function updateUrl(id, url) {
const endpoint = "https://api.mydomain.com/graphql";
const headers = {
"content-type": "application/json",
};
const graphqlQuery = {
query: `mutation UpdateAlbum($data: AlbumUpdateInput!, $where:
AlbumWhereUniqueInput!) {
updateAlbum(data: $data, where: $where) {
id
}
}`,
variables: {
data: {
album_cover: {
set: url,
},
},
where: {
id: id,
},
},
};
const response = await axios({
url: endpoint,
method: "post",
headers: headers,
data: graphqlQuery,
});
if (response.errors) {
functions.logger.error("API ERROR : ", response.errors); // errors if any
} else {
return response.data.data.album;
}
}
const triggerBucketEvent = async () => {
const config = {
action: "read",
expires: "03-17-2025",
};
const albums = await getAlbums();
albums.map((album) => {
const resizedFileName = album.id + "_300x200.webp";
const filePath = "images/albums/thumbs/" + resizedFileName;
const file = bucket.file(filePath);
functions.logger.info(file.name);
file.getSignedUrl(config, function (err, url) {
if (err) {
functions.logger.error(err);
return;
} else {
functions.logger.info(
`The signed url for ${resizedFileName} is ${url}.`
);
updateUrl(album.id, url);
}
} );
});
};
exports.updateResizedImageUrl = functions.https.onRequest(async () => {
await triggerBucketEvent();
});
I need to add Service Account Token Creator role for App Engine default service account.
My script is running well but at the end I get an error message Error during script execution.
Cannot set property 'status' of undefined.
Does anybody have a clue what I am doing wrong here?
const fs = require("fs-promise");
const axios = require("axios");
const jsonxml = require("jsonxml");
const tmp = require("tmp");
module.exports = {
mpGetChecklist: async function (mpurl, bearer, systemGetChecklistMethod, systemGetChecklistId, systemGetChecklistDatasetName) {
var getChecklist = {
method: systemGetChecklistMethod,
url: mpurl + "/connector/system/getChecklist?id=" + systemGetChecklistId,
headers: {
Authorization: "Bearer " + bearer,
},
};
let tmpPath = tmp.fileSync({ postfix: ".xml" });
let result;
await axios(getChecklist)
.then(function (response) {
console.log(JSON.stringify(response.data));
let xmlOptions = { header: true, root: "JSON", indent: true };
let xmlString = jsonxml(response.data, xmlOptions);
try {
fs.writeFileSync(tmpPath.name, xmlString);
result = { status: "succes", xmlPath: tmpPath.name, datasetName: systemGetChecklistDatasetName };
} catch (error) {
result = { status: "error", msg: error };
}
})
.catch(function (error) {
console.log(error);
});
return result;
},
};
Please do not share the documentation link, it's not straight forward and also the uploading using RNFS and document-picker is a bit confusing..
Code:
const uploadAttachments = async (data, sessionURI, message, onProgress) => {
const {files} = message;
let length = 0;
const formatedFileData = files.map(item => {
length += item.size;
return {
name: item.filename,
filename: item.filename,
filepath: RNFS.DocumentDirectoryPath + '/' + item.filename,
filetype: item.filetype,
};
});
RNFS.uploadFiles({
toUrl: sessionURI,
files: formatedFileData,
method: 'PUT',
headers: {
Authorization: 'Bearer ' + (await getUserToken()),
'Content-Length': length.toString(),
'Content-Type': 'application/json; charset=UTF-8',
},
fields: data,
progress: onProgress,
})
.promise.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
};
const requestSession = async (data: any, postUrl: string) => {
try {
const result = await axios({
data: data,
headers: {
Authorization: 'Bearer ' + (await getUserToken()),
'Content-Type': 'application/json; charset=UTF-8',
'Content-Length': 0,
'X-Upload-Content-Type': 'message/rfc822',
},
method: 'post',
url: postUrl,
});
return result;
} catch (error) {
throw error;
}
};
export const resumeableUpload = async (message, onProgress) => {
try {
const data = await getMetaData(message);
const response = await requestSession(data, RESUMABLE_URL);
const sessionURI = response.headers.location;
const res = await uploadAttachments(data, sessionURI, message, onProgress);
return res;
} catch (error) {
console.log(error);
}
};
I get the error from RNFS saying the 'Socket is closed'!
May be the way i'm uploading the file itself is wrong or is there any other way to upload files to the session uri?
If I send base64encoded bytes of the file, it raw feild becomes too huge for files over 5MB (25mb files) and the app crashes
I am facing an issue in converting Audio file to Binary format. I need to send it to Wit.AI api which is expecting the data in that format. I am using node.js. In my front-end I am recording the user voice using Mic-recorder Module. Any suggestions are welcome.
My front end code:
var recorder;
function startRecording() {
recorder = new MicRecorder({
bitRate: 128
});
recorder.start()
}
function stopRecording() {
recorder.stop().getMp3().then(([buffer, blob]) => {
console.log(buffer, blob);
const file = new File(buffer, 'music.mp3', {
type: blob.type,
lastModified: Date.now()
})
console.log(file)
axios({
method: 'post',
url: `${appUrl}/open_api/voice/send?data=${buffer}`
}).then(function (res) {
console.log(res)
if (res.data.success) {
console.log('done',res)
} else {
console.log(res.data)
}
})
})
};
After recording Successfully, I want to send the file to my api in order to call wit.ai /speech api.
My back end code is:
router.post('/voice/send', //chatbot response api
async (req, res, next) => {
let thread_id = '99-99-99-99'
let audioBinary = req.query.data
console.log(audioBinary)
let appId = "5d07621d6b79be66a73f4005"
let sessionId ="10-10-10-10"
let accessToken = await db.model('ChatBotApp').findOne({
_id: req.query.key
}, {
access_token: 1
}).lean()
var options = {
method: 'POST',
uri: 'https://api.wit.ai/speech?v=20190513',
body : audioBinary,
encoding: null,
headers: {
'Authorization': 'Bearer ' + "HY3ZWSUGPBPD5LWZLRSZ3QJCDC27M6EW",
'Content-Type': 'audio/mpeg',
},
// json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(async function (parsedBody) {
console.log('this called',parsedBody)
return
// let response = await firstEntityValue(parsedBody, appId, message, thread_id)
// events.emit('Chats', appId, thread_id, message, sessionId, response);
return res.apiOk(response)
})
.catch(function (err) {
console.log(err)
return res.apiError('Issue while creating app!', err);
})
}
)
var recorder
function startRecording() {
recorder = new MicRecorder({
bitRate: 128
});
recorder.start()
}
function stopRecording() {
recorder.stop().getMp3().then(([buffer, blob]) => {
console.log(buffer, blob);
const file = new File(buffer, 'music.mp3', {
type: blob.type,
lastModified: Date.now()
})
var bodyFormData = new FormData();
bodyFormData.append('file', file);
console.log(file)
axios({
method: 'post',
url: `${appUrl}/open_api/voice/send`,
headers: {
'Content-Type': 'multipart/form-data'
},
data: bodyFormData
}).then(function (res) {
console.log(res)
if (res.data.success) {
console.log('done', res)
} else {
console.log(res.data)
}
})
})
};
API
router.post('/voice/send',upload.single('file'), //chatbot response api
async (req, res, next) => {
console.log(req.file)
let thread_id = '99-99-99-99'
let audioBinary = req.file.buffer
let appId = "5d07621d6b79be66a73f4005"
let sessionId = "10-10-10-10"
let accessToken = await db.model('ChatBotApp').findOne({
_id: req.query.key
}, {
access_token: 1
}).lean()
var options = {
method: 'POST',
uri: 'https://api.wit.ai/speech?v=20190513',
headers: {
'Authorization': 'Bearer ' + "HY3ZWSUGPBPD5LWZLRSZ3QJCDC27M6EW",
'Content-Type': 'audio/mpeg',
},
body: audioBinary
// json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(async function (parsedBody) {
console.log('this called', parsedBody)
return
// let response = await firstEntityValue(parsedBody, appId, message, thread_id)
// events.emit('Chats', appId, thread_id, message, sessionId, response);
return res.apiOk(response)
})
.catch(function (err) {
console.log(err)
return res.apiError('Issue while creating app!', err);
})
})
Hello after setup a simple async function with promise return i'd like to use then promise instead of try!
But is returning
await is a reserved word
for the second await in the function.
i've tried to place async return promise the data! but did not worked either
async infiniteNotification(page = 1) {
let page = this.state.page;
console.log("^^^^^", page);
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
fetch(`/notifications?page=${page}`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Access: auth_token
},
params: { page }
})
.then(data => data.json())
.then(data => {
var allData = this.state.notifications.concat(data.notifications);
this.setState({
notifications: allData,
page: this.state.page + 1,
});
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
fetch("/notifications/mark_as_read", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Access: auth_token
},
body: JSON.stringify({
notification: {
read: true
}
})
}).then(response => {
this.props.changeNotifications();
});
})
.catch(err => {
console.log(err);
});
}
> await is a reserved word (100:25)
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
^
fetch("/notifications/mark_as_read", {
You should refactor how you make your requests. I would have a common function to handle setting up the request and everything.
const makeRequest = async (url, options, auth_token) => {
try {
// Default options and request method
if (!options) options = {}
options.method = options.method || 'GET'
// always pass a body through, handle the payload here
if (options.body && (options.method === 'POST' || options.method === 'PUT')) {
options.body = JSON.stringify(options.body)
} else if (options.body) {
url = appendQueryString(url, options.body)
delete options.body
}
// setup headers
if (!options.headers) options.headers = {}
const headers = new Headers()
for(const key of Object.keys(options.headers)) {
headers.append(key, (options.headers as any)[key])
}
if (auth_token) {
headers.append('Access', auth_token)
}
headers.append('Accept', 'application/json')
headers.append('Content-Type', 'application/json')
options.headers = headers
const response = await fetch(url, options as any)
const json = await response.json()
if (!response.ok) {
throw json
}
return json
} catch (e) {
console.error(e)
throw e
}
}
appendQueryString is a little helper util to do the get qs params in the url
const appendQueryString = (urlPath, params) => {
const searchParams = new URLSearchParams()
for (const key of Object.keys(params)) {
searchParams.append(key, params[key])
}
return `${urlPath}?${searchParams.toString()}`
}
Now, to get to how you update your code, you'll notice things become less verbose and more extensive.
async infiniteNotification(page = 1) {
try {
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
const data = await makeRequest(
`/notifications`,
{ body: { page } },
auth_token
)
var allData = this.state.notifications.concat(data.notifications);
this.setState({
notifications: allData,
page: this.state.page + 1,
});
const markedAsReadResponse = makeRequest(
"/notifications/mark_as_read",
{
method: "POST",
body: {
notification: { read: true }
},
auth_token
)
this.props.changeNotifications();
} catch (e) {
// TODO handle your errors
}
}