Hi guys. Can you help me with wagmi library? I need get price from smart contract which sale tokens and than multiple it for quantity of tokens which user wants to buy. But I can't invoke get function in moment of invoke buy function. I always get value from smart contract even if I define "enabled: false"

Mar 13, 2023, 5:38 PM
please provide code snippet and screenshots
Mar 13, 2023, 5:40 PM
const { Contract, getDefaultProvider } = require('wagmi')
const provider = getDefaultProvider('ropsten')

// Define the contract ABI and address
const contractABI = [...]
const contractAddress = '0x...'

// Create a contract instance
const contract = new Contract(contractABI, contractAddress, provider)

// Define the function to get the token price
async function getTokenPrice() {
const price = await contract.get.price({ forceRefresh: true })
return price
}

// Define the function to buy tokens
async function buyTokens(quantity) {
const price = await getTokenPrice()
const totalCost = price * quantity
// Invoke the buy function with the total cost
await contract.buy(totalCost)
}
Mar 13, 2023, 5:41 PM
this is not the best way of using wagmi
you have useContractRead for a reason
btw
get.price() I am not sure is the right way to call the getter
which is the getter name on the contract?
Mar 13, 2023, 5:44 PM
const price = useContractRead({
address: TST_MARKET,
abi: MARKET_ABI,
functionName: "price",
enabled: false,
});
console.log(parseInt(price.data._hex, 16)); I always have data here.
Mar 13, 2023, 5:48 PM
enable it
why enabled is false
and please show the contract function body
Mar 13, 2023, 5:50 PM
I need invoke it when user wants buy during execute buy function.
Mar 13, 2023, 5:50 PM
ah ok ok
Mar 13, 2023, 5:50 PM
But it's not work( I always have data
Mar 13, 2023, 5:51 PM
so how do you invoke it
means?
Mar 13, 2023, 5:51 PM
mb I really need something like this const price = await getTokenPrice()
Mar 13, 2023, 5:52 PM
you can use ethers directly too
or set enabled to use a variable
that you will change from false to true once it needs to be triggered
Mar 13, 2023, 5:55 PM
It's weird because on the docs => Set this to false to disable this query from automatically running. But it's don't work
Mar 13, 2023, 6:01 PM
Yes, you can define a function to get the token price using the useContractRead method, and then call this function to retrieve the price when needed
const readOnlyContract = contract.useContractRead()

// Define the function to get the token price
async function getTokenPrice() {
const price = await readOnlyContract.get.price()
return price
}
Mar 13, 2023, 6:26 PM
ah you mean it keep running?
Mar 13, 2023, 6:42 PM
yup
Mar 13, 2023, 6:42 PM
ahhh sorry I misunderstood
Mar 13, 2023, 6:42 PM
yes
Mar 13, 2023, 6:53 PM

© 2024 Draquery.com All rights reserved.