How do I connect to an Infura web socket in Ethers.js? - websocket

I know in Web3js you can connect to an Infura web socket like so:
const Web3 = require('web3')
const web3 = new Web3(
new Web3.providers.WebsocketProvider("wss://mainnet.infura.io/ws/v3/<project_id>")
)
but how do I connect using Ethers.js? I've tried searching the internet but the answer isn't immediately obvious.

Found it in the Ether.js docs:
const provider = new ethers.providers.WebSocketProvider(
"wss://mainnet.infura.io/ws/v3/<project_id>"
)
the mainnet is used by default, but you can specify also specify a test network:
// Using a test network
const provider = new ethers.providers.WebSocketProvider(
"wss://rinkeby.infura.io/ws/v3/<project_id>", "rinkeby"
)

Related

NEAR Protocol JsonRpcProvider(url?: string) deprecated use `JsonRpcProvider(connectionInfo: ConnectionInfo)` instead

I'm initiating API/RPC connection to NEAR Protocol using JsonRpcProvider like that:
const provider = new nearAPI.providers.JsonRpcProvider(
`https://rpc.${networkId}.near.org`
)
I'm getting this warning
JsonRpcProvider(url?: string) deprecated use `JsonRpcProvider(connectionInfo: ConnectionInfo)` instead index.js:18:18
I can't find any example of how to use it in JS. The only ConnectionInfo object I could found is https://near.github.io/near-api-js/interfaces/utils_web.connectioninfo.html
The way you can use it is like that:
let connInfo = { url: "https://rpc.${networkId}.near.org" }
// sets up a NEAR API/RPC provider to interact with the blockchain
const provider = new nearAPI.providers.JsonRpcProvider(connInfo)

Track Solana wallet change in Web

