The Coinbase addresses API endpoint returns mostly empty data - coinbase-api

I'm trying to get the addresses for my Coinbase wallets. I'm using node/axios. I'm grabbing accounts from the "accounts" endpoint and then calling the "addresses" endpoint with each account's id field.
The js code looks like this:
const getAccounts = async (auth) => {
const options = {
headers: {
'Authorization': 'Bearer ' + auth.access_token
}
};
let response = await axios.get(
'https://api.coinbase.com/v2/accounts', options
);
await getWallets(auth, response.data.data);
}
const getWallets = async (auth, accounts) => {
const options = {
headers: {
'Authorization': 'Bearer ' + auth.access_token
}
};
for (const account of accounts) {
console.log(`https://api.coinbase.com/v2/accounts/${account.id}/addresses`);
const url = `https://api.coinbase.com/v2/accounts/${account.id}/addresses`;
console.log('Wallets for ' + account.name);
try {
const response = await axios.get(url, options);
console.log(response.data);
} catch (e) {
console.log(e);
}
}
}
That results in a ton of rows that have an empty "data" array, like this:
Wallets for DOGE Wallet
{
pagination: {
ending_before: null,
starting_after: null,
previous_ending_before: null,
next_starting_after: null,
limit: 25,
order: 'desc',
previous_uri: null,
next_uri: null
},
data: [],
warnings: [
{
id: 'missing_version',
message: 'Please supply API version (YYYY-MM-DD) as CB-VERSION header',
url: 'https://developers.coinbase.com/api#versioning'
}
]
}
It seems like XLM is the only account that actually comes through with data. Any thoughts?

Related

MongoDB / ReactJS Patch handler / findOneAndUpdate not working

in the following code, I'm attempting to update the Checkpoints field for one of my objects within the projects collection. UpdatedCheckpoints is working correctly, so I believe the first block of code works. But the change isn't logging to the database so it doesn't persist. What's going wrong?
const onApprovedSubmit = useCallback(
async (e) => {
e.preventDefault();
let updatedCheckpoints = props.project.Checkpoints;
updatedCheckpoints[props.checkpointIndex].checkpointSubmitted = true;
console.log('here');
try {
let projectId = props.project._id;
await fetcher('/api/projects', {
method: 'PATCH',
headers: { 'Content-type': 'application/json' },
body: JSON.stringify({ Checkpoints: updatedCheckpoints }),
id: projectId,
});
toast.success('Your checkpoint has been updated');
} catch (e) {
toast.error(e.message);
}
},
[props],
);
handler.patch(async (req, res) => {
const db = await getMongoDb();
const project = await updateProjectById(db, req.id, req.body);
res.json({ project });
});
export async function updateProjectById(db, id, data) {
return db
.collection('projects')
.findOneAndUpdate(
{ _id: new ObjectId(id) },
{
$set: data,
},
{ returnDocument: 'after' },
)
.then(({ value }) => value);
}

Redux Saga call api before token is set

I m trying to implements a react application with authentification using keycloak, all sounds good but when I refresh the page and there is fetching of an api, Saga perform the call before the token is set
there is my saga call
function* getAPI(action) {
const state = yield select();
try {
let response = yield call(
axiosRequest,
"get",
BaseURL,
`/foo/mini`,
{},
setAuthorizationBearer(state.auth.token),
{ sendToken: true },
"application/json"
);
yield put({ type: `${action.type}_SUCCESS`, payload: response, metadata: action.metadata })
} catch (e) {
yield put({ type: `${action.type}_ERROR`, payload: e })
}
}
and here is my axios request instance
import axios from "axios";
let authorizationBearer = null;
export const setAuthorizationBearer = token => {
authorizationBearer = token;
};
const instance = (
method,
baseURL = process.env.REACT_APP_ENDPOINT,
url,
data = null,
headers = null,
sendToken = true,
contentType
) => {
return new Promise((resolve, reject) => {
const p = {
sendToken: sendToken.sendToken,
data: {
...data,
},
};
const req = axios.create({
method,
baseURL,
url,
timeout: 30000,
headers: headers,
crossDomain: true,
});
headers = {};
if (p.sendToken && authorizationBearer) {
headers.Authorization = `Bearer ${authorizationBearer}`;
headers["Content-Type"] = contentType;
}
req({
method,
baseURL,
url,
data,
headers,
sendToken,
})
.then((payload) => {
if (payload) {
if (payload.status < 400) {
resolve(payload);
} else {
reject(payload);
}
} else {
reject(payload);
}
})
.catch((e) => {
if (axios.isCancel(e)) {
console.log("Request canceled", e.message);
} else {
// handle error
}
reject(e);
});
});
};
export default instance;
And finally i set my token on authentification with a dispatch
const dispatch = useDispatch()
<ReactKeycloakProvider onTokens={({token}) => dispatch(authUser(token))} authClient={Keycloak(config)}
initOptions={{
onLoad: 'login-required',
checkLoginIframe: false,
timeSkew: "0",
refreshToken: ""
}}
LoadingComponent={<div />}
>
....
</ReactKeycloakProvider>
Most probably the application content is being rendered before the onTokens is being executed. Try checking on the existence of the token in the store state before rendering anything (or show a loading screen).

