why is my web3 import not working properly? - mocha.js

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

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

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

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"
)

hyperledger composer deploy example code fails

Currently working with the latest releases of the hyperledger development environment and am working through the admin services. The example code for admin -> deploy is documented as:
// Deploy a Business Network Definition
var adminConnection = new AdminConnection();
var businessNetworkDefinition = BusinessNetworkDefinition.fromArchive(myArchive);
return adminConnection.deploy(businessNetworkDefinition)
.then(function(){
// Business network definition deployed
})
.catch(function(error){
// Add optional error handling here.
});
In the code as provided, the second line fails as BusinessNetworkDefinition is not a part of the composer-admin node module. I have two options for creating a BusinessNetworkDefinition, one is to use composer-client. This fails with the following message: TypeError: composerClient.BusinessNetworkDefinition is not a constructor
The code used for this attempt is summarized here:
'use strict';
var fs = require('fs');
var path = require('path');
var composer = require('composer-admin');
var composerClient = require('composer-client');
var composerCommon = require('composer-common');
var businessNetworkDefinition = new composerClient.BusinessNetworkDefinition();
The other option is to use composer-common, which fails with the following message: TypeError: businessNetworkDefinition.fromArchive is not a function
The code used for this attempt is:
var fs = require('fs');
var path = require('path');
var composer = require('composer-admin');
var composerClient = require('composer-client');
var composerCommon = require('composer-common');
var net_identifier = "zerotoblockchain-network#0.1.6";
var net_description = "Z2B network";
var net_package = require("../../../../network/package.json");
var net_readme = "../../../../README.md";
var businessNetworkDefinition = new composerCommon.BusinessNetworkDefinition(net_identifier, net_description, net_package, net_readme);
var archive = businessNetworkDefinition.fromArchive(req.body.myArchive);
where req.body.myArchive is the name of the archive file to be used in the fromArchive method. Inspecting the BusinessNetworkDefinition created via the new command shows the following:
object property: modelManager
object property: aclManager
object property: queryManager
object property: scriptManager
object property: introspector
object property: factory
object property: serializer
object property: metadata
So, two questions:
One: What was created with the new command and
Two: How do I correctly create a BusinessNetworkDefinition object which as a fromArchive() function in it?
The example code in the hyperledger composer documentation is flawed. Following is code which will successfully execute a business network deploy.
(1) Required definitions:
let fs = require('fs');
let path = require('path');
let composerAdmin = require('composer-admin');
const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefinition;
The following is written as an exportable, routable routine in nodejs and has been tested through from client (browser). Client passes in name of network to deploy. File layout is:
root/network/dist/network-archive-file.bna
(2) Read in the archive file and create an admin connection:
/**
* Deploys a new BusinessNetworkDefinition to the Hyperledger Fabric. The connection must be connected for this method to succeed.
* #param {express.req} req - the inbound request object from the client
* req.body.myArchive: _string - string name of object
* req.body.deployOptions: _object - string name of object
* #param {express.res} res - the outbound response object for communicating back to client
* #param {express.next} next - an express service to enable post processing prior to responding to the client
* returns composerAdmin.connection - either an error or a connection object
* #function
*/
exports.deploy = function(req, res, next) {
let newFile = path.join(path.dirname(require.main.filename),'network/dist',req.body.myArchive);
let archiveFile = fs.readFileSync(newFile);
let adminConnection = new composerAdmin.AdminConnection();
(3) Invoke the (asynchronous) fromArchive function and then deploy the result of the fromArchive invocation.
return BusinessNetworkDefinition.fromArchive(archiveFile)
.then(function(archive) {
adminConnection.connect(config.composer.connectionProfile, config.composer.adminID, config.composer.adminPW)
.then(function(){
adminConnection.deploy(archive)
(4). Respond to the (browser based) request:
.then(function(){
console.log('business network deploy successful: ');
res.send({deploy: 'succeeded'});
})
.catch(function(error){
console.log('business network deploy failed: ',error);
res.send({deploy: error});
});
... (5) and for anyone copying all the code, a few closing braces:
});
});
};

How to get started with socket.io?

Installed Node.js and socketio io (using npm). Node Hello World works.
Created app.js with the following line:
var io = require('socket.io')();
node node app.js throws exception:
io_test.js:1
ts, require, module, __filename, __dirname) { var io = require('socket.io')();
^
TypeError: object is not a function
How to fix?
OSX 10.7.5. Node.js 0.8.18.
Replace that line with
var io = require('socket.io').listen(8080);
Basically, if you read the error description, the require('socket.io') is returning an object, not a function that you can call. If you look at the example code on the socket.io website, you can see that you can call listen() on the object returned. So, you could also write it like this:
var sockio = require('socket.io')
var io = sockio.listen(8080)

Resources