Files
explore/ui/address/contract/methods/useCallMethodPublicClient.ts
T
tom goriunovandGitHub 434aae92bb Call contract read methods from the client (#2032)
* display methods accordion

* add method_id to methods

* query read method via public client

* query read methods without inputs at accordion section open

* add custom abi tabs

* add proxy tabs

* custom wagmi config if wc is not configured

* remove ContractAbiItemConstant component

* display tuple properties in method outputs

* display read result

* clean up

* support nested arrays in the read result

* re-write test for contract methods

* change result view for address output

* refactoring

* fix tests

* remove web3 provider fallback

* fix tab loading

* refactoring

* add implementation contract selector

* add "copy to clipboard" for address, remove top-level square brackets

* add preview mode to contract method result

* tests for read result

* fix tests

* change styles for result preview

* review fix
2024-06-24 19:56:06 +02:00

45 lines
1.3 KiB
TypeScript

import React from 'react';
import { usePublicClient } from 'wagmi';
import type { FormSubmitResult, MethodCallStrategy, SmartContractMethod } from './types';
import config from 'configs/app';
import useAccount from 'lib/web3/useAccount';
interface Params {
item: SmartContractMethod;
args: Array<unknown>;
addressHash: string;
strategy: Exclude<MethodCallStrategy, 'write'>;
}
export default function useCallMethodPublicClient(): (params: Params) => Promise<FormSubmitResult> {
const publicClient = usePublicClient({ chainId: Number(config.chain.id) });
const { address } = useAccount();
return React.useCallback(async({ args, item, addressHash, strategy }) => {
if (!('name' in item)) {
throw new Error('Unknown contract method');
}
if (!publicClient) {
throw new Error('Public Client is not defined');
}
const params = {
abi: [ item ],
functionName: item.name,
args: args,
address: addressHash as `0x${ string }`,
account: address,
};
const result = strategy === 'read' ? await publicClient.readContract(params) : await publicClient.simulateContract(params);
return {
source: 'public_client' as const,
data: strategy === 'read' ? result : result.result,
};
}, [ address, publicClient ]);
}