how to solve problem with oAuth Zoom in Nextjs?

I am trying to authenticate the user in order to get data to use to create or update meetings later. but it full of errors.
Here I am sending Post Requests in order to get the AccessToken and then get the UserData as props.
export async function getServerSideProps(res){
const oauth = async() => {
const zoomUserData = [];
const b = Buffer.from(process.env.ZOOM_API_KEY + ":" + process.env.ZOOM_API_SECRET);
const zoomRes = await fetch(`https://zoom.us/oauth/token?grant_type=authorization_code&code=${req.body.code}&redirect_uri=${process.env.ZOOM_REDIRECT_URL}`, {
method: "POST",
headers: {
Authorization: `Basic ${b.toString("base64")}`,
},
});
const zoomData = await zoomRes.json();
const zoomUserRes = await fetch("https://api.zoom.us/v2/users/me", {
method: "GET",
headers: {
Authorization: `Bearer ${zoomData.access_token}`,
},
});
const zoomUserData = await zoomUserRes.json();
/*
Encrypt and store below details to your database:
zoomUserData.email
zoomUserData.account_id
zoomData.access_token
zoomData.refresh_token
zoomData.expires_in // convert it to time by adding these seconds to current time
*/
}
return{
props:{zoomUserData}
}
}
and then i am passing the props to a page component like that :
export default function Meeting({zoomUserData}) {
const router = useRouter();
useEffect(() => {
if (router.query.code) {
fetch('/connectZoom',
{ method: 'POST',
headers: {
'ContType': 'application/json',
},
body: JSON.stringify({ code: router.query.code }),
}).then(() => {
console.log("success")
}).catch(() => {
console.log("No!")
});
}
}, [router.query.code]);
console.log(zoomUserData)
return (
<a href={`https://zoom.us/oauth/authorize?response_type=code&client_id=${process.env.ZOOM_API_KEY}&redirect_uri=${process.env.ZOOM_REDIRECT_URL}`}>
Connect Zoom
</a>
)
}

Can't send image to azure API

