@polkadot/util-crypto#checkAddress TypeScript Examples

The following examples show how to use @polkadot/util-crypto#checkAddress. 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: address_swapper.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
AddressSwapper = (options: {
  address: string, currentPrefix: number,
}): string => {
  if (!options.address) throw new Error('No address provided to swap');
  if (!options.currentPrefix) return options.address;
  if (isU8a(options.address) || isHex(options.address)) {
    throw new Error('address not in SS58 format');
  }
  // check if it is valid as an address
  let decodedAddress: Uint8Array;
  try {
    decodedAddress = decodeAddress(options.address);
  } catch (e) {
    throw new Error('failed to decode address');
  }
  // check if it is valid with the current prefix & reencode if needed
  const [valid, errorMsg] = checkAddress(options.address, options.currentPrefix);
  if (!valid) {
    try {
      return encodeAddress(decodedAddress, options.currentPrefix);
    } catch (e) {
      throw new Error('failed to reencode address');
    }
  } else {
    return options.address;
  }
}
Example #2
Source File: addressSwapper.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
AddressSwapper = (options) => {
  if (!options.address) throw new Error('No address provided to swap');
  if (!options.currentPrefix) return options.address;
  if (isU8a(options.address) || isHex(options.address)) {
    throw new Error('address not in SS58 format');
  }
  // check if it is valid as an address
  let decodedAddress: Uint8Array;
  try {
    decodedAddress = decodeAddress(options.address);
  } catch (e) {
    throw new Error('failed to decode address');
  }
  // check if it is valid with the current prefix & reencode if needed
  const [valid, errorMsg] = checkAddress(options.address, options.currentPrefix);
  if (!valid) {
    try {
      return encodeAddress(decodedAddress, options.currentPrefix);
    } catch (e) {
      throw new Error('failed to reencode address');
    }
  } else {
    return options.address;
  }
}
Example #3
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 #4
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;
                },
              }),
            ]),
          ]),
        ]),
      ]
    );
  },
}