Undefined web3.eth.getAccounts() in React Native, metamask authentication - javascript

I want to authenticate the user by his Metamask wallet. I am using web3 package in order to interact with the blocks and sign transactions. When I try to get the user accounts I get an empty result:
const Web3 = require('web3');
const web3 = new Web3(
new Web3.providers.HttpProvider('https://api.avax.network/ext/bc/C/rpc')
);
const addresses = await web3.eth.getAccounts();
I suppose that I need to request the accounts like this await window.ethereum.request({ method: 'eth_requestAccounts'}); but it doesn't exist window mobile app.
I guess in a normal flow the user hit the auth button and will be redirected to Metamask wallet to authorize the app, how can I do this?

You are correct, but you also need to connect to MetaMask, not your own RPC. Here is your fixed code:
import detectEthereumProvider from '#metamask/detect-provider';
const web3 = await detectEthereumProvider(); // Use Metamask-injected web3
await web3.request({ method: 'eth_requestAccounts'});
const addresses = await web3.eth.getAccounts();

I found out a solution, I do not know if is the best way to do it.
In order to interact with the blocks and sign transactions the users authenticate their MetaMask wallet through WalletConnect service.
After the user is authenticated I can use the connector to create a provider in order to use it with ethers.js lib (Using web3.js the connection with RPC failed, I decided to use ethers instead):
const walletConnectProvider = new WalletConnectProvider({
rpc: {
43114: RPC
},
chainId: 43114,
connector: this.connector,
qrcode: false
})
let wp = await walletConnectProvider.enable();
if(wp){
this.provider = new providers.Web3Provider(walletConnectProvider);
}
const signer = this.provider.getSigner();
const contract = new Contract(GAMESESSION_ADDRESS, GameSession.abi, signer);
....
It is a little tricky but WalletConnect works fine.

Related

How to connect to a deployed Polygon testnet contract?

I have a front-end / web3 application that connects to a deployed contract in the rinkeby ethereum networt.
That is possible with the Web3 library, and creating an instance of web3, like the code below:
web3.js
import Web3 from "web3";
window.ethereum.request({ method: "eth_requestAccounts" });
const web3 = new Web3(window.ethereum);
export default web3;
So, in another file, i connect to the deployed contract via contract address and ABI:
contract.js
import web3 from "./web3";
const address = "0x(...)fEb";
const abi = ["(...)"]
export default new web3.eth.Contract(abi, address);
Ok. Then i can call methods on my etherium contract.
But i would like to do it in the mumbai polygon testnet. I already have a deployed / verified contract, and then in the contract.js, I replaced the values, address and abi, but it doesn't work.
I saw something about magic sdk library, but the examples is kind different from this model, and i got kind confused.
So, someone have a hint about how to connect to a mumbai polygon testnet to front-end?
If you need to communicate with Polygon, you should use Matic.js and use this guide: https://medium.com/the-polygon-blog/beginner-friendly-tutorial-to-matic-js-58f7c24c9744
Answer to the question: To connect to Mumbai Polygon you use:
const polygonNodeOptions = {
rpcUrl: 'https://rpc-mumbai.maticvigil.com/',
chainId: 80001,
};
From https://mumbai.polygonscan.com/tx/xxxxxx
Get the contract address from your deployed contract.
which you can find in To: section
deployed contract
then
const getContract = new web3.eth.Contract(yourabi, deployedcontractAddress);
const res = await getContract.methods.your-method().call();
Hope this helps.

How can I connect to a Metamask wallet using ethers.js from a standalone node.js application?

