@polkadot/util#u8aConcat TypeScript Examples

The following examples show how to use @polkadot/util#u8aConcat. 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: util.ts    From crust-apps with Apache License 2.0 7 votes vote down vote up
// recover an address from a signature JSON (as supplied by e.g. MyCrypto)
export function recoverFromJSON (signatureJson: string | null): RecoveredSignature {
  try {
    const { msg, sig } = JSON.parse(signatureJson || '{}') as Record<string, string>;

    if (!msg || !sig) {
      throw new Error('Invalid signature object');
    }

    const parts = sigToParts(sig);

    return {
      error: null,
      ethereumAddress: registry.createType('EthereumAddress', recoverAddress(hexHasPrefix(msg) ? hexToString(msg) : msg, parts)),
      signature: registry.createType('EcdsaSignature', u8aConcat(parts.signature, new Uint8Array([parts.recovery])))
    };
  } catch (error) {
    console.error(error);

    return {
      error: error as Error,
      ethereumAddress: null,
      signature: null
    };
  }
}
Example #2
Source File: index.test.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
describe('bodhi', () => {
  it('should export the Provider', () => {
    expect(Provider).to.not.be.undefined;
  });

  it('default evm address', () => {
    const accountid = decodeAddress('5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY');

    const encode = u8aConcat('evm:', accountid);

    expect(u8aToHex(blake2AsU8a(encode, 256).slice(0, 20))).to.equal('0xf4ca11ca834c9e2fb49f059ab71fb9c72dad05f9');
  });
});
Example #3
Source File: address.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
computeDefaultEvmAddress = (substrateAddress: HexString | string | Uint8Array): string => {
  if (!isSubstrateAddress) {
    return logger.throwArgumentError('invalid substrate address', 'address', substrateAddress);
  }

  const publicKey = decodeAddress(substrateAddress);

  const isStartWithEvm = u8aEq('evm:', publicKey.slice(0, 4));

  if (isStartWithEvm) {
    return getAddress(u8aToHex(publicKey.slice(4, 24)));
  }

  return getAddress(u8aToHex(blake2AsU8a(u8aConcat('evm:', publicKey), 256).slice(0, 20)));
}
Example #4
Source File: address.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
computeDefaultSubstrateAddress = (evmAddress: string): string => {
  if (!isEvmAddress(evmAddress)) {
    return logger.throwArgumentError('invalid evm address', 'address', evmAddress);
  }

  const address = encodeAddress(u8aFixLength(u8aConcat('evm:', hexToU8a(evmAddress)), 256, true));

  return address.toString();
}
Example #5
Source File: Signer.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
/**
   *
   * @returns The default EVM address generated for the signer's substrate address
   */
  computeDefaultEvmAddress(): string {
    const address = this._substrateAddress;
    const publicKey = decodeAddress(address);

    const isStartWithEvm = u8aEq('evm:', publicKey.slice(0, 4));

    if (isStartWithEvm) {
      return getAddress(u8aToHex(publicKey.slice(4, 24)));
    }

    return getAddress(u8aToHex(blake2AsU8a(u8aConcat('evm:', publicKey), 256).slice(0, 20)));
  }
