4

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

1 Answer 1

1

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.

1
  • Mikko is correct. In fact, when using Next.js, e.g., the server-side and client-side will actually render the webpage. So what happens here? Well, when the server-side renders it, you need to tell web3 to connect to a node provider (like Infura), and when it's the client side, you rely on Metamask (if the user has it), and if not: then also use the node provider. So yes: You can run your dapp with frontend without metamask. Jul 26, 2022 at 19:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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