Binance Futures API: Signature is not valid - javascript

I'm currently developing a trading bot for fun, but when I want to send a POST request with axios I get following error as a response: {code: -1022, msg: 'Signature for this request is not valid.'}
I use the node.js crypto package to create a hmac sha256 hash like mentionend in the binance api docs and in every other tutorial i've seen.
I also already created a new API, so my key & secret is correct!
Here's the code:
let querystring = `symbol=LTCUSDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity=0.05&price=${price}&recvWindow=5000&timestamp=${new Date().getTime()}`;
let signature = crypto
.createHmac('sha256', credentials.secret)
.update(querystring)
.digest('hex');
axios
.post(
`https://fapi.binance.com/fapi/v1/order?${querystring}&signature=${signature}`,
{},
{
headers: {
'X-MBX-APIKEY': credentials.key,
'content-type': 'application/x-www-form-urlencoded',
},
}
)
.then((response) => {
console.log(response.data);
resolve(response);
})
.catch(function (error) {
if (error.response) {
// Request made and server responded
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
});

Related

Localhost Fetch request failing

I have a flask api (running on host='0.0.0.0', port=8080, which should cause it to run on my priv ip), and a javascript fetch request, which when called isnt able to reach the api for some reason. The javascript is running in a webpage hosted on http://127.0.0.1:5500. Yes I have tried curl and it works perfectly. The code for the fetch request is
const lbutton = document.getElementById("lbutton");
lbutton.addEventListener("click", function() {
console.log('button clicked');
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
fetch('http://not gonna give out my ip:8080/api/log', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({email: email, password: password})
})
.then(response => {
console.log('Success:', response);
if (response.ok) {
console.log('worked');
} else {
throw new Error('Server response was not OK');
}
})
.catch(error => {
console.error('Error:', error);
});
});
Can someone explain to me why it is not working, I have been trying to figure out how to do this for ages.
I tried to make it send a POST request to my api, which should work and the api should receive login info, but the request is not making it through at all.
The fetch api is making a GET request to http://127.0.0.1:5500/login.html?email=test#gmail.com&password=test

Axios call to Springboot backend responding is not forwarding to new page after returning response

My postmapping "login" in my controller is returning a 200. But I'm getting undefined and I believe it is from my axios call. I know that the undefined error is being reported from the catch block in the console
Axios call -
submit() {
let formData = new FormData();
formData.set("email", this.email)
formData.set("password", this.password)
formData.set("staySignedIn", this.staySignedIn)
// When the client/server sides are running from the same port (AWS) the url for this api call should be changed to /api/v1/login
axios.post("http://localhost:8080/api/v1/login", formData,
{headers: {'Content-Type': 'application/json'}})
.then(function (res) {
console.log(res); // test
if (res.data.code === 200) {
this.router.push('/dashboard')
console.log("success");
} else {
console.log(res.data.code);
}
})
.catch(function (err) {
console.log(err);
})
}
Response from dev tools
Response from test
Axios response schema documentation is here
Unless you have a key code in your controller response, response.data.code will be undefined.
Try res.status instead if you want to check the HTTP status.
axios.post("http://localhost:8080/api/v1/login", formData,
{headers: {'Content-Type': 'application/json'}})
.then(function (res) {
if (res.status === 200) {
this.router.push('/dashboard')
console.log("success");
} else {
console.log(res.status);
}
})
.catch(function (err) {
console.log(err);
})
EDIT
You seem to be sending back the password back in the response. Even though the password is encrypted, better restrict exposing it in the response.

Azure Function axios POST empty Response