Example #6
Source File: useOwnStashInfos.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
function getStakerState (stashId: string, allAccounts: string[], validators: string[], [isOwnStash, { controllerId: _controllerId, exposure, nextSessionIds, nominators, rewardDestination, sessionIds, stakingLedger, validatorPrefs }, validateInfo]: [boolean, DeriveStakingAccount, ValidatorInfo]): StakerState {
  const isStashNominating = !!(nominators?.length);
  const isStashValidating = validators.indexOf(stashId) !== -1;
  const nextConcat = u8aConcat(...nextSessionIds.map((id): Uint8Array => id.toU8a()));
  const currConcat = u8aConcat(...sessionIds.map((id): Uint8Array => id.toU8a()));
  const controllerId = toIdString(_controllerId);

  return {
    controllerId,
    destination: rewardDestination,
    exposure,
    hexSessionIdNext: u8aToHex(nextConcat, 48),
    hexSessionIdQueue: u8aToHex(currConcat.length ? currConcat : nextConcat, 48),
    isLoading: false,
    isOwnController: allAccounts.includes(controllerId || ''),
    isOwnStash,
    isStashNominating,
    isStashValidating,
    // we assume that all ids are non-null
    nominating: nominators?.map(toIdString) as string[],
    sessionIds: (
      nextSessionIds.length
        ? nextSessionIds
        : sessionIds
    ).map(toIdString) as string[],
    stakingLedger,
    stashId,
    validatorPrefs
  };
}
Example #7
Source File: index.spec.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
describe('evm-provider', () => {
  it('should export the Provider', () => {
    expect(Provider).toBeDefined();
  });

  it('default evm address', () => {
    const accountid = decodeAddress(
      '5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY'
    );

    const encode = u8aConcat('evm:', accountid);

    expect(u8aToHex(blake2AsU8a(encode, 256).slice(0, 20))).toEqual(
      '0xf4ca11ca834c9e2fb49f059ab71fb9c72dad05f9'
    );
  });
});
Example #8
Source File: Signer.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
/**
   *
   * @returns The default EVM address generated for the signer's substrate address
   */
  computeDefaultEvmAddress(): string {
    const address = this._substrateAddress;
    const publicKey = decodeAddress(address);

    const isStartWithEvm = u8aEq('evm:', publicKey.slice(0, 4));

    if (isStartWithEvm) {
      return getAddress(u8aToHex(publicKey.slice(4, 24)));
    }

    return getAddress(
      u8aToHex(blake2AsU8a(u8aConcat('evm:', publicKey), 256).slice(0, 20))
    );
  }
Example #9
Source File: QrSigner.ts    From sdk with Apache License 2.0 6 votes vote down vote up
async function _integrateMultiPartData() {
  const { multipartData, totalFrameCount } = signer;

  // concatenate all the parts into one binary blob
  let concatMultipartData = multipartData.reduce((acc, part) => {
    if (part === null) throw new Error("part data is not completed");
    const c = new Uint8Array(acc.length + part.length);
    c.set(acc);
    c.set(part, acc.length);
    return c;
  }, new Uint8Array(0));

  // unshift the frame info
  const frameInfo = u8aConcat(MULTIPART, _encodeNumber(totalFrameCount), _encodeNumber(0));
  concatMultipartData = u8aConcat(frameInfo, concatMultipartData);

  signer.multipartComplete = true;
  // handle the binary blob as a single UOS payload
  await _setParsedData(concatMultipartData, true);
}
Example #10
Source File: QrSigner.ts    From sdk with Apache License 2.0 6 votes vote down vote up
function _createFrames(input: Uint8Array) {
  const frames = [];
  let idx = 0;
  while (idx < input.length) {
    frames.push(input.subarray(idx, idx + FRAME_SIZE));
    idx += FRAME_SIZE;
  }
  return frames.map((frame, index) => u8aConcat(MULTIPART, _encodeNumber(frames.length), _encodeNumber(index), frame));
}
Example #11
Source File: KeyValue.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function KeyValue({
  className = '',
  isDisabled,
  label,
  onChange,
  onEnter,
  withLabel,
}: Props): React.ReactElement<Props> {
  const [, setIsValid] = useState(false);
  const [key, setKey] = useState<StateParam>({ isValid: false, u8a: new Uint8Array([]) });
  const [value, setValue] = useState<StateParam>({ isValid: false, u8a: new Uint8Array([]) });

  useEffect((): void => {
    const isValid = key.isValid && value.isValid;

    // eslint-disable-next-line
    onChange &&
      onChange({
        isValid,
        value: u8aConcat(key.u8a, value.u8a),
      });
    setIsValid(isValid);
  }, [key, onChange, value]);

  const _onChangeKey = useCallback((k: string): void => setKey(createParam(k)), []);
  const _onChangeValue = useCallback((val: string): void => setValue(createParam(val)), []);

  return (
    <Bare className={className}>
      <Input
        className="medium"
        isDisabled={isDisabled}
        isError={!key.isValid}
        label={label}
        onChange={_onChangeKey}
        placeholder="0x..."
        type="text"
        withLabel={withLabel}
      />
      <Input
        className="medium"
        isDisabled={isDisabled}
        isError={!value.isValid}
        onChange={_onChangeValue}
        onEnter={onEnter}
        placeholder="0x..."
        type="text"
        withLabel={withLabel}
      />
    </Bare>
  );
}
Example #12
Source File: useOwnStashInfos.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function getStakerState(
  stashId: string,
  allAccounts: string[],
  [
    isOwnStash,
    {
      controllerId: _controllerId,
      exposure,
      nextSessionIds,
      nominators,
      rewardDestination,
      sessionIds,
      stakingLedger,
      validatorPrefs,
    },
    validateInfo,
  ]: [boolean, DeriveStakingAccount, ValidatorInfo]
): StakerState {
  const isStashNominating = !!nominators?.length;
  const isStashValidating = !(Array.isArray(validateInfo) ? validateInfo[1].isEmpty : validateInfo.isEmpty);
  const nextConcat = u8aConcat(...nextSessionIds.map((id): Uint8Array => id.toU8a()));
  const currConcat = u8aConcat(...sessionIds.map((id): Uint8Array => id.toU8a()));
  const controllerId = toIdString(_controllerId);

  return {
    controllerId,
    destination: rewardDestination,
    exposure,
    hexSessionIdNext: u8aToHex(nextConcat, 48),
    hexSessionIdQueue: u8aToHex(currConcat.length ? currConcat : nextConcat, 48),
    isLoading: false,
    isOwnController: allAccounts.includes(controllerId || ''),
    isOwnStash,
    isStashNominating,
    isStashValidating,
    // we assume that all ids are non-null
    nominating: nominators?.map(toIdString) as string[],
    sessionIds: (nextSessionIds.length ? nextSessionIds : sessionIds).map(toIdString) as string[],
    stakingLedger,
    stashId,
    validatorPrefs,
  };
}
Example #13
Source File: Provider.ts    From evm-provider.js with Apache License 2.0 5 votes vote down vote up
async _toAddress(addressOrName: string | Promise<string>): Promise<string> {
    const resolved = await addressOrName;
    const address = encodeAddress(
      u8aFixLength(u8aConcat('evm:', hexToU8a(resolved)), 256, true)
    );
    return address.toString();
  }
