web3-utils#checkAddressChecksum TypeScript Examples

The following examples show how to use web3-utils#checkAddressChecksum. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: create_invite_modal.ts    From commonwealth with GNU General Public License v3.0 4 votes vote down vote up
CreateInviteModal: m.Component<
  {
    chainInfo?: ChainInfo;
  },
  {
    success: boolean;
    failure: boolean;
    disabled: boolean;
    error: string;
    invitedAddressChain: string;
    invitedEmail: string;
    searchAddressTerm: string;
    inputTimeout: any;
    hideResults: boolean;
    isTyping: boolean; // only monitors address search
    results: any[];
    closeResults: Function;
    isAddressValid: boolean;
    newAddressToValidate: boolean;
    enterAddress: Function;
    errorText: string;
  }
> = {
  oncreate: (vnode) => {
    const { chainInfo } = vnode.attrs;
  },
  view: (vnode) => {
    const { chainInfo } = vnode.attrs;
    const chainOrCommunityObj = chainInfo ? { chain: chainInfo } : null;
    if (!chainOrCommunityObj) return;

    const selectedChainId =
      vnode.state.invitedAddressChain ||
      (chainInfo ? chainInfo.id : app.config.chains.getAll()[0].id);
    const selectedChain = app.config.chains.getById(selectedChainId);

    if (vnode.state.isTyping) {
      vnode.state.isAddressValid = false;
    }

    if (
      vnode.state.searchAddressTerm?.length > 0 &&
      !vnode.state.isTyping &&
      vnode.state.newAddressToValidate
    ) {
      if (selectedChain?.base === ChainBase.Substrate) {
        try {
          decodeAddress(vnode.state.searchAddressTerm);
          vnode.state.isAddressValid = true;
        } catch (e) {
          console.log(e);
        }
      } else if (selectedChain?.base === ChainBase.Ethereum) {
        vnode.state.isAddressValid = checkAddressChecksum(
          vnode.state.searchAddressTerm
        );
      } else {
        // TODO: check Cosmos & Near?
      }
      vnode.state.newAddressToValidate = false;
    }

    const isEmailValid = validateEmail(vnode.state.invitedEmail);

    const { results, searchAddressTerm } = vnode.state;

    const LoadingPreview = m(
      List,
      {
        class: 'search-results-loading',
      },
      [m(ListItem, { label: m(Spinner, { active: true }) })]
    );

    const searchResults =
      !results || results?.length === 0
        ? app.searchAddressCache[searchAddressTerm]?.loaded
          ? m(List, [m(emptySearchPreview, { searchTerm: searchAddressTerm })])
          : LoadingPreview
        : vnode.state.isTyping
        ? LoadingPreview
        : m(List, { class: 'search-results-list' }, results);

    vnode.state.closeResults = () => {
      vnode.state.hideResults = true;
    };
    vnode.state.enterAddress = (address: string) => {
      vnode.state.searchAddressTerm = address;
      vnode.state.newAddressToValidate = true;
    };

    return m('.CreateInviteModal', [
      m('.compact-modal-title', [
        m('h3', 'Invite members'),
        m(CompactModalExitButton),
      ]),
      m('.compact-modal-body', [
        m(Form, { class: 'add-address-form' }, [
          m(FormGroup, { class: 'chain-select-group', span: 4 }, [
            m(FormLabel, { class: 'chain-select-label' }, 'Community'),
            m(SelectList, {
              closeOnSelect: true,
              items: chainInfo
                ? [{ label: chainInfo.name, value: chainInfo.id }]
                : app.config.chains
                    .getAll()
                    .map((chain) => ({
                      label: chain.name.toString(),
                      value: chain.id.toString(),
                    }))
                    .sort((a: ICommunityOption, b: ICommunityOption) => {
                      if (a.label > b.label) return 1;
                      if (a.label < b.label) return -1;
                      return 0;
                    }),
              itemRender: (item: ICommunityOption) =>
                m(ListItem, {
                  label: item.label,
                  selected:
                    vnode.state.invitedAddressChain &&
                    vnode.state.invitedAddressChain === item.value,
                }),
              itemPredicate: (query: string, item: ICommunityOption) => {
                return item.label.toLowerCase().includes(query.toLowerCase());
              },
              onSelect: (item: ICommunityOption) => {
                vnode.state.invitedAddressChain = item.value;
              },
              loading: false,
              popoverAttrs: {
                hasArrow: false,
              },
              trigger: m(Button, {
                align: 'left',
                compact: true,
                iconRight: Icons.CHEVRON_DOWN,
                label: selectedChainId,
                style: { minWidth: '100%', height: '40px' },
              }),
              emptyContent: 'No communities found',
              inputAttrs: {
                placeholder: 'Search Community...',
              },
              checkmark: false,
            }),
          ]),
          m(
            FormGroup,
            {
              class: 'address-input-group',
              span: 8,
              style: { position: 'relative' },
            },
            [
              m(FormLabel, 'Address'),
              m(Input, {
                fluid: true,
                name: 'address',
                autocomplete: 'off',
                placeholder: 'Type to search by name or address',
                value: vnode.state.searchAddressTerm,
                style: 'height: 40px',
                oninput: (e) => {
                  e.stopPropagation();
                  vnode.state.isTyping = true;
                  vnode.state.searchAddressTerm = e.target.value?.toLowerCase();
                  if (vnode.state.hideResults) {
                    vnode.state.hideResults = false;
                  }
                  if (!app.searchAddressCache[vnode.state.searchAddressTerm]) {
                    app.searchAddressCache[vnode.state.searchAddressTerm] = {
                      loaded: false,
                    };
                  }
                  if (e.target.value?.length > 3) {
                    const params: SearchParams = {
                      communityScope: null,
                      chainScope:
                        vnode.state.invitedAddressChain ||
                        (chainInfo
                          ? chainInfo.id
                          : app.config.chains.getAll()[0].id),
                    };
                    clearTimeout(vnode.state.inputTimeout);
                    vnode.state.inputTimeout = setTimeout(() => {
                      vnode.state.isTyping = false;
                      return search(
                        vnode.state.searchAddressTerm,
                        params,
                        vnode.state
                      );
                    }, 500);
                  }
                },
              }),
              searchAddressTerm?.length > 3 &&
                !vnode.state.hideResults &&
                searchResults,
            ]
          ),
          m(InviteButton, {
            selection: 'address',
            disabled: !vnode.state.isAddressValid,
            successCallback: (v: boolean) => {
              vnode.state.success = v;
              vnode.state.searchAddressTerm = '';
              m.redraw();
            },
            failureCallback: (v: boolean, err?: string) => {
              vnode.state.failure = v;
              if (err) vnode.state.error = err;
              m.redraw();
            },
            invitedAddress: vnode.state.searchAddressTerm,
            invitedAddressChain: selectedChainId,
            ...chainOrCommunityObj,
          }),
        ]),
        m(Form, { class: 'invite-email-form' }, [
          m(FormGroup, [
            m(FormLabel, 'Email'),
            m(Input, {
              fluid: true,
              name: 'emailAddress',
              autocomplete: 'off',
              placeholder: 'Enter email',
              class: !vnode.state.invitedEmail?.length
                ? ''
                : isEmailValid
                ? 'valid'
                : 'invalid',
              oninput: (e) => {
                vnode.state.invitedEmail = (e.target as any).value;
              },
            }),
          ]),
          m(InviteButton, {
            selection: 'email',
            disabled: !isEmailValid,
            successCallback: (v: boolean) => {
              vnode.state.success = v;
              vnode.state.invitedEmail = '';
              m.redraw();
            },
            failureCallback: (v: boolean, err?: string) => {
              vnode.state.failure = v;
              if (err) vnode.state.error = err;
              m.redraw();
            },
            invitedEmail: vnode.state.invitedEmail,
            ...chainOrCommunityObj,
          }),
        ]),
        m('div.divider'),
        m(CreateInviteLink, { ...chainOrCommunityObj }),
        vnode.state.success &&
          m('.success-message', ['Success! Your invite was sent']),
        vnode.state.failure &&
          m('.error-message', [vnode.state.error || 'An error occurred']),
      ]),
    ]);
  },
}
Example #2
Source File: index.ts    From commonwealth with GNU General Public License v3.0 4 votes vote down vote up
loadProfile = async (
  attrs: IProfilePageAttrs,
  state: IProfilePageState
) => {
  const chain =
    m.route.param('base') || app.customDomainId() || m.route.param('scope');
  const { address } = attrs;
  const chainInfo = app.config.chains.getById(chain);
  let valid = false;
  if (chainInfo?.base === ChainBase.Substrate) {
    const ss58Prefix = parseInt(chainInfo.ss58Prefix, 10);
    [valid] = checkAddress(address, ss58Prefix);
  } else if (chainInfo?.base === ChainBase.Ethereum) {
    valid = checkAddressChecksum(address);
  } else if (chainInfo?.base === ChainBase.CosmosSDK) {
    valid = checkCosmosAddress(address);
  } else if (chainInfo?.base === ChainBase.NEAR) {
    valid = true;
  } else if (chainInfo?.base === ChainBase.Solana) {
    valid = checkSolanaAddress(address);
  }
  if (!valid) {
    return;
  }
  state.loading = true;
  state.initialized = true;
  try {
    const response = await $.ajax({
      url: `${app.serverUrl()}/profile`,
      type: 'GET',
      data: {
        address,
        chain,
        jwt: app.user.jwt,
      },
    });

    const { result } = response;
    state.loaded = true;
    state.loading = false;
    const a = result.account;
    const profile = new Profile(a.chain, a.address);
    if (a.OffchainProfile) {
      const profileData = JSON.parse(a.OffchainProfile.data);
      // ignore off-chain name if substrate id exists
      if (a.OffchainProfile.identity) {
        profile.initializeWithChain(
          a.OffchainProfile.identity,
          profileData?.headline,
          profileData?.bio,
          profileData?.avatarUrl,
          a.OffchainProfile.judgements,
          a.last_active,
          a.is_councillor,
          a.is_validator
        );
      } else {
        profile.initialize(
          profileData?.name,
          profileData?.headline,
          profileData?.bio,
          profileData?.avatarUrl,
          a.last_active,
          a.is_councillor,
          a.is_validator
        );
      }
    } else {
      profile.initializeEmpty();
    }
    const account = {
      profile,
      chain: a.chain,
      address: a.address,
      id: a.id,
      name: a.name,
      user_id: a.user_id,
      ghost_address: a.ghost_address,
    };
    state.account = account;
    state.threads = result.threads.map((t) => modelThreadFromServer(t));
    state.comments = result.comments.map((c) => modelCommentFromServer(c));
    m.redraw();
  } catch (err) {
    // for certain chains, display addresses not in db if formatted properly
    if (chainInfo?.base === ChainBase.Substrate) {
      try {
        decodeAddress(address);
        state.account = {
          profile: null,
          chain,
          address,
          id: null,
          name: null,
          user_id: null,
        };
      } catch (e) {
        // do nothing if can't decode
      }
    } else if (chainInfo?.base === ChainBase.Ethereum) {
      if (checkAddressChecksum(address)) {
        state.account = {
          profile: null,
          chain,
          address,
          id: null,
          name: null,
          user_id: null,
        };
      }
    } else if (chainInfo?.base === ChainBase.CosmosSDK) {
      if (checkCosmosAddress(address)) {
        state.account = {
          profile: null,
          chain,
          address,
          id: null,
          name: null,
          user_id: null,
        };
      }
    } else if (chainInfo?.base === ChainBase.Solana) {
      if (checkSolanaAddress(address)) {
        state.account = {
          profile: null,
          chain,
          address,
          id: null,
          name: null,
          user_id: null,
        };
      }
    }
    state.loaded = true;
    state.loading = false;
    m.redraw();
    if (!state.account)
      throw new Error(
        err.responseJSON && err.responseJSON.error
          ? err.responseJSON.error
          : 'Failed to find profile'
      );
  }
}
Example #3
Source File: index.ts    From commonwealth with GNU General Public License v3.0 4 votes vote down vote up
ProfilePage: m.Component<IProfilePageAttrs, IProfilePageState> = {
  oninit: (vnode) => {
    vnode.state.account = null;
    vnode.state.tabSelected = 0;
    vnode.state.initialized = false;
    vnode.state.loaded = false;
    vnode.state.loading = false;
    vnode.state.threads = [];
    vnode.state.comments = [];
    vnode.state.refreshProfile = false;
    const chain =
      m.route.param('base') || app.customDomainId() || m.route.param('scope');
    const { address } = vnode.attrs;
    const chainInfo = app.config.chains.getById(chain);
    const baseSuffix = m.route.param('base');

    if (chainInfo?.base === ChainBase.Substrate) {
      const decodedAddress = decodeAddress(address);
      const ss58Prefix = parseInt(chainInfo.ss58Prefix, 10);

      const [valid] = checkAddress(address, ss58Prefix);
      if (!valid) {
        try {
          const encoded = encodeAddress(decodedAddress, ss58Prefix);
          navigateToSubpage(
            `/account/${encoded}${baseSuffix ? `?base=${baseSuffix}` : ''}`
          );
        } catch (e) {
          // do nothing if can't encode address
        }
      }
    } else if (chainInfo?.base === ChainBase.Ethereum) {
      const valid = checkAddressChecksum(address);

      if (!valid) {
        try {
          const checksumAddress = toChecksumAddress(address);
          navigateToSubpage(
            `/account/${checksumAddress}${
              baseSuffix ? `?base=${baseSuffix}` : ''
            }`
          );
        } catch (e) {
          // do nothing if can't get checksumAddress
        }
      }
    }
  },
  oncreate: async (vnode) => {},
  view: (vnode) => {
    const { setIdentity } = vnode.attrs;
    const { account, loaded, loading, refreshProfile } = vnode.state;
    if (!loading && !loaded) {
      loadProfile(vnode.attrs, vnode.state);
    }
    if (account && account.address !== vnode.attrs.address) {
      vnode.state.loaded = false;
      loadProfile(vnode.attrs, vnode.state);
    }
    if (loading) return m(PageLoading, { showNewProposalButton: true });
    if (!account && !vnode.state.initialized) {
      return m(PageNotFound, { message: 'Invalid address provided' });
    } else if (!account) {
      return m(PageLoading, { showNewProposalButton: true });
    }

    if (!vnode.state.allContentCount) {
      vnode.state.allContentCount = 10;
    }

    if (!vnode.state.proposalsContentCount) {
      vnode.state.proposalsContentCount = 10;
    }

    if (!vnode.state.commentsContentCount) {
      vnode.state.commentsContentCount = 10;
    }

    const { onOwnProfile, onLinkedProfile, displayBanner, currentAddressInfo } =
      getProfileStatus(account);

    if (refreshProfile) {
      loadProfile(vnode.attrs, vnode.state);
      vnode.state.refreshProfile = false;
      if (onOwnProfile) {
        setActiveAccount(account).then(() => {
          m.redraw();
        });
      } else {
        m.redraw();
      }
    }

    const onscroll = _.debounce(() => {
      const tab = vnode.state.tabSelected;
      if (tab === 0) {
        if (!postsRemaining(allContent.length, vnode.state.allContentCount))
          return;
      } else if (tab === 1) {
        if (
          !postsRemaining(proposals.length, vnode.state.proposalsContentCount)
        )
          return;
      } else {
        if (!postsRemaining(comments.length, vnode.state.commentsContentCount))
          return;
      }
      const scrollHeight = $(document).height();
      const scrollPos = $(window).height() + $(window).scrollTop();
      if (scrollPos > scrollHeight - 400) {
        if (tab === 0) {
          vnode.state.allContentCount += 20;
          const thisUrl = m.route.get();
          if (m.route.get() === thisUrl)
            window.location.hash = vnode.state.allContentCount.toString();
        } else if (tab === 1) {
          vnode.state.proposalsContentCount += 20;
          const thisUrl = m.route.get();
          if (m.route.get() === thisUrl)
            window.location.hash = vnode.state.proposalsContentCount.toString();
        } else {
          vnode.state.commentsContentCount += 20;
          const thisUrl = m.route.get();
          if (m.route.get() === thisUrl)
            window.location.hash = vnode.state.commentsContentCount.toString();
        }
        m.redraw();
      }
    }, 400);

    // TODO: search for cosmos proposals, if ChainBase is Cosmos
    const comments = vnode.state.comments.sort(
      (a, b) => +b.createdAt - +a.createdAt
    );
    const proposals = vnode.state.threads.sort(
      (a, b) => +b.createdAt - +a.createdAt
    );
    const allContent = []
      .concat(proposals || [])
      .concat(comments || [])
      .sort((a, b) => +b.createdAt - +a.createdAt);

    const allTabTitle =
      proposals && comments
        ? ['All ', m('.count', proposals.length + comments.length)]
        : 'All';
    const threadsTabTitle = proposals
      ? ['Threads ', m('.count', proposals.length)]
      : 'Threads';
    const commentsTabTitle = comments
      ? ['Comments ', m('.count', comments.length)]
      : 'Comments';

    return m(
      Sublayout,
      {
        showNewProposalButton: true,
        onscroll,
      },
      [
        m('.ProfilePage', [
          displayBanner &&
            m(ProfileBanner, {
              account,
              addressInfo: currentAddressInfo,
            }),
          m('.row.row-narrow.forum-row', [
            m('.col-xs-12 .col-md-8', [
              m(ProfileHeader, {
                account,
                setIdentity,
                onOwnProfile,
                onLinkedProfile,
                refreshCallback: () => {
                  vnode.state.refreshProfile = true;
                },
              }),
              m(Tabs, [
                {
                  name: allTabTitle,
                  onclick: () => {
                    vnode.state.tabSelected = 0;
                  },
                  content: m(ProfileContent, {
                    account,
                    type: UserContent.All,
                    content: allContent,
                    count: vnode.state.allContentCount,
                    // eslint-disable-next-line max-len
                    localStorageScrollYKey: `profile-${
                      vnode.attrs.address
                    }-${m.route.param('base')}-${app.activeChainId()}-scrollY`,
                  }),
                },
                {
                  name: threadsTabTitle,
                  onclick: () => {
                    vnode.state.tabSelected = 1;
                  },
                  content: m(ProfileContent, {
                    account,
                    type: UserContent.Threads,
                    content: proposals,
                    count: vnode.state.proposalsContentCount,
                    // eslint-disable-next-line max-len
                    localStorageScrollYKey: `profile-${
                      vnode.attrs.address
                    }-${m.route.param('base')}-${app.activeChainId()}-scrollY`,
                  }),
                },
                {
                  name: commentsTabTitle,
                  onclick: () => {
                    vnode.state.tabSelected = 2;
                  },
                  content: m(ProfileContent, {
                    account,
                    type: UserContent.Comments,
                    content: comments,
                    count: vnode.state.commentsContentCount,
                    // eslint-disable-next-line max-len
                    localStorageScrollYKey: `profile-${
                      vnode.attrs.address
                    }-${m.route.param('base')}-${app.activeChainId()}-scrollY`,
                  }),
                },
              ]),
            ]),
            m('.xs-display-none .col-md-4', [
              m(ProfileBio, {
                account,
                setIdentity,
                onOwnProfile,
                onLinkedProfile,
                refreshCallback: () => {
                  vnode.state.refreshProfile = true;
                },
              }),
            ]),
          ]),
        ]),
      ]
    );
  },
}