ValidateAddr.tsx 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. import { ContractInfo } from '@polkadot/types/interfaces';
  5. import React, { useEffect, useState } from 'react';
  6. import { Option } from '@polkadot/types';
  7. import { useApi, useCall } from '@polkadot/react-hooks';
  8. import { InfoForInput } from '@polkadot/react-components';
  9. import keyring from '@polkadot/ui-keyring';
  10. import { useTranslation } from '../translate';
  11. interface Props {
  12. address?: string | null;
  13. onChange: (isValid: boolean) => void;
  14. }
  15. function ValidateAddr ({ address, onChange }: Props): React.ReactElement<Props> | null {
  16. const { t } = useTranslation();
  17. const { api } = useApi();
  18. const contractInfo = useCall<Option<ContractInfo>>(api.query.contracts.contractInfoOf, [address]);
  19. const [isAddress, setIsAddress] = useState(false);
  20. const [isStored, setIsStored] = useState(false);
  21. useEffect((): void => {
  22. try {
  23. keyring.decodeAddress(address || '');
  24. setIsAddress(true);
  25. } catch (error) {
  26. setIsAddress(false);
  27. }
  28. }, [address]);
  29. useEffect((): void => {
  30. setIsStored(!!contractInfo?.isSome);
  31. }, [contractInfo?.isSome]);
  32. useEffect((): void => {
  33. onChange(isAddress && isStored);
  34. }, [isAddress, isStored, onChange]);
  35. if (isStored || !isAddress) {
  36. return null;
  37. }
  38. return (
  39. <InfoForInput type='error'>
  40. {isAddress
  41. ? t<string>('Unable to find deployed contract code at the specified address')
  42. : t<string>('The value is not in a valid address format')
  43. }
  44. </InfoForInput>
  45. );
  46. }
  47. export default React.memo(ValidateAddr);