I'm building a Web3 app while using Solana.
I'm using #solana/wallet-adapter for wallet connection
Code:
const Wallet = ({ children }) => {
// The network can be set to 'devnet', 'testnet', or 'mainnet-beta'.
const network = WalletAdapterNetwork.Devnet;
// You can also provide a custom RPC endpoint.
const endpoint = useMemo(() => clusterApiUrl(network), [network]);
// #solana/wallet-adapter-wallets includes all the adapters but supports tree shaking and lazy loading --
// Only the wallets you configure here will be compiled into your application and only the dependencies
// of wallets that your users connect to will be loaded.
const wallets = useMemo(
() => [
new PhantomWalletAdapter(),
new SlopeWalletAdapter(),
new SolflareWalletAdapter(),
new TorusWalletAdapter(),
new LedgerWalletAdapter(),
new SolletWalletAdapter({ network }),
new SolletExtensionWalletAdapter({ network }),
],[network]);
return (
<ConnectionProvider endpoint={endpoint}>
<WalletProvider wallets={wallets} autoConnect>
<WalletModalProvider>
<WalletMultiButton />
<WalletDisconnectButton />
{children}
</WalletModalProvider>
</WalletProvider>
</ConnectionProvider>
);
};
It's a basic components. Same as a presented in #solana/wallet-adapter docs
The problem:
After connecting some wallet manager(let's say Phantom, for instance), I'm getting all the information I need. But after changing wallet -- I don't see any updates in my app.
The question is
How can I handle this?
After a couple of days of research, I came to the conclusion that this is an API bug.
I found a way that allows you to find out if the account has changed or not. It can be used if it is critical for you:
const isAccountChanged = window.solana.publicKey.toBase58() !== `${your_current_public_key}`;
if (isAccountChanged) {
// do some updates
}
For now, you can create setInterval(for instance) to detect these changes. So, if isAccountChanged = true -> you need to update the users state. If it's still false -> you can wait.
fyi:
https://github.com/solana-labs/wallet-adapter/issues/49
https://github.com/solana-labs/wallet-adapter/pull/109

why is my web3 import not working properly?

I am using truffle with mocha to test my smart contract. I have required web3 like so
const web3 = require('web3')
the import seems only to work partially.
for example, this statement works just fine
const amount = web3.utils.toWei('0.23')
however this statement
const balance = await web3.eth.getBalance(myContract.address)
causes the following error message:
TypeError Cannot read property 'getBalance' of undefined.
Moreover, Visual Studio Code gives me the following error message if I hover of the word eth in this following code:
web.eth.getBalance(myContract.address)
Property 'eth' does not exist on typeof import (/Users/eitanbronschtein/Desktop/fundraiser/node_modules/web3/types/index)
I am using javascript and not typescript.
What is going on?
web3 does not work without provider. install ganach-cli
const ganache = require("ganache-cli");
const Web3 = require("web3");
// this is in local ganache network gasLimit has to be set to 10million and and factory gas must be 10million
// if u get error about gasLimit, this keep changing. look for docs
const web3 = new Web3(ganache.provider({ gasLimit: 10000000 }));
If you set truffle suit, you should have "test" directory in your project and web3 would be already set and available globally
From https://web3js.readthedocs.io/en/v1.7.5/web3.html:
The Web3 class is an umbrella package to house all Ethereum related modules.
var Web3 = require('web3');
// "Web3.providers.givenProvider" will be set if in an Ethereum supported browser.
var web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546');
//now you can do web3.eth

Embedded node-red in a feathersjs application get websocket error

I can embed node-red with a custom service with the following node-red.service.js :
// Initializes the `node-red` service on path `/red`
const { NodeRed } = require('./node-red.class');
const hooks = require('./node-red.hooks');
const RED = require("node-red");
module.exports = function (app) {
const paginate = app.get('paginate');
const options = {
paginate
};
// Create the node-red settings object
const settings = {
httpAdminRoot:"/red",
httpNodeRoot: "/red",
userDir: "./red",
functionGlobalContext: { } // enables global context
};
// Initialise the runtime with a server and settings
RED.init(app,settings);
// Serve the editor UI from /red
app.use('/red' , RED.httpAdmin );
RED.start()
};
If I go to localhost:3030/red I get the node-red page, but after few seconds it lost connection to server with the following error:
WebSocket connection to 'ws://localhost:3030/red/comms' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
I think there is a problem serving thru websocket or maybe since /red/comms is not defined in feathersjs it can't connect. Any idea?
Thank you
The issue comes with this line:
// Initialise the runtime with a server and settings
RED.init(app,settings);
As the comment says, you need to initialise the runtime with a server object. Here you are passing it an Express application, not a server.
It is not possible to mount websocket listeners on an express app - Node-RED needs access to the underlying HTTP Server object.
I am not familiar with what apis featherjs provides, but it does appear to allow you access to the http server object - for example by calling app.listen yourself - https://docs.feathersjs.com/api/express.html#app-listen-port

What is the purpose of a resource in a WebSocket URL?

Looking at the W3 spec on WebSockets, I see
var socket = new WebSocket('ws://game.example.com:12010/updates');
socket.onopen = function () {
setInterval(function() {
if (socket.bufferedAmount == 0)
socket.send(getUpdateData());
}, 50);
};
I understand that the socket services lives on port 12010 at game.example.com, but what is the purpose of the '/updates' resource in the URL? If the service lives at some port, what good will a resource do?
You can expose different logical WebSockets on the same port, using different URI's.
Lets take chat as an example. You could use the URI to determine the particular channel or chat room you want to join.
var socket = new WebSocket('ws://chat.example.com/games');
var socket = new WebSocket('ws://chat.example.com/movies');
var socket = new WebSocket('ws://chat.example.com/websockets');
You can also use query strings. Imagine a stock ticker:
var socket = new WebSocket('ws://www.example.com/ticker?code=MSFT');
var socket = new WebSocket('ws://www.example.com/ticker?code=GOOG');

Resources