Example #14
Source File: QrSigner.ts    From sdk with Apache License 2.0 5 votes vote down vote up
function _createSignPayload(address: string, cmd: number, payload: Uint8Array | any, genesisHash: Uint8Array | any) {
  return u8aConcat(SUBSTRATE_ID, CRYPTO_SR25519, new Uint8Array([cmd]), decodeAddress(address), u8aToU8a(payload), u8aToU8a(genesisHash));
}
Example #15
Source File: index.ts    From sdk with Apache License 2.0 5 votes vote down vote up
function _extractStakerState(
  accountId,
  stashId,
  allStashes,
  [
    isOwnStash,
    {
      controllerId: _controllerId,
      exposure,
      nextSessionIds,
      nominators,
      rewardDestination,
      sessionIds,
      stakingLedger,
      validatorPrefs,
    },
    validateInfo,
  ]
) {
  const isStashNominating = !!nominators?.length;
  const isStashValidating =
    !(Array.isArray(validateInfo)
      ? validateInfo[1].isEmpty
      : validateInfo.isEmpty) || !!allStashes?.includes(stashId);
  const nextConcat = u8aConcat(...nextSessionIds.map((id: any) => id.toU8a()));
  const currConcat = u8aConcat(...sessionIds.map((id: any) => id.toU8a()));
  const controllerId = _toIdString(_controllerId);

  return {
    controllerId,
    destination: rewardDestination?.toString().toLowerCase(),
    destinationId: rewardDestination?.toNumber() || 0,
    exposure,
    hexSessionIdNext: u8aToHex(nextConcat, 48),
    hexSessionIdQueue: u8aToHex(
      currConcat.length ? currConcat : nextConcat,
      48
    ),
    isOwnController: accountId == controllerId,
    isOwnStash,
    isStashNominating,
    isStashValidating,
    // we assume that all ids are non-null
    nominating: nominators?.map(_toIdString),
    sessionIds: (nextSessionIds.length ? nextSessionIds : sessionIds).map(
      _toIdString
    ),
    stakingLedger,
    stashId,
    validatorPrefs,
  };
}
Example #16
Source File: customHashers.ts    From parity-bridges-ui with GNU General Public License v3.0 5 votes vote down vote up
function blake2Keccak256Hasher(data: Uint8Array) {
  return u8aConcat(blake2AsU8a(data), keccakAsU8a(data));
}
Example #17
Source File: KeyValue.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function KeyValue ({ className = '', isDisabled, label, onChange, onEnter, withLabel }: Props): React.ReactElement<Props> {
  const [, setIsValid] = useState(false);
  const [key, setKey] = useState<StateParam>({ isValid: false, u8a: new Uint8Array([]) });
  const [value, setValue] = useState<StateParam>({ isValid: false, u8a: new Uint8Array([]) });

  useEffect((): void => {
    const isValid = key.isValid && value.isValid;

    onChange && onChange({
      isValid,
      value: u8aConcat(
        key.u8a,
        value.u8a
      )
    });
    setIsValid(isValid);
  }, [key, onChange, value]);

  const _onChangeKey = useCallback(
    (key: string): void => setKey(createParam(key)),
    []
  );
  const _onChangeValue = useCallback(
    (value: string): void => setValue(createParam(value)),
    []
  );

  return (
    <Bare className={className}>
      <Input
        className='medium'
        isDisabled={isDisabled}
        isError={!key.isValid}
        label={label}
        onChange={_onChangeKey}
        placeholder='0x...'
        type='text'
        withLabel={withLabel}
      />
      <Input
        className='medium'
        isDisabled={isDisabled}
        isError={!value.isValid}
        onChange={_onChangeValue}
        onEnter={onEnter}
        placeholder='0x...'
        type='text'
        withLabel={withLabel}
      />
    </Bare>
  );
}
Example #18
Source File: PreClaimCRU18.tsx    From crust-apps with Apache License 2.0 4 votes vote down vote up
function PreClaimCRU18 ({ className = '', isHighlight, isPadded = true, value, withShrink = false }: Props): React.ReactElement<Props> | null {
  const { api } = useApi();
  const [preClaims, setPreClaims] = useState<PreClaimsMapping[]>([]);
  const [ownPreClaims, setOwnPreClaims ] = useState<PreClaimsMapping[]>([]);

  const [preValue, setPreValue] = useState<BN>(BN_ZERO);

  const getAllPreClaims = () => {
    let unsub: (() => void) | undefined;
    const fns: any[] = [
      [api.query.claims.cru18Claims.entries]
    ];
    const tmp: PreClaimsMapping[] = [];

    api.combineLatest<any[]>(fns, ([preClaims]): void => {
      if (Array.isArray(preClaims)) {
        preClaims.forEach(([{ args: [ethereumAddress, accountId] }, value]) => {
          tmp.push({
            account: accountId,
            ethAddress: u8aToHex(u8aConcat(ethereumAddress), 48).toString(),
            value: new BN(Number(value).toString())
          })
        });
        setPreClaims(tmp);
      }
    }).then((_unsub): void => {
      unsub = _unsub;
    }).catch(console.error);
    return (): void => {
      unsub && unsub();
    };
  };

  useEffect(() => {
    getAllPreClaims();
  }, []);

  useEffect(() => {
    if (preClaims.length) {
      const claimTmp = lodash.filter(preClaims, e => e.account.toString() == value?.toString());

      setOwnPreClaims(claimTmp);
      setPreValue(lodash.reduce(claimTmp, (sum, n) => {
        return sum.add(n.value)
      }, BN_ZERO))
    }
  }, [preClaims])

  if (preValue.isZero()) {
    return null;
  }

  return (
    <div className={`ui--AddressMini${isHighlight ? ' isHighlight' : ''}${isPadded ? ' padded' : ''}${withShrink ? ' withShrink' : ''} ${className}`}>
      <div className='ui--AddressMini-balances'>
        <React.Fragment key={3}>
          <FormatCru18
            className='result'
            label={
              <Icon
                icon='info-circle'
                tooltip={`${value}-locks-trigger`}
              />
            }
            value={new BN(Number(preValue).toString())}
          >
            <Tooltip
              text={ownPreClaims.map(({ ethAddress, value }, index): React.ReactNode => (
                <div key={index}>
                  {formatBalance(value, { forceUnit: '-', withUnit: 'CRU18' })
                  }<div className='faded'>{ethAddress.toString()}</div>
                </div>
              ))}
              trigger={`${value}-locks-trigger`}
            />
          </FormatCru18>
        </React.Fragment>
      </div>
    </div>
  );
}