Skip to content

Commit

Permalink
Create useBlockchain.js
Browse files Browse the repository at this point in the history
  • Loading branch information
KOSASIH authored Nov 20, 2024
1 parent 00ac3cf commit 939285d
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions dapps-builder/src/hooks/useBlockchain.js
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit 939285d

Please sign in to comment.