useWeight.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. // Copyright 2017-2020 @polkadot/react-hooks authors & contributors
  2. // This software may be modified and distributed under the terms
  3. // of the Apache-2.0 license. See the LICENSE file for details.
  4. import { Call } from '@polkadot/types/interfaces';
  5. import BN from 'bn.js';
  6. import { useEffect, useState } from 'react';
  7. import { BN_ZERO } from '@polkadot/util';
  8. import useApi from './useApi';
  9. import useIsMountedRef from './useIsMountedRef';
  10. // a random address that we are using for our queries
  11. const ZERO_ACCOUNT = '5CAUdnwecHGxxyr5vABevAfZ34Fi4AaraDRMwfDQXQ52PXqg';
  12. const EMPTY_STATE: [BN, number] = [BN_ZERO, 0];
  13. // for a given call, calculate the weight
  14. export default function useWeight (call?: Call | null): [BN, number] {
  15. const { api } = useApi();
  16. const mountedRef = useIsMountedRef();
  17. const [state, setState] = useState(EMPTY_STATE);
  18. useEffect((): void => {
  19. if (call) {
  20. api.tx(call)
  21. .paymentInfo(ZERO_ACCOUNT)
  22. .then(({ weight }) => mountedRef.current && setState([weight, call.encodedLength]))
  23. .catch(console.error);
  24. } else {
  25. setState(EMPTY_STATE);
  26. }
  27. }, [api, call, mountedRef]);
  28. return state;
  29. }