From 939285d36758146f8db9f732ef975214fed26865 Mon Sep 17 00:00:00 2001 From: KOSASIH Date: Wed, 20 Nov 2024 19:31:34 +0700 Subject: [PATCH] Create useBlockchain.js --- dapps-builder/src/hooks/useBlockchain.js | 49 ++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 dapps-builder/src/hooks/useBlockchain.js diff --git a/dapps-builder/src/hooks/useBlockchain.js b/dapps-builder/src/hooks/useBlockchain.js new file mode 100644 index 000000000..4d867dad3 --- /dev/null +++ b/dapps-builder/src/hooks/useBlockchain.js @@ -0,0 +1,49 @@ +import { useState, useEffect } from 'react'; +import BlockchainService from '../services/BlockchainService'; + +const useBlockchain = (abi, contractAddress) => { + const [accounts, setAccounts] = useState([]); + const [networkId, setNetworkId] = useState(null); + const [error, setError] = useState(null); + const [contract, setContract] = useState(null); + + useEffect(() => { + const initBlockchain = async () => { + try { + const accounts = await BlockchainService.getAccounts(); + const networkId = await BlockchainService.getNetworkId(); + setAccounts(accounts); + setNetworkId(networkId); + setContract(new BlockchainService(abi, contractAddress)); + } catch (err) { + setError(err.message); + } + }; + + initBlockchain(); + }, [abi, contractAddress]); + + const callMethod = async (method, args) => { + if (!contract) { + throw new Error('Contract not initialized.'); + } + return await contract.callMethod(method, args); + }; + + const sendMethod = async (method, args, from) => { + if (!contract) { + throw new Error('Contract not initialized.'); + } + return await contract.sendMethod(method, args, from); + }; + + return { + accounts, + networkId, + error, + callMethod, + sendMethod, + }; +}; + +export default useBlockchain;