import { Polymesh } from '@polymathnetwork/polymesh-sdk';
import { ClaimType, ScopeType } from '@polymathnetwork/polymesh-sdk/types';
import { hexToUnpaddedString } from './formatters';

export const hasUidClaim = async ({
  sdk,
  did,
  ticker,
}: {
  sdk: Polymesh;
  did: string;
  ticker: string;
}) => {
  const tickersWithUidClaim: string[] = [];

  const uniquenessClaim: any = await sdk._polkadotApi.query.identity.claims.entries(
    {
      target: did,
      claim_type: ClaimType.InvestorUniqueness,
    }
  );

  (uniquenessClaim || []).forEach((uc: any) => {
    const {
      claim: { value: claimValues },
    } = uc[1];
    const scope = claimValues[0];
    const parsedTicker = hexToUnpaddedString(scope.value.toString());

    if (scope.type === ScopeType.Ticker) {
      tickersWithUidClaim.push(parsedTicker);
    }
  });

  return tickersWithUidClaim.includes(ticker);
};
