I'm trying to connect to Solana mainnet using websockets. I can't find out how to connect using web3.js. Maybe someone faced this issue and can help me ?
Thanks
Here's a simple line of code I made:
let con = new web3.Connection('https://api.mainnet-beta.solana.com', { commitment: "confirmed", wsEndpoint: 'ws://api.mainnet-beta.solana.com' });
Check out this example for subscribing to websockets using web3 on the Solana Cookbook: https://solanacookbook.com/references/local-development.html#subscribing-to-websocket
function monitor() {
ws = new WebSocket(WSS_ENDPOINT)
ws.onopen = () => {
ws.send(
JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'programSubscribe',
params: [
address,
{
encoding: 'base64',
commitment: 'finalized',
},
],
})
)
}
the endpoint you want to use goes in that method entry.
now each time you want to react to something... you use
ws.on('message', (evt) => {
try {
const buffer = evt.toString('utf8')
console.log(buffer)
} catch (e) {
console.log(e)
}
})
}
Related
My current setup is as such:
I have connected to my postgres database and i also have the websocket connected fine to the frontend.
But I am not sure how to use the postgres-adapter as its suggested in the documentation:
They say that you make a pool instead of a Client - thats fine for the db - then you say you use the io.adapter(createAdapter(pool));
The main functionality I want to get at is - when a change occurs on the postgresdb - then a notification gets send out just as I have currently - but then it should be connected inside the websocket for the websocket to send a message with the data to all connected clients. Has anyone implemented this?
client.connect(err => {
if (err) {
console.log("Error in connecting database: ", err);
} else {
console.log("Database connected");
client.on('notification', (msg) => {
console.log(msg.payload);
console.log(msg)
});
const query = client.query("LISTEN update_notification");
}
})
const webSocketSetup = (server) => {
var io = new Server(server, {
cors: {
origin: [
'http://localhost:3000',
]
}
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.on('my message', (msg) => {
"" I Want the postgres Notification to be setup here. ""
});
});
}
I am facing a timeout issue with nestJs Httpservice.
The error number is -60 and error code is 'ETIMEDOUT'.
I am basically trying to call one api after the previous one is successfully.
Here is the first api
getUaaToken(): Observable<any> {
//uaaUrlForClient is defined
return this.httpService
.post(
uaaUrlForClient,
{ withCredentials: true },
{
auth: {
username: this.configService.get('AUTH_USERNAME'),
password: this.configService.get('AUTH_PASSWORD'),
},
},
)
.pipe(
map((axiosResponse: AxiosResponse) => {
console.log(axiosResponse);
return this.getJwtToken(axiosResponse.data.access_token).subscribe();
}),
catchError((err) => {
throw new UnauthorizedException('failed to login to uaa');
}),
);
}
Here is the second api
getJwtToken(uaaToken: string): Observable<any> {
console.log('inside jwt method', uaaToken);
const jwtSignInUrl = `${awsBaseUrl}/api/v1/auth`;
return this.httpService
.post(
jwtSignInUrl,
{ token: uaaToken },
{
headers: {
'Access-Control-Allow-Origin': '*',
'Content-type': 'Application/json',
},
},
)
.pipe(
map((axiosResponse: AxiosResponse) => {
console.log('SUCUSUCSCUSS', axiosResponse);
return axiosResponse.data;
}),
catchError((err) => {
console.log('ERRRORRRORROR', err);
// return err;
throw new UnauthorizedException('failed to login for');
}),
);
}
Both files are in the same service file. Strangely, when i call the second api through the controller like below. It works fine
#Post('/signin')
#Grafana('Get JWT', '[POST] /v1/api/auth')
signin(#Body() tokenBody: { token: string }) {
return this.authService.getJwtToken(tokenBody.token);
}
When the two api's are called, however, the first one works, the second one that is chained is giving me the timeout issue.
Any ideas?
Two things that made it work: changed the http proxy settings and used switchMap.
I'm using mock-socket to mock websockets calls.
I've got a test working but it only works for one test, then it says that the mock server is already listening on that url:
describe('mock socket method 1', () => {
let mockSocket;
let mockServer;
beforeEach(() => {
cy.visit('/', {
onBeforeLoad(win: Window): void {
// #ts-ignore
cy.stub(win, 'WebSocket', url => {
mockServer = new Server(url).on('connection', socket => {
console.log('mock socket connected');
mockSocket = socket;
});
if (!mockServer) return new WebSocket(url);
});
},
});
});
afterEach(() => {
mockSocket.close()
});
it('gets a message', () => {
const object = _createSettingsApiPutPayload(defaultSettingsState)
mockSocket.send(JSON.stringify(object));
cy.contains('Motion threshold')
});
it('gets a message', () => {
const object = _createSettingsApiPutPayload(defaultSettingsState)
mockSocket.send(JSON.stringify(object));
cy.contains('Motion threshold')
});
});
If I change the method to before() instead of beforeEach it works, but then I don't get a fresh environment for each test. I tried mockSocket.close() in afterEach() as you can see, but that doesn't work. I've tried cy.reload() but that gives a CORS error!
The error appears to be thrown at
> 15 | ReactDOM.render(
16 | <AppWrapper/>,
17 | document.getElementById('root'),
18 | );
AppWrapper is a AppContainer wrapped in redux's Provider, AppContainer connects App to redux, and here's App:
class App extends Component<AppProps> {
settingsSubscription: W3CWebSocket;
componentDidMount(): void {
// subscribe to websockets
this.settingsSubscription = this.subscribeToSettings(urls.SETTINGS_WS);
}
/**
* Sets up the websockets subscription to the settings.
* #param url the url of the websocket server
* #return the subscription object
*/
subscribeToSettings(url: string): W3CWebSocket {
let settingsSubscription = new W3CWebSocket(url);
settingsSubscription.onopen = () => console.log('WebSocket Client Connected (settings)');
settingsSubscription.onclose = () => console.log('WebSocket Client Disconnected (settings)');
settingsSubscription.onmessage = (message: MessageEvent) => this.handleSettingsMessage(message);
return settingsSubscription;
}
...
}
In the documentation they use mockServer.stop() to stop the mockServer instead of closing the mockSocket. That's what I am doing and most probably what you need as well.
Here's the snippet I am referring to:
// NOTE: this timeout is for creating another micro task that will happen after the above one
setTimeout(() => {
t.is(app.messages.length, 1);
t.is(app.messages[0], 'test message from mock server', 'we have subbed our websocket backend');
mockServer.stop(t.done);
}, 100);
Here's the link to the repo:
https://github.com/thoov/mock-socket/
I'm writing a Vue app that uses vue-apollo to interact with graphql. I'm wondering if it's possible to stub the graphql requests. I thought this should work:
it('should access a story', function() {
cy.server();
cy.route('http://localhost:3002/graphql', {
data: {
Story: { id: 2, title: 'story title', content: 'story content' }
}
});
cy.visit('/stories/2');
});
Unfortunately, I get an error from graphql complaining that id is an Int instead of an ObjectId. Am I missing something?
The problem was that stubbing fetch requests isn't yet implemented in Cypress (which is what Vue Apollo is using). I ended up following these instructions:
Install github/fetch
Add this to cypress/support/index.js:
.
Cypress.on('window:before:load', win => {
win.fetch = null;
win.Blob = null;
});
Now it works!
I got it working with this package here:
npm i #iam4x/cypress-graphql-mock
Add this line to 'support/commands.js'
import "#iam4x/cypress-graphql-mock";
go to your graphiql playground and download your schema
add task command to 'plugins/index.js' (REMEMBER TO CHANGE PATH TO SCHEMA FILE YOU DOWNLOADED EARLIER)
module.exports = (on, config) => {
on("task", {
getSchema() {
return fs.readFileSync(
path.resolve(__dirname, "../../../schema.graphql"),
"utf8"
);
}
});
};
write your tests with loaded schema
beforeEach(() => {
cy.server();
cy.task("getSchema").then(schema => {
cy.mockGraphql({
schema
});
});
});`
describe("Login Form", () => {
it("should redirect after login", () => {
cy.mockGraphqlOps({
operations: {
Login: {
login: {
jwt: "some-token",
user: {
id: "5d5a8e1e635a8b6694dd7cb0"
}
}
}
}
});
cy.visit("/login");
cy.getTestEl("email-input").type("Max Mustermann");
cy.getTestEl("password-input").type("passwort");
cy.getTestEl("submit").click();
cy.getTestEl("toolbar-title").should("exist");
});
})
Visit the original repo for further explanation as i find it less confusing. The package you have installed is just a working fork of this one:
https://github.com/tgriesser/cypress-graphql-mock
im having this issue where i send a request to the API to retrieve all users, the login function is called(index.vue) when called it tries to go to api/users/all which in this case should return all the users in that collection.
using Postman the API returns the correct results and if i console.log the output in the routeUsers before i send the response back, it outputs all the correct data to the console
when it returns to index.vue, the response status code is 0.
ive had a look online and some things are mentioning about CORS Headers but i dont think thats applicable to me and other things about the response has been cancelled,
can anyone shed some light on this for me and help me try to fix it?!
API main.js
var app = express();
var users = require('./routes/routeUsers');
app.use('/users', users);
module.exports = app;
api/models/users.js
var db = require('../Utilities/db')
module.exports.all = function(cb) {
var collection = db.get().collection('users')
collection.find().toArray(function(err, docs) {
cb(err, docs)
})
}
api/routes/routeUsers.js
var express = require('express')
, router = express.Router()
var user = require('../models/users');
router.get('/all', function(req, res) {
user.all(function(err, users) {
res.send(users);
})
})
Index.vue
export default {
data: function () {
return {
username: '',
password: '',
users: []
}
},
methods: {
login: function() {
Vue.http.get('/api/users/all').then((response) => {
console.log("SUCCESS",response);
this.users = response.body;
console.log(users);
}, function (error) {
console.log("Error", error.status); // handle error
});
}
}
};
The issue was that the inputs were in a form tag. removed Form tag and worked fine.