1

I've a web application where I have some structure with ids and a function to get prices by an id from an smart contract, and I've payable functions.

I'm not able to show prices for each item if I don't click "connect to wallet" first. So, I'd like to know a way to use the deployed contract and get the prices without clicking "connect to wallet"

I have a button that says "connect to wallet" and this will trigger the web3 function in order to connect with metamask.

connect to wallet fn:

   let web3 = window.web3;
    console.log(web3)
    if (!web3) rej('MetaMask not available');
    web3 = new Web3(web3.currentProvider);
    res(web3);

I'm using truffle:

import Contract from '../../build/contracts/Contract.json';
import contract from 'truffle-contract';
export default async function(provider: any): Promise<any> {
  const _contract = contract(Contract);
  _contract.setProvider(provider);
  const instance = await _contract.deployed();
  return instance;
}

executing the contract and saving it globally

const handleDeployedSmartContract = async(): Promise<void> => {
    const m = await contractProvider(window.web3.currentProvider);
    window.contracts = {
      ...window.contracts,
      m
    };
    dispatch({ type: types.ui.contractLoaded, payload: true });
    dispatch({ type: types.ui.handleWalletModal, payload: false});
  }

and If I execute handleDeployedSmartContract without the web3 connection, I'm not able to get the contract :/ I want to show the prices without even clicking "connect to a wallet" and the prices comes from the smart contract function

0

You can create a Web3.js connection directly from your Dapp. You do not need to use one provided by wallet. Simply point Web3.js to any of Ethereum node providers. The connection is HTTPS or Websocket WSS. You can also run your own node for your Dapp users.

Note that in both cases you will bear the cost of paying for the node maintenance, because you are not piggybacking the connection MetaMask team gives for its wallet users for free.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.