@polkadot/types/types#Codec TypeScript Examples
The following examples show how to use
@polkadot/types/types#Codec.
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: State.ts From gear-js with GNU General Public License v3.0 | 6 votes |
/**
* Read state of particular program
* @param programId
* @param metaWasm - file with metadata
* @returns decoded state
*/
async read(programId: ProgramId, metaWasm: Buffer, inputValue?: any): Promise<Codec> {
const program = await this.gProg(programId);
if (!program) {
throw new ReadStateError('Program is terminated');
}
const pages = await this.gPages(programId, program);
const initialSize = program.allocations.size;
const block = await this.api.blocks.getFinalizedHead();
const blockTimestamp = await this.api.blocks.getBlockTimestamp(block.toHex());
if (!pages) {
throw new ReadStateError(`Unable to read state. Unable to recieve program pages from chain`);
}
const metadata = await getWasmMetadata(metaWasm);
if (!metadata.meta_state_output) {
throw new ReadStateError(`Unable to read state. meta_state_output type is not specified in metadata`);
}
if (metadata.meta_state_input && inputValue === undefined) {
throw new ReadStateError(`Unable to read state. inputValue not specified`);
}
const encodedInput = inputValue === undefined ? undefined : this.encodeInput(metadata, inputValue);
const state = await readState(metaWasm, initialSize, pages, encodedInput, blockTimestamp);
return this.decodeState(state, metadata);
}
Example #2
Source File: helpers.ts From guardian with Apache License 2.0 | 6 votes |
getOraclePrice =
<CurrencyId extends Codec>(api: ApiRx, period: number) =>
(tokenId: CurrencyId) => {
// acala chain
if (api.consts.cdpTreasury) {
const stableCurrencyId = api.consts.cdpTreasury.getStableCurrencyId;
const stableCurrencyIdPrice = api.consts.prices.stableCurrencyFixedPrice.toString();
if (tokenId.eq(stableCurrencyId)) return of(Big(stableCurrencyIdPrice));
} else {
const ausd = api.createType('CurrencyId', 'AUSD');
if (tokenId.eq(ausd)) return of(Big(1e18));
}
const price$ = observeRPC<Option<TimestampedValue>>(api.rpc.oracle.getValue, ['Aggregated', tokenId], period);
return price$.pipe(
filter((i) => i.isSome),
map((i) => i.unwrap()),
map((i) => Big(getValueFromTimestampValue(i).toString()))
);
}
Example #3
Source File: BalancesTask.ts From guardian with Apache License 2.0 | 6 votes |
getBalance<CurrencyId extends Codec>(api: ApiRx, account: string, currencyId: CurrencyId): Observable<Balance> {
return (api.derive as any).currencies.balance(account, currencyId).pipe(
map((result: ORMLBalance) => {
return {
account,
currencyId: currencyId.toString(),
free: result.toString()
};
})
);
}
Example #4
Source File: storage.ts From interbtc-api with Apache License 2.0 | 6 votes |
export async function setCodecStorage(
api: ApiPromise,
moduleName: string,
storageItemName: string,
value: Codec,
account: AddressOrPair,
isLittleEndian = true
): Promise<void> {
const data = value.toHex(isLittleEndian);
await setStorage(api, moduleName, storageItemName, data, account);
}
Example #5
Source File: PricesTask.ts From guardian with Apache License 2.0 | 6 votes |
async start<T extends BaseSubstrateGuardian>(guardian: T) {
const { apiRx } = await guardian.isReady();
const { key, period } = this.arguments;
if (key === 'all') {
return observeRPC<Vec<ITuple<[Codec, Option<TimestampedValue>]>>>(
apiRx.rpc.oracle.getAllValues,
['Aggregated'],
period
).pipe(
mergeMap((result): Observable<Price> => {
return from(result).pipe(
filter(([, item]) => item.isSome),
map(([key, item]) => ({
key: key.toString(),
value: getValueFromTimestampValue(item.unwrap()).toString()
}))
);
})
);
}
const keys = castArray(key).map((x) => apiRx.createType('CurrencyId', x));
return from(keys).pipe(
mergeMap((key) =>
from(getOraclePrice(apiRx, period)(key)).pipe(
map((price) => ({ key: key.toString(), value: price.toFixed(0) }))
)
),
filter((price) => price.value.length > 0)
);
}
Example #6
Source File: types.ts From commonwealth with GNU General Public License v3.0 | 6 votes |
export function formatCall(c: Call | { section: string, method: string, args: string[] }): string {
// build args string
const args: (string | Codec)[] = c.args;
const argsStr = args.map((v: Codec | string): string => {
if (!v) return '[unknown]';
const vStr = v.toString();
if (vStr.length < 16) return vStr;
return `${vStr.slice(0, 15)}…`;
}).join(', ');
// finish format
return `${c.section}.${c.method}(${argsStr})`;
}
Example #7
Source File: historic.ts From subscan-multisig-react with Apache License 2.0 | 6 votes |
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default async function getHistoric<T extends Codec, I extends any[] = any[]>(
atQuery: AtQuery<I>,
params: I,
hashes: Hash[]
): Promise<[Hash, T][]> {
return Promise.all(hashes.map((hash): Promise<T> => atQuery(hash, ...params) as Promise<T>)).then(
(results): [Hash, T][] => results.map((value, index): [Hash, T] => [hashes[index], value])
);
}
Example #8
Source File: Static.tsx From subscan-multisig-react with Apache License 2.0 | 6 votes |
// eslint-disable-next-line complexity
function StaticParam({
asHex,
children,
childrenPre,
className = '',
defaultValue,
label,
}: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const value =
defaultValue &&
(defaultValue.value as string) &&
(asHex
? (defaultValue.value as Codec).toHex()
: JSON.stringify(
(defaultValue.value as { toHuman?: () => unknown }).toHuman
? (defaultValue.value as Codec).toHuman()
: defaultValue.value,
null,
// eslint-disable-next-line no-magic-numbers
2
)
.replace(/"/g, '')
.replace(/\\/g, '')
.replace(/\],\[/g, '],\n['));
return (
<Bare className={className}>
{childrenPre}
<Static className="full" label={label} value={<pre>{value || t<string>('<empty>')}</pre>} />
{children}
</Bare>
);
}
Example #9
Source File: usePolkadotPreclaims.ts From crust-apps with Apache License 2.0 | 6 votes |
export default function usePolkadotPreclaims (): string[] {
const { allAccounts } = useAccounts();
const { api } = useApi();
const mountedRef = useIsMountedRef();
const [needsAttest, setNeedsAttest] = useState<string[]>([]);
// find all own preclaims
const preclaims = useCall<[string, EthereumAddress][]>(api.query.claims?.preclaims?.multi, [allAccounts], {
transform: (preclaims: Option<EthereumAddress>[]) =>
preclaims
.map((opt, index): [string, Option<EthereumAddress>] => [allAccounts[index], opt])
.filter(([, opt]) => opt.isSome)
.map(([address, opt]) => [address, opt.unwrap()])
});
// Filter the accounts that need attest. They are accounts that
// - already preclaimed
// - has a balance, either vested or normal
useEffect((): void => {
preclaims && api.queryMulti(
preclaims.reduce((result: [QueryableStorageEntry<'promise'>, EthereumAddress][], [, ethAddr]) =>
result.concat([
[api.query.claims.claims, ethAddr],
[api.query.claims.vesting, ethAddr]
]),
[]), (opts: Option<Codec>[]): void => {
// filter the cases where either claims or vesting has a value
mountedRef.current && setNeedsAttest(
preclaims
.filter((_, index) => opts[index * 2].isSome || opts[(index * 2) + 1].isSome)
.map(([address]) => address)
);
}
);
}, [api, allAccounts, mountedRef, preclaims]);
return needsAttest;
}
Example #10
Source File: CreateType.ts From gear-js with GNU General Public License v3.0 | 6 votes |
private createType(type: string, data: any): Codec {
if (typeIsString(type)) {
return this.registry.createType('String', data);
} else if (type.toLowerCase() === 'bytes') {
if (data instanceof Uint8Array) {
return this.registry.createType('Bytes', Array.from(data));
} else if (data instanceof Bytes) {
return data;
}
return this.registry.createType('Bytes', data);
} else {
return this.registry.createType(type, data);
}
}
Example #11
Source File: CreateType.ts From gear-js with GNU General Public License v3.0 | 6 votes |
/**
*
* @param type `TypeName` to encode or decode payload
* @param payload `Payload` that have to be encoded or decoded
* @param meta `Metadata` if type isn't standart rust Type
* @returns Codec
* @example
* ```javascript
* const encoded = CreateType.create('String', 'Hello, World');
* console.log(encoded.toHex()); // 0x48656c6c6f2c20576f726c6421
* ```
*/
static create(type: string, payload: any, meta?: Metadata): Codec {
const createType = new CreateType();
return createType.create(type, payload, meta);
}
Example #12
Source File: CreateType.ts From gear-js with GNU General Public License v3.0 | 6 votes |
/**
*
* @param type `TypeName` to encode or decode payload
* @param payload `Payload` that have to be encoded or decoded
* @param meta `Metadata` if type isn't standart rust Type
* @returns Codec
* @example
* ```javascript
* const createType = new CreateType();
* const encoded = createType.create('String', 'Hello, World');
* console.log(encoded.toHex()); // 0x48656c6c6f2c20576f726c6421
*
* const decoded = createType.create('String', '0x48656c6c6f2c20576f726c6421');
* console.log(decoded.toHuman()); // "Hello, World!"
*
* // create type with metadata
* const metadata = fs.readFileSync('path/to/file/with/metadata/*.meta.wasm);
* const encoded = create(metadata.handle_input, somePayload, metadata);
* console.log(encoded.toHex());
* ```
*/
public create(type: string, payload: any, meta?: Metadata): Codec {
type = checkTypeAndPayload(type, payload);
const namespaces = meta?.types ? this.createRegistry(meta.types) : this.createRegistry();
return this.createType(
namespaces ? setNamespaces(type, namespaces) : type,
isJSON(payload) ? toJSON(payload) : payload,
);
}
Example #13
Source File: Storage.ts From gear-js with GNU General Public License v3.0 | 6 votes |
/**
* Get list of pages for program
* @param programId
* @param pagesList - list with pages numbers
* @returns
*/
async gPages(programId: ProgramId, gProg: IActiveProgram): Promise<IGearPages> {
const keys = {};
gProg.pages_with_data.forEach((value) => {
keys[value.toNumber()] = `0x${PREFIXES.pages}${programId.slice(2)}${SEPARATOR}${this.api
.createType('Bytes', Array.from(this.api.createType('u32', value).toU8a()))
.toHex()
.slice(2)}`;
});
const pages = {};
for (let key of Object.keys(keys)) {
const storage = ((await this.api.rpc.state.getStorage(keys[key])) as Option<Codec>).unwrap().toU8a();
pages[key] = storage;
}
return pages;
}
Example #14
Source File: State.ts From gear-js with GNU General Public License v3.0 | 6 votes |
/**
* Decode state to meta_state_output type
* @param state - Uint8Array state representation
* @param meta - Metadata
* @returns decoded state
*/
decodeState(state: Uint8Array, meta: Metadata): Codec {
if (!state) {
throw new ReadStateError(`Unable to read state. meta_state function is not specified in metadata`);
}
const bytes = this.api.createType('Bytes', Array.from(state));
const decoded = this.createType.create(meta.meta_state_output, bytes, meta);
return decoded;
}
Example #15
Source File: valueToText.tsx From crust-apps with Apache License 2.0 | 6 votes |
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export default function valueToText (type: string, value: Codec | undefined | null, swallowError = true, contentShorten = true): React.ReactNode {
if (isNull(value) || isUndefined(value)) {
return div({}, '<unknown>');
}
return div(
{},
['Bytes', 'Raw', 'Option<Keys>', 'Keys'].includes(type)
? u8aToHex(value.toU8a(true), contentShorten ? 512 : -1)
// HACK Handle Keys as hex-only (this should go away once the node value is
// consistently swapped to `Bytes`)
: type === 'Vec<(ValidatorId,Keys)>'
? toString(formatKeys(value as unknown as [ValidatorId, Keys][]))
: value instanceof Raw
? value.isEmpty
? '<empty>'
: value.toString()
: (value instanceof Option) && value.isNone
? '<none>'
: toString(toHuman(value))
);
}
Example #16
Source File: Static.tsx From crust-apps with Apache License 2.0 | 6 votes |
function StaticParam ({ asHex, children, className = '', defaultValue, label }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const value = defaultValue && (defaultValue.value as string) && (
asHex
? (defaultValue.value as Codec).toHex()
: JSON.stringify(
(defaultValue.value as { toHuman?: () => unknown }).toHuman
? (defaultValue.value as Codec).toHuman()
: defaultValue.value,
null, 2
).replace(/"/g, '').replace(/\\/g, '').replace(/\],\[/g, '],\n[')
);
return (
<Bare className={className}>
<Static
className='full'
label={label}
value={<pre>{value || t<string>('<empty>')}</pre>}
/>
{children}
</Bare>
);
}
Example #17
Source File: Raw.tsx From crust-apps with Apache License 2.0 | 6 votes |
function Raw ({ className = '', defaultValue: { value }, isDisabled, isError, label, onChange, onEnter, onEscape, withLabel }: Props): React.ReactElement<Props> {
const [isValid, setIsValid] = useState(false);
const _onChange = useCallback(
(value: string): void => {
const isValid = value.length !== 0;
onChange && onChange({
isValid,
value
});
setIsValid(isValid);
},
[onChange]
);
const defaultValue = value
? ((value as { toHex?: () => unknown }).toHex ? (value as Codec).toHex() : value)
: '';
return (
<Bare className={className}>
<Input
className='full'
defaultValue={defaultValue as string}
isDisabled={isDisabled}
isError={isError || !isValid}
label={label}
onChange={_onChange}
onEnter={onEnter}
onEscape={onEscape}
placeholder='Hex data'
type='text'
withLabel={withLabel}
/>
</Bare>
);
}
Example #18
Source File: useCall.ts From crust-apps with Apache License 2.0 | 6 votes |
// subscribe, trying to play nice with the browser threads
function subscribe <T> (mountedRef: MountedRef, tracker: TrackerRef, fn: TrackFn | undefined, params: CallParams, setValue: (value: T) => void, { transform = transformIdentity, withParams, withParamsTransform }: CallOptions<T> = {}): void {
const validParams = params.filter((p) => !isUndefined(p));
unsubscribe(tracker);
setTimeout((): void => {
if (mountedRef.current) {
if (fn && (!fn.meta || !fn.meta.type?.isDoubleMap || validParams.length === 2)) {
// swap to acive mode
tracker.current.isActive = true;
tracker.current.subscriber = (fn as (...params: unknown[]) => Promise<VoidFn>)(...params, (value: Codec): void => {
// we use the isActive flag here since .subscriber may not be set on immediate callback)
if (mountedRef.current && tracker.current.isActive) {
mountedRef.current && tracker.current.isActive && setValue(
withParams
? [params, transform(value)] as any
: withParamsTransform
? transform([params, value])
: transform(value)
);
}
});
} else {
tracker.current.subscriber = null;
}
}
}, 0);
}
Example #19
Source File: valueToText.tsx From subscan-multisig-react with Apache License 2.0 | 6 votes |
// eslint-disable-next-line @typescript-eslint/no-unused-vars
// eslint-disable-next-line complexity
export default function valueToText(
type: string,
value: Codec | undefined | null,
_swallowError = true,
contentShorten = true
): React.ReactNode {
if (isNull(value) || isUndefined(value)) {
return div({}, '<unknown>');
}
return div(
{},
['Bytes', 'Raw', 'Option<Keys>', 'Keys'].includes(type) && isFunction(value.toU8a)
? // eslint-disable-next-line no-magic-numbers
u8aToHex(value.toU8a(true), contentShorten ? 512 : -1)
: // HACK Handle Keys as hex-only (this should go away once the node value is
// consistently swapped to `Bytes`)
type === 'Vec<(ValidatorId,Keys)>'
? toString(formatKeys(value as unknown as [ValidatorId, Keys][]))
: value instanceof Raw
? value.isEmpty
? '<empty>'
: value.toString()
: value instanceof Option && value.isNone
? '<none>'
: toString(toHuman(value))
);
}
Example #20
Source File: Results.tsx From crust-apps with Apache License 2.0 | 6 votes |
function Results ({ queue = [] }: Props): React.ReactElement<Props> | null {
const filtered = queue
.filter(({ error, result }) => !isUndefined(error) || !isUndefined(result))
.reverse();
if (!filtered.length) {
return null;
}
return (
<section className='rpc--Results'>
{filtered.map(({ error, id, result, rpc: { method, section } }): React.ReactNode => (
<Output
isError={!!error}
key={id}
label={`${id}: ${section}.${method}`}
value={
error
? error.message
: <pre>{JSON.stringify((result as Codec).toHuman(), null, 2).replace(/"/g, '').replace(/\\/g, '').replace(/\],\[/g, '],\n[')}</pre>
}
/>
))}
</section>
);
}
Example #21
Source File: util.ts From crust-apps with Apache License 2.0 | 6 votes |
export function sliceHex (value: Codec, max = 8): string {
const hex = value.toHex();
return hex.length > ((2 * max) + 2)
? `${hex.slice(0, max + 2)}…${hex.slice(-max)}`
: hex;
}
Example #22
Source File: Logs.tsx From crust-apps with Apache License 2.0 | 6 votes |
function formatVector (vector: Vec<Codec>): React.ReactNode {
const type = getTypeDef(vector.Type);
const values = vector.toArray().map((value): { isValid: boolean; value: Codec } => ({
isValid: true,
value
}));
const params = values.map((_, index): { name: string; type: TypeDef } => ({
name: `${index}`,
type
}));
return (
<Params
isDisabled
params={params}
values={values}
/>
);
}
Example #23
Source File: Logs.tsx From crust-apps with Apache License 2.0 | 6 votes |
function formatTuple (tuple: Tuple): React.ReactNode {
const params = tuple.Types.map((type): { type: TypeDef } => ({
type: getTypeDef(type)
}));
const values = tuple.toArray().map((value): { isValid: boolean; value: Codec } => ({
isValid: true,
value
}));
return (
<Params
isDisabled
params={params}
values={values}
/>
);
}
Example #24
Source File: Logs.tsx From crust-apps with Apache License 2.0 | 6 votes |
function formatStruct (struct: Struct): React.ReactNode {
const params = Object.entries(struct.Type).map(([name, value]): { name: string; type: TypeDef } => ({
name,
type: getTypeDef(value)
}));
const values = struct.toArray().map((value): { isValid: boolean; value: Codec } => ({
isValid: true,
value
}));
return (
<Params
isDisabled
params={params}
values={values}
/>
);
}
Example #25
Source File: Justifications.tsx From crust-apps with Apache License 2.0 | 6 votes |
function formatTuple (tuple: Tuple): React.ReactNode {
const params = tuple.Types.map((type): { type: TypeDef } => ({
type: getTypeDef(type)
}));
const values = tuple.toArray().map((value): { isValid: boolean; value: Codec } => ({
isValid: true,
value
}));
return (
<Params
isDisabled
params={params}
values={values}
/>
);
}
Example #26
Source File: SubstrateService.ts From squid with GNU General Public License v3.0 | 6 votes |
async eventsAt(
hash: Hash | Uint8Array | string
): Promise<EventRecord[] & Codec> {
debug(`Fething events. BlockHash: ${JSON.stringify(hash)}`)
return this.apiCall(
(api) => api.query.system.events.at(hash),
`get block events of block ${JSON.stringify(hash)}`
)
}
Example #27
Source File: CreateType.ts From gear-js with GNU General Public License v3.0 | 5 votes |
/**
* @deprecated use `CreateType.create()`
*/
static encode(type: any, payload: any, meta?: Metadata): Codec {
const createType = new CreateType();
return createType.create(type, payload, meta);
}
Example #28
Source File: valueToText.tsx From subscan-multisig-react with Apache License 2.0 | 5 votes |
function toHuman(value: Codec | Codec[]): unknown {
// eslint-disable-next-line @typescript-eslint/unbound-method
return isFunction((value as Codec).toHuman) ? (value as Codec).toHuman() : (value as Codec[]).map(toHuman);
}
Example #29
Source File: Raw.tsx From subscan-multisig-react with Apache License 2.0 | 5 votes |
function Raw({
className = '',
defaultValue: { value },
isDisabled,
isError,
label,
onChange,
onEnter,
onEscape,
withLabel,
}: Props): React.ReactElement<Props> {
const [isValid, setIsValid] = useState(false);
const _onChange = useCallback(
(val: string): void => {
const beValid = val.length !== 0;
// eslint-disable-next-line
onChange &&
onChange({
isValid: beValid,
value: val,
});
setIsValid(beValid);
},
[onChange]
);
const defaultValue = value ? ((value as { toHex?: () => unknown }).toHex ? (value as Codec).toHex() : value) : '';
return (
<Bare className={className}>
<Input
className="full"
defaultValue={defaultValue as string}
isDisabled={isDisabled}
isError={isError || !isValid}
label={label}
onChange={_onChange}
onEnter={onEnter}
onEscape={onEscape}
placeholder="Hex data"
type="text"
withLabel={withLabel}
/>
</Bare>
);
}