I can't figure out how to do this. I have seen some documentation talking about ethers.Wallet.fromMnemonic, but how does ethers know my wallet is a metamask one? Or, if the wallet provider is irrelevant (is it?) how does it know its address?
Does it make any difference that I want to then interact with a liquidity pool on BSC? I mean in terms of the wallet. Can a wallet be used on multiple networks?
var web3 = require("web3")
var ethers = require("ethers")
async function MetaMask() {
privateKey = "Your wallet privateKey";
account = new ethers.Wallet(privateKey)
console.log(account)
//from mnemonic
mnemonic = "Your Mnemonic"
const wallet = new ethers.Wallet.fromMnemonic(mnemonic)
console.log(wallet)
}
MetaMaskAddress = MetaMask()

AadTokenProvider returns access token from old user

We are developing Microsoft Sharepoint "Widgets" using javascript(React) and aadTokenProviderFactory to acquire tokens.
import { WebPartContext } from "#microsoft/sp-webpart-base";
const getMSToken = async (context: WebPartContext) => {
const provider = await context.aadTokenProviderFactory.getTokenProvider();
const token = await provider.getToken('https://graph.microsoft.com');
return token;
}
This token is valid and everything works fine. But when switching users I receive a token from the old user.
How to solve this issue and acquire tokens for the user that is currently signed in?
Issue solved.
getToken method has 2nd parameter called useCachedToken: boolean.
const token = await provider.getToken('https://graph.microsoft.com', false);

How it is possible to connect with uniswap smart contract with uniswap sdk pakage without giving private key

I am developing the decentralized application of assy indexes where we swap tokens using uniswap sdk. To complete the transaction I need to connect the account with uniswap smart contract. To connect with uniswap it requires a signer and signer connect the wallet with the private key.
You can see the steps below.
provider = ethers.getDefaultProvider('rinkeby', {
infura: 'https://rinkeby.infura.io/v3/38a3d4450c784956877a1bd2fe75c406'
})
console.log('provider', provider)
const signer = new ethers.Wallet(privateKey)
console.log('signer', signer)
const account = signer.connect(provider)
console.log('account', account)
const uniswap = new ethers.Contract(
'0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',
uniswapAbi,
**account**
)
console.log('Uniswap', uniswap)
const to = this.accountAddress

unable to invoke chaincode from client : Error processing transaction. Error: PEM encoded certificate is required

i am tring to invoke chaincode command from client by i get Error processing transaction. Error: PEM encoded certificate is required this is my client code i am using to connect to the fabric network and invoke the chaincode.
i can invoke and execute chaincode commands from the peer cli but why can't i do it from a client. i think it might have to do something with tls parameter or something. can anyone tell me what i'm missing.
thanks
`
'use strict';
const fs = require('fs');
const yaml = require('js-yaml');
const { FileSystemWallet, Gateway } = require('fabric-network');
const CommercialPaper = require('../chaincode/lib/paper');
// A wallet stores a collection of identities for use
const wallet = new FileSystemWallet('../identity/user/isabella/wallet');
async function main() {
const gateway = new Gateway();
try {
const userName = 'User1#org1.bionic.com';
// Load connection profile; will be used to locate a gateway
let connectionProfile =
yaml.safeLoad(fs.readFileSync('../gateway/networkConnection.yaml', 'utf8')
);
// Set connection options; identity and wallet
let connectionOptions = {
identity: userName,
wallet: wallet,
discovery: { enabled: false, asLocalhost: true }
};
await gateway.connect(connectionProfile, connectionOptions);
const network = await gateway.getNetwork('bionicchannel');
console.error('error occured');
// Get addressability to commercial paper contract
const contract = await network.getContract('papercontract');
const issueResponse = await contract.submitTransaction(
'issue',
'BionicSoftware',
'00001',
'2020-05-31',
'2020-11-30',
'5000000');}
If you have TLS enabled, you are probably missing certificates client side (Node SDK).
I suggest to keep TLS enabled but remove mutual authentication, in this way the client does not have to autentify each time.
You must change environment variables on docker compose setting CLIENTAUTHREQUIRED to false and generating again certificates in the wallet for the client.
the problem was in the connection configuration yaml file after specifying the ca address which was not available at the time everything worked.

Categories

Resources