I am trying to make an axios call in my React frontend to get some information from the backend to access some information. When I log the response on the server, I see the required information, but in the axios call, I get data = "" for some reason.
ReactJS Axios call
await axios
.post(url, {
token: this.props.authUser.idToken.rawIdToken,
blob_path: blobPath,
container: container
},
config
)
.then((response) => {
if(response.data == ""){
console.log("nada");
debugger;
}
callback(response);
})
.catch((error) => {
debugger;
callback(error);
});
Azure Server Response Code
exit = (result) => {
console.log("---------- RESULT ------------");
console.log(result);
console.log("------ END RESULT ------------");
context.res = {
status: 200 /* Defaults to 200 */,
body: result,
headers: { 'Content-Type': 'application/json' },
};
context.done();
};
The response on the backend
The response on the frontend
EDIT: Axios is sending double requests and the old request's response gets ignored.

Firebase 'Unhandled Rejection' and 'Can't set headers after they are set' JavaScript error

Firstly, please note that I am very very new to JS and coding as a general :)
Desired behaviour:
I have written the following JS HTTPS Firebase function which, which takes in a query parameter locationId, it performs a GET API call and saves the response back to Firebase. The code correctly saves the data to Firebase as desired. I have come across similar issues but i'm struggling to adapt those solutions to my specific issue below. From what I see, I'm only sending the response once.
Specific error: The following is the console output
Cannot set headers after they are sent to the client
Unhandled rejection
My function:
exports.doshiiGetMenuForOnboardedVenue = functions.https.onRequest((req, res) => {
// Forbidding PUT requests.
if (req.method === 'PUT') {
return res.status(403).send('Forbidden!');
}
cors(req, res, () => {
const locationId = req.query.locationId;
console.log('locationId', locationId);
if (locationId){
console.log('locationId', locationId);
var token = jwttoken();
const options = {
headers: {
'content-type': 'application/json',
'authorization': 'Bearer ' + token}
};
const uri = 'https://sandbox.doshii.co/partner/v3/locations/' + locationId + '/menu?lastVersion=:lastVersion&filtered=true'
axios.get(uri, options)
.then(response => {
return admin.database().ref(`/venue-menus/${locationId}/`).set(response.data)
.then(response => {
return res.status(200).send(locationId)
})
.catch(err => {
return res.status(500).send({error: err})
})
})
.then(response => {
return res.status(200).send(locationId)
})
.catch(err => {
return res.status(500).send({error: err})
})//end axios
} else {
return res.status(500).send({error: 'locationId missing'})
}//end if-else (!locationId)
})//end cors
});
By flattening out your nested promises, you can see that your code is performing the following instructions (when the axios call doesn't throw an error):
admin.database().ref(`/venue-menus/${locationId}/`).set(response.data))
.then(response => res.status(200).send(locationId))
.catch(err => res.status(500).send({error: err})
.then(response => res.status(200).send(locationId)) // this line is always called after either of the above.
.catch(err => res.status(500).send({error: err})
As general practice, unless required, you should not nest promises with their own then() and catch() handlers as it will lead to bizarre effects like this.
Furthermore, if your code calls for using //end axios or //end cors messages, you should flatten out your code so it makes sense without those messages.
Adapting your code to "fail fast", correcting your API responses and appropriately hiding error stack traces gives:
const cors = require('cors')({
origin: true,
methods: ["GET"]
});
exports.doshiiGetMenuForOnboardedVenue = functions.https.onRequest((req, res) => {
cors(req, res, (err) => { // note: cors will handle OPTIONS method
if (err) {
// note: log full error at ERROR message level
console.error('Internal CORS error:', err);
// note: return only generic status message to client
return res.status(500).json({error: 'Internal Server Error'});
}
// Forbidding anything but GET requests.
if (req.method !== 'GET') {
// 405 METHOD_NOT_ALLOWED
return res.status(405)
.set('Allow', 'GET')
.json({error: 'Not Allowed!'});
}
const locationId = req.query.locationId;
console.log('locationId', locationId);
if (!locationId) {
// 400 BAD_REQUEST
return res.status(400).json({error: 'locationId missing'})
}
var token = jwttoken();
const options = {
headers: {
'content-type': 'application/json',
'authorization': 'Bearer ' + token
}
};
// note: Don't forget to enable billing for third-party APIs!
const uri = 'https://sandbox.doshii.co/partner/v3/locations/' + locationId + '/menu?lastVersion=:lastVersion&filtered=true'
axios.get(uri, options)
.then(response => admin.database().ref(`/venue-menus/${locationId}/`).set(response.data))
.then(() => {
// note: as locationId was already sent by the client, send new/useful
// information back or nothing but the right status code
res.status(200).json({ ref: `/venue-menus/${locationId}/` });
})
.catch(err => {
// note: log full error at ERROR message level
console.error('Failed to retrieve/save API data:', err);
// note: return only message to client
res.status(500).json({error: err.message || 'Internal Server Error'});
});
});
});

How to programmatically connect to AWS websocket API Gateway

I am trying to implement messaging between users on my website by leveraging AWS's websocket api gateway. Every guide/documentation that I look at says to use wscat to test the connection to the gateway. I am at the point where I can connect to the api gateway and send messages between clients using wscat but am struggling to get it working programmatically from my ts code.
What I want to do is make an api call to the websocket api gateway once the user logs in so they can send messages at any point. I am using serverless for my backend and Angular 6 for the front end. I read that I need to make a POST request to https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/#connections/{connection_id} to send messages through a websocket connection but i'm having trouble using typescript in a service I created to connect/get a connection id.
I am making a second API call after the user successfully logs in to open a connection to the websocket api gateway. I tried calling a function that makes a post request with no body (not sure what I would send in the body of the request since I've only connected to it using the wscat tool) to the URL I get after deploying my serverless code. I also tried making a POST request to the https:// URL I see in the AWS console after manually deploying the API gateway.
base.service.ts
protected getBaseSocketEndpoint(): string {
// 'wss://xxxxxxx.execute-api.us-east-1.amazonaws.com/dev' <-- tried this too
return 'https://xxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/#connections';
}
authentication.service.ts
this.authService.login(username, password).pipe(first()).subscribe(
(response) => {
console.log(response);
this.authService.setCookie('userId', response.idToken.payload.sub);
this.authService.setCookie('jwtToken', response.idToken.jwtToken);
this.authService.setCookie('userEmail', response.idToken.payload.email);
this.authService.setCookie('refreshToken', response.refreshToken.token);
this.toastr.success('Login successful. Redirecting to your dashboard.', 'Success!', {
timeOut: 1500
});
this.authService.connectToWebSocket(response.idToken.payload.sub).pipe(first()).subscribe(
response => {
console.log(response);
}
);
this.routerService.routeToUserDashboard();
},
(error) => {
// const errorMessage = JSON.parse(error._body).message;
this.toastr.error("Incorrect username and password combination.", 'Error!', {
timeOut: 1500
});
}
);
authentication.service.ts extends BaseService
public connectToWebSocket(userId: string): Observable<any> {
const body = {
userId: userId
};
console.log('calling connectToWebSocket()..');
return this.http.post(this.getBaseSocketEndpoint(), body).pipe(map(response => {
console.log(response);
}));
}
serverless.yaml
functions:
connectionHandler:
handler: connectionHandler.connectionHandler
events:
- websocket:
route: $connect
cors: true
- websocket:
route: $disconnect
cors: true
defaultHandler:
handler: connectionHandler.defaultHandler
events:
- websocket:
route: $default
cors: true
sendMessageHandler:
handler: messageHandler.sendMessageHandler
events:
- websocket:
route: sendMessage
cors: true
connectionHandler.js (lambda)
const success = {
statusCode: 200,
headers: { "Access-Control-Allow-Origin": "*" },
body: "everything is alright"
};
module.exports.connectionHandler = (event, context, callback) => {
var connectionId = event.requestContext.connectionId;
if (event.requestContext.eventType === "CONNECT") {
addConnection(
connectionId,
"b72656eb-db8e-4f32-a6b5-bde4943109ef",
callback
)
.then(() => {
console.log("Connected!");
callback(null, success);
})
.catch(err => {
callback(null, JSON.stringify(err));
});
} else if (event.requestContext.eventType === "DISCONNECT") {
deleteConnection(
connectionId,
"b72656eb-db8e-4f32-a6b5-bde4943109ef",
callback
)
.then(() => {
console.log("Disconnected!");
callback(null, success);
})
.catch(err => {
callback(null, {
statusCode: 500,
body: "Failed to connect: " + JSON.stringify(err)
});
});
}
};
// THIS ONE DOESNT DO ANYHTING
module.exports.defaultHandler = (event, context, callback) => {
callback(null, {
statusCode: 200,
body: "default handler was called."
});
};
const addConnection = (connectionId, userId, callback) => {
const params = {
TableName: CHATCONNECTION_TABLE,
Item: {
connectionId: connectionId,
userId: userId
}
};
var response;
return dynamo
.put(params, function(err, data) {
if (err) {
errorHandler.respond(err, callback);
return;
} else {
response = {
statusCode: 200,
headers: { "Access-Control-Allow-Origin": "*" },
body: JSON.stringify(data)
};
callback(null, response);
}
})
.promise();
};
const deleteConnection = (connectionId, userId, callback) => {
const params = {
TableName: CHATCONNECTION_TABLE,
Key: {
connectionId: connectionId,
userId: userId
}
};
var response;
return dynamo
.delete(params, function(err, data) {
if (err) {
errorHandler.respond(err, callback);
return;
} else {
response = {
statusCode: 200,
headers: { "Access-Control-Allow-Origin": "*" },
body: JSON.stringify(data)
};
callback(null, response);
}
})
.promise();
};
Expected: trigger POST api call and open a persistent connection with the Websocket API Gateway.
Actual: unable to connect via API call above. I get a 403 in the console with the message:
Access to XMLHttpRequest at 'https://xxxxxxx.execute-api.us-east-1.amazonaws.com/dev/#connections' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Not sure why im getting a CORS error when I have CORS enabled in my serverless file.
I had a similar problem. You can use all the socket.io-client goodness. But you have to set the option transports to :
let socket = io(url, {
reconnectionDelayMax: 1000,
transports: ["websocket"],
});
The default is
transports: ["polling", "websocket"],
So your app will kick off polling with the resulting in a CORS error. It's not that clear in the docs, but here is a useful link.
Look under "Available options for the underlying Engine.IO client:".
I had the same problem and finally figured out, that normally there should not be such a CORS error message with websockets:
Why is there no same-origin policy for WebSockets? Why can I connect to ws://localhost?
Skipping the client library "socket.io" and using "vanilla websockets" helped me out.
In your case I would check the libraries behind "connectToWebSocket".
I used python lambda handler, so it might be helpful to many.
I have implemented a websocket which sends user some message 5 times with a gap
serverless.yml
service: realtime-websocket-test
provider:
name: aws
stage: ${opt:stage, 'dev'}
runtime: python3.8
region: ${opt:region, 'ap-south-1'}
memorySize: 128
timeout: 300
functions:
connect:
handler: handler.lambda_handler
events:
- websocket:
route: $connect
- websocket:
route: $disconnect
- websocket:
route: $default
handler.py
import time
import json
import boto3
def lambda_handler(event, context):
print(event)
event_type = event["requestContext"]["eventType"]
if event_type == "CONNECT" or event_type == "DISCONNECT":
response = {'statusCode': 200}
return response
elif event_type == "MESSAGE":
connection_id = event["requestContext"]["connectionId"]
domain_name = event["requestContext"]["domainName"]
stage = event["requestContext"]["stage"]
message = f'{domain_name}: {connection_id}'.encode('utf-8')
api_client = boto3.client('apigatewaymanagementapi', endpoint_url = f"https://{domain_name}/{stage}")
for _ in range(5):
api_client.post_to_connection(Data=message,
ConnectionId=connection_id)
time.sleep(5)
response = {'statusCode': 200}
return response

Categories

Resources