ValidateCode.tsx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2017-2020 @polkadot/app-contracts 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. /* eslint-disable camelcase */
  5. import { PrefabWasmModule } from '@polkadot/types/interfaces';
  6. import React, { useMemo } from 'react';
  7. import { Option } from '@polkadot/types';
  8. import { InfoForInput } from '@polkadot/react-components';
  9. import { useApi, useCall } from '@polkadot/react-hooks';
  10. import { isHex } from '@polkadot/util';
  11. import { useTranslation } from '../translate';
  12. interface Props {
  13. codeHash?: string | null;
  14. onChange: React.Dispatch<boolean>;
  15. }
  16. function ValidateCode ({ codeHash, onChange }: Props): React.ReactElement<Props> | null {
  17. const { api } = useApi();
  18. const { t } = useTranslation();
  19. const codeStorage = useCall<Option<PrefabWasmModule>>((api.query.contracts || api.query.contract).codeStorage, [codeHash]);
  20. const [isValidHex, isValid] = useMemo(
  21. (): [boolean, boolean] => {
  22. const isValidHex = !!codeHash && isHex(codeHash) && codeHash.length === 66;
  23. const isStored = !!codeStorage && codeStorage.isSome;
  24. const isValid = isValidHex && isStored;
  25. onChange(isValid);
  26. return [
  27. isValidHex,
  28. isValid
  29. ];
  30. },
  31. [codeHash, codeStorage, onChange]
  32. );
  33. if (isValid || !isValidHex) {
  34. return null;
  35. }
  36. return (
  37. <InfoForInput type='error'>
  38. {
  39. isValidHex
  40. ? t('Unable to find on-chain WASM code for the supplied codeHash')
  41. : t('The codeHash is not a valid hex hash')
  42. }
  43. </InfoForInput>
  44. );
  45. }
  46. export default React.memo(ValidateCode);