svelte-web3 icon indicating copy to clipboard operation
svelte-web3 copied to clipboard

How to use makeContractStore?

Open kamesen99 opened this issue 3 years ago • 4 comments

Hello, after I create a store using makeContractStore(ABI, address) I'm unable to call this Contract object from another component in my app. Could you provide an example of how to call and use a contract method from this store? Thank you.

kamesen99 avatar Jan 04 '22 21:01 kamesen99

Edit: I misunderstood the question. I don't think you're able to call the store from other contracts as far as I'm aware?

The store returns a web3 contract https://web3js.readthedocs.io/en/v1.2.11/web3-eth-contract.html

Try including the following block:

onMount(async () => {
     const contract = makeContractStore(.....);
     const symbol = await $contract.methods.symbol().call();
     console.log(symbol);
})

pythonicode avatar Jan 05 '22 04:01 pythonicode

@PythoniCode is correct, if you create a contract store locally, you can only use it inside that file. But there are ways to go around that and use is somewhere else.

  1. saving the store inside a context `setContext(,<myContractStore>)
  2. creating a store in a separate file and exporting it. This one is probably a better pattern than setContext. I could try to document that better in the README and give an example. Will do that a bit later...

clbrge avatar Jan 05 '22 05:01 clbrge

Thank you. Yes the goal was to re-use the contract object elsewhere. I did try to create a store with only the contract within but ran into some issues, specifically setting the store. Thank you for clarifying the intent behind this function

kamesen99 avatar Jan 05 '22 06:01 kamesen99

In the meantime this part is improving, here is a small example how to create your own contract store form a separate file that can be imported everywhere: Let's define a file contract-stores.js:

import ERC20 from '@openzeppelin/contracts/build/contracts/IERC20.json'

import { derived } from 'svelte/store'
import { web3, chainId } from 'svelte-web3'

const DAI = '0x6b175474e89094c44da98b954eedeac495271d0f'

const myContractStore = derived([web3, chainId], ([$web3, $chainId]) => {
  if ($chainId && $web3.eth) {
    // Do whatever nececessay to get address from chainId
    return new $web3.eth.Contract(ERC20.abi, DAI, {})
  }
  return null
})

export default myContractStore

And in svelte file:

import DAI from './contract-stores.js'

$: DAISupply = $DAI ? $DAI.methods.totalSupply().call() : ''

</script>

{#await DAISupply}
   pending contract definition
{:then value}
  {value}
{/await}

clbrge avatar Jan 10 '22 12:01 clbrge