I'm making OCR app using amazon. App I'm doing using react native. And I have an error on the moment when I send data.
Error:
{
"code": "InvalidImageUrl",
"requestId": "c495b0d7-a65a-4138-97a9-2b1cb25dced8",
"message": "Image URL is badly formatted."
}
Why? What am I doing wrong? Code:
// ...
selectImage() {
ImagePicker.showImagePicker(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
const source = { uri: response.uri };
this.setState({ imageSource: source });
this.extractText(response.uri);
}
});
}
extractText = async (imageSource) => {
// alert(imageSource)
let subscriptionKey = ['CODE'];
let endpoint = ['ENDPOINT']
if (!subscriptionKey) { throw new Error('Set your environment variables for your subscription key and endpoint.'); }
var uriBase = endpoint + "vision/v2.1/ocr";
// Request parameters.
// Display the image.
var sourceImageUrl = imageSource;
const data = new FormData();
data.append(imageSource);
fetch(uriBase + "?" + {
"language": "unk",
"detectOrientation": "true",
},
{
method: 'POST',
headers:
{
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': subscriptionKey,
},
body: '{"url": ' + '"' + data + '"}',
}).then((response) => response.json()).then((data) =>
{
console.log(JSON.stringify(data, null, 2));
}).catch((error) =>
{
console.log(error);
});
};
}
export default ImagePickerScreen;
Based on your code,there is something wrong with your data,it should an image URL so that Azure Version service can access it . I am not quite sure that how you get data in your custom logic . But anyway , this snippet below works , pls have a try :
const data = 'https://stanstroage.blob.core.windows.net/container2/personPic.jpg';
let subscriptionKey = '<key>';
let endpoint = '<endpoint>';
if (!subscriptionKey) { throw new Error('Set your environment variables for your subscription key and endpoint.'); }
var uriBase = endpoint + "vision/v2.1/ocr";
fetch(uriBase + "?" + {
"language": "unk",
"detectOrientation": "true",
},
{
method: 'POST',
headers:
{
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': subscriptionKey,
},
body: '{"url": ' + '"' + data + '"}',
}).then((response) => response.json()).then((data) =>
{
console.log(JSON.stringify(data, null, 2));
}).catch((error) =>
{
console.log(error);
});
Result:
If you want to upload a local image, you should use application/octet-stream as request content-type and set image content buffer as request body.
You can use react-native-fs to read your local image content and use buffer to get image content buffer and post it to Azure side , try snippet below below :
let subscriptionKey = '<key>';
let endpoint = '<endpoint>';
let fileUri = '<fileUri>';
let base64 = await fs.readFile(fileUri, 'base64');
let data = Buffer.from(base64, 'base64');
console.log(data);
if (!subscriptionKey) { throw new Error('Set your environment variables for your subscription key and endpoint.'); }
var uriBase = endpoint + "vision/v2.1/ocr";
fetch(uriBase + "?" + {
"language": "unk",
"detectOrientation": "true",
},
{
method: 'POST',
headers:
{
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key': subscriptionKey,
},
body: data,
}).then((response) => response.json()).then((data) =>
{
console.log(JSON.stringify(data, null, 2));
}).catch((error) =>
{
console.log(error);
});
Result :

Proxy to express - 500-timeout - Server code is executed more then once

I don't know what is going on. When i try to send request to the backend to add follower(my route bellow), I get server tiemout error instead of sucess, but in my database the follower is added correctly(and removed), buuuut not always. Sometimes it saves 3 times the same result(follower to db), or sometimes doesn't delete the follower.
And the problem is that i have no idea what's is going on.
In my console i have this error sometimes i see this:
[HPM] Error occurred while trying to proxy request /api/users/user/follow from 127.0.0.1:8080 to http://[::1]:1648 (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)
setFollower route:
const setFollowing = async (req, res, next) => {
try {
const userId = req.body.userId;
const followId = req.body.followId;
await User.findByIdAndUpdate(
userId,
{
$push: {
following: followId,
},
},
);
next();
} catch (err) {
res.status(400).json({
error: err,
});
}
};
const setFollower = async (req: Request, res: Response) => {
try {
const followId = req.body.followId;
const userId = req.body.userId;
const result = await User.findByIdAndUpdate(
followId,
{
$push: {
followers: userId,
},
},
{ new: true },
)
.populate('following', '_id name')
.populate('followers', '_id name')
const followerResult = { ...result._doc };
const { photo, salt, passwordHash, ...rest } = followerResult;
return res.status({ ...rest });
} catch (err) {
res.status(400).json({
error: err,
});
}
};
router.put(
'/user/follow',
isUserSignIn,
setFollowing,
setFollower,
);
sending request on button click
try {
setLoading(true);
const response = await fetch('/api/users/user/follow', {
body: JSON.stringify({
followId: params.userId,
userId: loggedInUser._id,
}),
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
method: 'PUT',
});
const data = await response.json();
setLoading(false);
setFollowing(true);
} catch (err) {
if (err.message) {
setServerError(err.message);
} else {
setServerError(JSON.stringify(err));
}
}
my repo: https://github.com/bartek-fecko/fullstackapp
for my assumption, you're using express, given the logs you have in your question. The
key is to set the timeout property on server (the following sets the timeout to one
second, use whatever value you want):
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
server.timeout = 1000;

Resources