@polkadot/util#isU8a TypeScript Examples
The following examples show how to use
@polkadot/util#isU8a.
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: utils.ts From bodhi.js with Apache License 2.0 | 7 votes |
export function dataToString(bytes: BytesLike): string {
if (isBuffer(bytes)) {
return u8aToHex(bufferToU8a(bytes));
}
if (isU8a(bytes)) {
return u8aToHex(bytes);
}
if (Array.isArray(bytes)) {
return u8aToHex(Buffer.from(bytes));
}
return bytes as string;
}
Example #2
Source File: utils.ts From bodhi.js with Apache License 2.0 | 7 votes |
export function toBN(bigNumberis: BigNumberish = 0): BN {
if (isU8a(bigNumberis)) {
return u8aToBn(bigNumberis);
}
if (isHex(bigNumberis)) {
return hexToBn(bigNumberis);
}
if (BigNumber.isBigNumber(bigNumberis)) {
const hex = bigNumberis.toHexString();
if (hex[0] === '-') {
return new BN('-' + hex.substring(3), 16);
}
return new BN(hex.substring(2), 16);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return new BN(bigNumberis as any);
}
Example #3
Source File: utils.ts From evm-provider.js with Apache License 2.0 | 7 votes |
export function dataToString(bytes: BytesLike): string {
if (isBuffer(bytes)) {
return u8aToHex(bufferToU8a(bytes));
}
if (isU8a(bytes)) {
return u8aToHex(bytes);
}
if (Array.isArray(bytes)) {
return u8aToHex(Buffer.from(bytes));
}
return bytes as string;
}
Example #4
Source File: utils.ts From evm-provider.js with Apache License 2.0 | 7 votes |
export function toBN(bigNumberis: BigNumberish = 0): BN {
if (isU8a(bigNumberis)) {
return u8aToBn(bigNumberis);
}
if (isHex(bigNumberis)) {
return hexToBn(bigNumberis);
}
if (BigNumber.isBigNumber(bigNumberis)) {
const hex = bigNumberis.toHexString();
if (hex[0] === '-') {
return new BN('-' + hex.substring(3), 16);
}
return new BN(hex.substring(2), 16);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return new BN(bigNumberis as any);
}
Example #5
Source File: Query.tsx From crust-apps with Apache License 2.0 | 6 votes |
function keyToName (isConst: boolean, _key: Uint8Array | QueryableStorageEntry<'promise'> | ConstValue): string {
if (isConst) {
const key = _key as ConstValue;
return `const ${key.section}.${key.method}`;
}
const key = _key as Uint8Array | QueryableStorageEntry<'promise'>;
if (isU8a(key)) {
const [, u8a] = compactStripLength(key);
// If the string starts with `:`, handle it as a pure string
return u8a[0] === 0x3a
? u8aToString(u8a)
: u8aToHex(u8a);
}
return `${key.creator.section}.${key.creator.method}`;
}
Example #6
Source File: Blocks.ts From gear-js with GNU General Public License v3.0 | 6 votes |
/**
* Get data of particular block by blockNumber or blockHash
* @param hashOrNumber
* @returns
*/
async get(hashOrNumber: `0x${string}` | Uint8Array | number): Promise<SignedBlock> {
const hash = isU8a(hashOrNumber) || isHex(hashOrNumber) ? hashOrNumber : await this.getBlockHash(+hashOrNumber);
try {
return await this.api.rpc.chain.getBlock(hash);
} catch (error) {
throw new GetBlockError(error.message, hash);
}
}
Example #7
Source File: GasSpent.ts From gear-js with GNU General Public License v3.0 | 6 votes |
private getPayload(
payload: PayloadType,
metaOrTypeOfPayload: string | Metadata,
meta_type: string,
): Hex | Uint8Array {
if (isHex(payload)) {
return payload;
} else if (isU8a(payload)) {
return u8aToHex(payload);
}
if (!metaOrTypeOfPayload) {
throw new GetGasSpentError('Impossible to create bytes from payload without specified type or meta');
}
const [type, meta] = isString(metaOrTypeOfPayload)
? [metaOrTypeOfPayload, undefined]
: [metaOrTypeOfPayload[meta_type], metaOrTypeOfPayload];
return createPayload(this.createType, type, payload, meta);
}
Example #8
Source File: addressSwapper.ts From commonwealth with GNU General Public License v3.0 | 6 votes |
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 #9
Source File: CreateType.ts From gear-js with GNU General Public License v3.0 | 6 votes |
private createRegistry(types?: any): Map<string, string> {
if (!types) {
return null;
}
if (isHex(types) || isU8a(types)) {
const { typesFromTypeDef, namespaces } = getTypesFromTypeDef(types, this.registry);
types = typesFromTypeDef;
this.namespaces = namespaces;
}
this.registerTypes(types);
return this.namespaces;
}
Example #10
Source File: blocks.errors.ts From gear-js with GNU General Public License v3.0 | 6 votes |
constructor(message: string, hash?: string | Uint8Array) {
super();
const splittedMessage = message.split(':');
if (isU8a(hash)) {
hash = u8aToString(hash);
}
const errorCode = splittedMessage.length > 0 ? parseInt(splittedMessage[0]) : NaN;
switch (errorCode) {
case -32603:
this.message = `State already discarded for block ${hash}`;
break;
default:
this.message = 'Unknow error occurred';
break;
}
}
Example #11
Source File: generate.ts From gear-js with GNU General Public License v3.0 | 6 votes |
export function createPayload(createType: CreateType, type: any, data: any, meta?: Metadata): Hex {
if (data === undefined) {
return '0x00';
}
if (isHex(data)) {
return data;
} else if (isU8a(data)) {
return u8aToHex(data);
}
let payload = data;
if (meta && type) {
const encoded = createType.create(type, data, meta);
payload = isHex(encoded) ? encoded : encoded.toHex();
} else if (type) {
try {
const encoded = createType.create(type, data);
payload = isHex(encoded) ? encoded : encoded.toHex();
} catch (error) {
console.error(error.message);
}
}
return payload;
}
Example #12
Source File: address_swapper.ts From commonwealth with GNU General Public License v3.0 | 6 votes |
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 #13
Source File: BaseBytes.tsx From subscan-multisig-react with Apache License 2.0 | 5 votes |
function BaseBytes({
asHex,
children,
className = '',
defaultValue: { value },
isDisabled,
isError,
label,
length = -1,
onChange,
onEnter,
onEscape,
size = 'full',
validate = defaultValidate,
withCopy,
withLabel,
withLength,
}: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [defaultValue] = useState(
value
? isDisabled && isU8a(value) && isAscii(value)
? u8aToString(value)
: isHex(value)
? value
: // eslint-disable-next-line no-magic-numbers
u8aToHex(value as Uint8Array, isDisabled ? 256 : -1)
: undefined
);
const [isValid, setIsValid] = useState(false);
const _onChange = useCallback(
(hex: string): void => {
let [beValid, val] = convertInput(hex);
beValid = beValid && validate(val) && (length !== -1 ? val.length === length : val.length !== 0);
if (withLength && beValid) {
val = compactAddLength(val);
}
// eslint-disable-next-line
onChange &&
onChange({
isValid: beValid,
value: asHex ? u8aToHex(val) : val,
});
setIsValid(beValid);
},
[asHex, length, onChange, validate, withLength]
);
return (
<Bare className={className}>
<Input
className={size}
defaultValue={defaultValue as string}
isAction={!!children}
isDisabled={isDisabled}
isError={isError || !isValid}
label={label}
onChange={_onChange}
onEnter={onEnter}
onEscape={onEscape}
placeholder={t<string>('0x prefixed hex, e.g. 0x1234 or ascii data')}
type="text"
withEllipsis
withLabel={withLabel}
>
{children}
{withCopy && <CopyButton value={defaultValue} />}
</Input>
</Bare>
);
}
Example #14
Source File: Keyring.ts From gear-js with GNU General Public License v3.0 | 5 votes |
static async fromSeed(seed: Uint8Array | string, name?: string): Promise<KeyringPair> {
const keyring = new Keyring({ type: 'sr25519' });
await waitReady();
const keypair = isU8a(seed) ? keyring.addFromSeed(seed, { name }) : keyring.addFromSeed(hexToU8a(seed), { name });
return keypair;
}
Example #15
Source File: BaseBytes.tsx From crust-apps with Apache License 2.0 | 5 votes |
function BaseBytes ({ asHex, children, className = '', defaultValue: { value }, isDisabled, isError, label, length = -1, onChange, onEnter, onEscape, size = 'full', validate = defaultValidate, withCopy, withLabel, withLength }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [defaultValue] = useState(
value
? isDisabled && isU8a(value) && isAscii(value)
? u8aToString(value)
: isHex(value)
? value
: u8aToHex(value as Uint8Array, isDisabled ? 256 : -1)
: undefined
);
const [isValid, setIsValid] = useState(false);
const _onChange = useCallback(
(hex: string): void => {
let [isValid, value] = convertInput(hex);
isValid = isValid && validate(value) && (
length !== -1
? value.length === length
: value.length !== 0
);
if (withLength && isValid) {
value = compactAddLength(value);
}
onChange && onChange({
isValid,
value: asHex
? u8aToHex(value)
: value
});
setIsValid(isValid);
},
[asHex, length, onChange, validate, withLength]
);
return (
<Bare className={className}>
<Input
className={size}
defaultValue={defaultValue as string}
isAction={!!children}
isDisabled={isDisabled}
isError={isError || !isValid}
label={label}
onChange={_onChange}
onEnter={onEnter}
onEscape={onEscape}
placeholder={t<string>('0x prefixed hex, e.g. 0x1234 or ascii data')}
type='text'
withEllipsis
withLabel={withLabel}
>
{children}
{withCopy && (
<CopyButton value={defaultValue} />
)}
</Input>
</Bare>
);
}
Example #16
Source File: Query.tsx From crust-apps with Apache License 2.0 | 5 votes |
function Query ({ className = '', onRemove, value }: Props): React.ReactElement<Props> | null {
const [{ Component }, callName, callType] = useMemo(
() => [
getCachedComponent(value),
keyToName(value.isConst, value.key),
value.isConst
? (value.key as unknown as ConstValue).meta.type.toString()
: isU8a(value.key)
? 'Raw'
: typeToString(value.key as QueryableStorageEntry<'promise'>)
],
[value]
);
const _onRemove = useCallback(
(): void => {
delete cache[value.id];
onRemove(value.id);
},
[onRemove, value]
);
if (!Component) {
return null;
}
return (
<div className={`storage--Query storage--actionrow ${className}`}>
<div className='storage--actionrow-value'>
<Labelled
label={
<div className='storage--actionrow-label'>
{callName}: {callType}
</div>
}
>
<Component />
</Labelled>
</div>
<div className='storage--actionrow-buttons'>
<Button
icon='times'
key='close'
onClick={_onRemove}
/>
</div>
</div>
);
}
Example #17
Source File: Query.tsx From crust-apps with Apache License 2.0 | 5 votes |
function getCachedComponent (query: QueryTypes): CacheInstance {
const { id, isConst, key, params = [] } = query as StorageModuleQuery;
if (!cache[id]) {
let renderHelper;
let type: string;
if (isConst) {
const { meta, method, section } = key as unknown as ConstValue;
renderHelper = withCallDiv(`consts.${section}.${method}`, { withIndicator: true });
type = meta.type.toString();
} else {
if (isU8a(key)) {
// subscribe to the raw key here
renderHelper = withCallDiv('rpc.state.subscribeStorage', {
paramName: 'params',
paramValid: true,
params: [[key]],
transform: ([data]: Option<Raw>[]): Option<Raw> => data,
withIndicator: true
});
} else {
const values: unknown[] = params.map(({ value }) => value);
const { creator: { meta: { type } } } = key;
const allCount = type.isPlain
? 0
: type.isMap
? 1
: 2;
renderHelper = withCallDiv('subscribe', {
paramName: 'params',
paramValid: true,
params: values.length === allCount
? [key, ...values]
: [key.entries, ...values],
withIndicator: true
});
}
type = key.creator && key.creator.meta
? typeToString(key)
: 'Raw';
}
const defaultProps = { className: 'ui--output' };
const Component = renderHelper(
// By default we render a simple div node component with the query results in it
(value: any) => <pre>{valueToText(type, value, true, true)}</pre>,
defaultProps
);
cache[query.id] = createComponent(type, Component, defaultProps, renderHelper);
}
return cache[id];
}