@polkadot/types/types#Registry TypeScript Examples
The following examples show how to use
@polkadot/types/types#Registry.
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 gear-js with GNU General Public License v3.0 | 7 votes |
export function getTypesFromTypeDef(
types: Uint8Array | Hex,
registry?: Registry,
): { typesFromTypeDef: any; namespaces: Map<string, string> } {
if (!registry) {
registry = new TypeRegistry();
}
const typesFromTypeDef = {};
const namespaces = new Map<string, string>();
const portableReg = new PortableRegistry(registry, isHex(types) ? hexToU8a(types) : types, true);
portableReg.types.forEach(({ id, type: { path } }) => {
const typeDef = portableReg.getTypeDef(id);
if (path.length === 0 || (!typeDef.lookupName && !typeDef.lookupNameRoot)) {
return;
}
const name = portableReg.getName(id);
let camelCasedNamespace = toCamelCase(path.slice(0, path.length - 1));
if (camelCasedNamespace === name) {
camelCasedNamespace = path.length > 2 ? toCamelCase(path.slice(0, path.length - 2)) : undefined;
}
namespaces.set(name.replace(camelCasedNamespace, ''), name);
typesFromTypeDef[typeDef.lookupName || typeDef.lookupNameRoot] = typeDef.type.toString();
});
return { typesFromTypeDef, namespaces };
}
Example #2
Source File: helpers.ts From atlas with GNU General Public License v3.0 | 6 votes |
createNftIssuanceTransactionalStatus = (
registry: Registry,
inputMetadata: NftIssuanceInputMetadata
): InitTransactionalStatus => {
if (!inputMetadata.sale) {
return new InitTransactionalStatus(registry, { idle: null })
}
if (inputMetadata.sale.type === 'buyNow') {
return new InitTransactionalStatus(registry, { buyNow: new Balance(registry, inputMetadata.sale.buyNowPrice) })
} else if (inputMetadata.sale.type === 'open') {
return new InitTransactionalStatus(registry, {
OpenAuction: createNftOpenAuctionParams(registry, inputMetadata.sale),
})
} else if (inputMetadata.sale.type === 'english') {
return new InitTransactionalStatus(registry, {
EnglishAuction: createNftEnglishAuctionParams(registry, inputMetadata.sale),
})
} else {
throw new JoystreamLibError({ name: 'UnknownError', message: `Unknown sale type`, details: { inputMetadata } })
}
}
Example #3
Source File: FormatBalance.tsx From crust-apps with Apache License 2.0 | 6 votes |
function getFormat (registry: Registry, formatIndex = 0): [number, string] {
const decimals = registry.chainDecimals;
const tokens = registry.chainTokens;
return [
formatIndex < decimals.length
? decimals[formatIndex]
: decimals[0],
formatIndex < tokens.length
? tokens[formatIndex]
: tokens[1]
];
}
Example #4
Source File: rpcs.ts From subscan-multisig-react with Apache License 2.0 | 6 votes |
export function getAllRpc(
registry: Registry,
chain: Text,
{ specName }: RuntimeVersion
): Record<string, Record<string, DefinitionRpcExt>> {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return Object.entries(getSpecRpc(registry, chain, specName)).reduce(
(
all: Record<string, Record<string, DefinitionRpcExt>>,
[section, contents]
): Record<string, Record<string, DefinitionRpcExt>> => {
all[section] = all[section] ?? toExt(section, contents);
return all;
},
{ ...jsonrpc }
);
}
Example #5
Source File: useParamDefs.ts From crust-apps with Apache License 2.0 | 6 votes |
export default function useParamDefs (registry: Registry, type: TypeDef): ParamDef[] {
const [params, setParams] = useState<ParamDef[]>([]);
useEffect((): void => {
const typeDef = expandDef(registry, type);
if (!typeDef.sub) {
return setParams([]);
}
setParams(
(Array.isArray(typeDef.sub) ? typeDef.sub : [typeDef.sub]).map((td): ParamDef => ({
length: typeDef.length,
name: td.name,
type: td // expandDef(td)
}))
);
}, [registry, type]);
return params;
}
Example #6
Source File: useParamDefs.ts From subscan-multisig-react with Apache License 2.0 | 6 votes |
export default function useParamDefs(registry: Registry, type: TypeDef): ParamDef[] {
const [params, setParams] = useState<ParamDef[]>([]);
useEffect((): void => {
const typeDef = expandDef(registry, type);
if (!typeDef.sub) {
return setParams([]);
}
setParams(
(Array.isArray(typeDef.sub) ? typeDef.sub : [typeDef.sub]).map(
(td): ParamDef => ({
length: typeDef.length,
name: td.name,
type: td, // expandDef(td)
})
)
);
}, [registry, type]);
return params;
}
Example #7
Source File: rpcs.ts From crust-apps with Apache License 2.0 | 6 votes |
export function getAllRpc (registry: Registry, chain: Text, { specName }: RuntimeVersion): Record<string, Record<string, DefinitionRpcExt>> {
return Object
.entries(getSpecRpc(registry, chain, specName))
.reduce((all: Record<string, Record<string, DefinitionRpcExt>>, [section, contents]): Record<string, Record<string, DefinitionRpcExt>> => {
all[section] ??= toExt(section, contents);
return all;
}, { ...jsonrpc });
}
Example #8
Source File: helpers.ts From atlas with GNU General Public License v3.0 | 6 votes |
createNftIssuanceParameters = (
registry: Registry,
inputMetadata?: NftIssuanceInputMetadata
): NftIssuanceParameters | null => {
if (!inputMetadata) {
return null
}
const initTransactionalStatus = createNftIssuanceTransactionalStatus(registry, inputMetadata)
return new NftIssuanceParameters(registry, {
nft_metadata: new Bytes(registry, '0x0'),
royalty: new Option(
registry,
Royalty,
inputMetadata.royalty ? inputMetadata.royalty * NFT_PERBILL_PERCENT : undefined
),
init_transactional_status: initTransactionalStatus,
non_channel_owner: new Option(registry, RuntimeMemberId),
})
}
Example #9
Source File: FormatBalance.tsx From subscan-multisig-react with Apache License 2.0 | 6 votes |
function getFormat(registry: Registry, formatIndex = 0): [number, string] {
const decimals = registry.chainDecimals;
const tokens = registry.chainTokens;
return [
formatIndex < decimals.length ? decimals[formatIndex] : decimals[0],
formatIndex < tokens.length ? tokens[formatIndex] : tokens[1],
];
}
Example #10
Source File: helpers.ts From atlas with GNU General Public License v3.0 | 6 votes |
extractExtrinsicErrorMsg = (registry: Registry, event: Event) => {
const dispatchError = event.data[0] as DispatchError
let errorMsg = dispatchError.toString()
if (dispatchError.isModule) {
try {
const { name, docs } = registry.findMetaError(dispatchError.asModule)
errorMsg = `${name} (${docs.join(', ')})`
} catch (e) {
// This probably means we don't have this error in the metadata
// In this case - continue (we'll just display dispatchError.toString())
}
}
return errorMsg
}
Example #11
Source File: TestAccountSigningKey.ts From evm-provider.js with Apache License 2.0 | 5 votes |
readonly #registry: Registry;
Example #12
Source File: values.ts From subscan-multisig-react with Apache License 2.0 | 5 votes |
export function createValue(registry: Registry, param: { type: TypeDef }): RawParam {
const value = getInitValue(registry, param.type);
return {
isValid: !isUndefined(value),
value,
};
}
Example #13
Source File: TestAccountSigningKey.ts From evm-provider.js with Apache License 2.0 | 5 votes |
constructor(registry: Registry) {
this.#keyringPairs = [];
this.#registry = registry;
}
Example #14
Source File: SingleAccountSigner.ts From interbtc-api with Apache License 2.0 | 5 votes |
readonly #registry: Registry;
Example #15
Source File: values.ts From subscan-multisig-react with Apache License 2.0 | 5 votes |
export default function createValues(registry: Registry, params: { type: TypeDef }[]): RawParam[] {
return params.map((param) => createValue(registry, param));
}
Example #16
Source File: QrSigner.ts From crust-apps with Apache License 2.0 | 5 votes |
readonly #registry: Registry;
Example #17
Source File: LedgerSigner.ts From subscan-multisig-react with Apache License 2.0 | 5 votes |
constructor(registry: Registry, getLedger: () => Ledger, accountOffset: number, addressOffset: number) {
this.accountOffset = accountOffset;
this.addressOffset = addressOffset;
this.getLedger = getLedger;
this.registry = registry;
}
Example #18
Source File: ApiSigner.ts From crust-apps with Apache License 2.0 | 5 votes |
readonly #registry: Registry;
Example #19
Source File: AccountSigningKey.ts From bodhi.js with Apache License 2.0 | 5 votes |
readonly #registry: Registry;
Example #20
Source File: helpers.ts From atlas with GNU General Public License v3.0 | 5 votes |
sendExtrinsicAndParseEvents = (
tx: SubmittableExtrinsic<'promise'>,
accountId: string,
registry: Registry,
endpoint: string,
cb?: ExtrinsicStatusCallbackFn
) =>
new Promise<RawExtrinsicResult>((resolve, reject) => {
let unsub: () => void
let transactionInfo: string
tx.signAndSend(accountId, (result) => {
const { status, isError, events: rawEvents } = result
if (isError) {
unsub()
SentryLogger.error(`Transaction error: ${transactionInfo}`, 'JoystreamJs', 'error')
reject(new JoystreamLibError({ name: 'UnknownError', message: 'Unknown extrinsic error!' }))
return
}
if (status.isInBlock) {
const hash = status.asInBlock.toString()
transactionInfo = [
rawEvents.map((event) => event.event.method).join(', '),
`on network: ${endpoint}`,
`in block: ${hash}`,
`more details at: https://polkadot.js.org/apps/?rpc=${endpoint}#/explorer/query/${hash}`,
].join('\n')
}
if (status.isFinalized) {
unsub()
SentryLogger.message(`Successful transaction: ${transactionInfo}`, 'JoystreamJs', 'info')
try {
const events = parseExtrinsicEvents(registry, rawEvents)
resolve({ events, blockHash: status.asFinalized })
} catch (error) {
reject(error)
}
}
})
.then((unsubFn) => {
// if signAndSend succeeded, report back to the caller with the update
cb?.(ExtrinsicStatus.Signed)
unsub = unsubFn
})
.catch((e) => {
reject(e)
})
})
Example #21
Source File: values.ts From crust-apps with Apache License 2.0 | 5 votes |
export function createValue (registry: Registry, param: { type: TypeDef }): RawParam {
const value = getInitValue(registry, param.type);
return {
isValid: !isUndefined(value),
value
};
}
Example #22
Source File: SingleAccountSigner.ts From interbtc-api with Apache License 2.0 | 5 votes |
constructor (registry: Registry, keyringPair: KeyringPair, signDelay = 0) {
this.#keyringPair = keyringPair;
this.#registry = registry;
this.#signDelay = signDelay;
}
Example #23
Source File: LedgerSigner.ts From crust-apps with Apache License 2.0 | 5 votes |
constructor (registry: Registry, getLedger: () => Ledger, accountOffset: number, addressOffset: number) {
this.#accountOffset = accountOffset;
this.#addressOffset = addressOffset;
this.#getLedger = getLedger;
this.#registry = registry;
}
Example #24
Source File: AccountSigningKey.ts From bodhi.js with Apache License 2.0 | 5 votes |
constructor(registry: Registry) {
this.#keyringPairs = [];
this.#registry = registry;
}
Example #25
Source File: bountyFactory.ts From crust-apps with Apache License 2.0 | 5 votes |
readonly #registry: Registry;
Example #26
Source File: CreateType.ts From gear-js with GNU General Public License v3.0 | 5 votes |
registry: Registry;
Example #27
Source File: initValue.ts From subscan-multisig-react with Apache License 2.0 | 4 votes |
// eslint-disable-next-line complexity
export default function getInitValue(registry: Registry, def: TypeDef): unknown {
if (def.info === TypeDefInfo.Vec) {
return [getInitValue(registry, def.sub as TypeDef)];
} else if (def.info === TypeDefInfo.Tuple) {
return Array.isArray(def.sub) ? def.sub.map((item) => getInitValue(registry, item)) : [];
} else if (def.info === TypeDefInfo.Struct) {
return Array.isArray(def.sub)
? def.sub.reduce((result: Record<string, unknown>, cur): Record<string, unknown> => {
result[cur.name as string] = getInitValue(registry, cur);
return result;
}, {})
: {};
} else if (def.info === TypeDefInfo.Enum) {
return Array.isArray(def.sub) ? { [def.sub[0].name as string]: getInitValue(registry, def.sub[0]) } : {};
}
const type = [TypeDefInfo.Compact, TypeDefInfo.Option].includes(def.info) ? (def.sub as TypeDef).type : def.type;
switch (type) {
case 'AccountIndex':
case 'Balance':
case 'BalanceOf':
case 'BlockNumber':
case 'Compact':
case 'Gas':
case 'Index':
case 'Nonce':
case 'ParaId':
case 'PropIndex':
case 'ProposalIndex':
case 'ReferendumIndex':
case 'i8':
case 'i16':
case 'i32':
case 'i64':
case 'i128':
case 'u8':
case 'u16':
case 'u32':
case 'u64':
case 'u128':
case 'VoteIndex':
return BN_ZERO;
case 'bool':
return false;
case 'Bytes':
return undefined;
case 'String':
case 'Text':
return '';
case 'Moment':
return BN_ZERO;
case 'Vote':
return -1;
case 'VoteThreshold':
return 0;
case 'BlockHash':
case 'CodeHash':
case 'Hash':
case 'H256':
return registry.createType('H256');
case 'H512':
return registry.createType('H512');
case 'H160':
return registry.createType('H160');
case 'Raw':
case 'Keys':
return '';
case 'AccountId':
case 'AccountIdOf':
case 'Address':
case 'Call':
case 'CandidateReceipt':
case 'Digest':
case 'Header':
case 'KeyValue':
case 'LookupSource':
case 'MisbehaviorReport':
case 'Proposal':
case 'Signature':
case 'SessionKey':
case 'StorageKey':
case 'ValidatorId':
return undefined;
case 'Extrinsic':
return registry.createType('Raw');
case 'Null':
return null;
default: {
let error: string | null = null;
try {
const instance = registry.createType(type as 'u32');
const raw = getTypeDef(instance.toRawType());
if (isBn(instance)) {
return BN_ZERO;
} else if ([TypeDefInfo.Struct].includes(raw.info)) {
return undefined;
} else if ([TypeDefInfo.Enum, TypeDefInfo.Tuple].includes(raw.info)) {
return getInitValue(registry, raw);
}
} catch (e) {
error = (e as Error).message;
}
// we only want to want once, not spam
if (!warnList.includes(type)) {
warnList.push(type);
// eslint-disable-next-line
error && console.error(`params: initValue: ${error}`);
console.info(
`params: initValue: No default value for type ${type} from ${JSON.stringify(def)}, using defaults`
);
}
return '0x';
}
}
}
Example #28
Source File: initValue.ts From crust-apps with Apache License 2.0 | 4 votes |
export default function getInitValue (registry: Registry, def: TypeDef): unknown {
if (def.info === TypeDefInfo.Vec) {
return [getInitValue(registry, def.sub as TypeDef)];
} else if (def.info === TypeDefInfo.Tuple) {
return Array.isArray(def.sub)
? def.sub.map((def) => getInitValue(registry, def))
: [];
} else if (def.info === TypeDefInfo.Struct) {
return Array.isArray(def.sub)
? def.sub.reduce((result: Record<string, unknown>, def): Record<string, unknown> => {
result[def.name as string] = getInitValue(registry, def);
return result;
}, {})
: {};
} else if (def.info === TypeDefInfo.Enum) {
return Array.isArray(def.sub)
? { [def.sub[0].name as string]: getInitValue(registry, def.sub[0]) }
: {};
}
const type = [TypeDefInfo.Compact, TypeDefInfo.Option].includes(def.info)
? (def.sub as TypeDef).type
: def.type;
switch (type) {
case 'AccountIndex':
case 'Balance':
case 'BalanceOf':
case 'BlockNumber':
case 'Compact':
case 'Gas':
case 'Index':
case 'Nonce':
case 'ParaId':
case 'PropIndex':
case 'ProposalIndex':
case 'ReferendumIndex':
case 'i8':
case 'i16':
case 'i32':
case 'i64':
case 'i128':
case 'u8':
case 'u16':
case 'u32':
case 'u64':
case 'u128':
case 'VoteIndex':
return BN_ZERO;
case 'bool':
return false;
case 'Bytes':
return undefined;
case 'String':
case 'Text':
return '';
case 'Moment':
return BN_ZERO;
case 'Vote':
return -1;
case 'VoteThreshold':
return 0;
case 'BlockHash':
case 'CodeHash':
case 'Hash':
case 'H256':
return registry.createType('H256');
case 'H512':
return registry.createType('H512');
case 'H160':
return registry.createType('H160');
case 'Raw':
case 'Keys':
return '';
case 'AccountId':
case 'AccountIdOf':
case 'Address':
case 'Call':
case 'CandidateReceipt':
case 'Digest':
case 'Header':
case 'KeyValue':
case 'LookupSource':
case 'MisbehaviorReport':
case 'Proposal':
case 'Signature':
case 'SessionKey':
case 'StorageKey':
case 'ValidatorId':
return undefined;
case 'Extrinsic':
return registry.createType('Raw');
case 'Null':
return null;
default: {
let error: string | null = null;
try {
const instance = registry.createType(type as 'u32');
const raw = getTypeDef(instance.toRawType());
if (isBn(instance)) {
return BN_ZERO;
} else if ([TypeDefInfo.Struct].includes(raw.info)) {
return undefined;
} else if ([TypeDefInfo.Enum, TypeDefInfo.Tuple].includes(raw.info)) {
return getInitValue(registry, raw);
}
} catch (e) {
error = (e as Error).message;
}
// we only want to want once, not spam
if (!warnList.includes(type)) {
warnList.push(type);
error && console.error(`params: initValue: ${error}`);
console.info(`params: initValue: No default value for type ${type} from ${JSON.stringify(def)}, using defaults`);
}
return '0x';
}
}
}
Example #29
Source File: initValue.ts From contracts-ui with GNU General Public License v3.0 | 4 votes |
export function getInitValue(registry: Registry, keyring: Keyring, def: TypeDef): unknown {
if (def.info === TypeDefInfo.Si) {
const lookupTypeDef = registry.lookup.getTypeDef(def.lookupIndex as number);
return getInitValue(registry, keyring, lookupTypeDef);
} else if (def.info === TypeDefInfo.Option) {
return null;
} else if (def.info === TypeDefInfo.Vec) {
return [getInitValue(registry, keyring, def.sub as TypeDef)];
} else if (def.info === TypeDefInfo.Tuple) {
return Array.isArray(def.sub) ? def.sub.map(def => getInitValue(registry, keyring, def)) : [];
} else if (def.info === TypeDefInfo.Struct) {
return Array.isArray(def.sub)
? def.sub.reduce((result: Record<string, unknown>, def): Record<string, unknown> => {
result[def.name as string] = getInitValue(registry, keyring, def);
return result;
}, {})
: {};
} else if (def.info === TypeDefInfo.Enum) {
return Array.isArray(def.sub)
? { [def.sub[0].name as string]: getInitValue(registry, keyring, def.sub[0]) }
: {};
}
const type = [TypeDefInfo.Compact, TypeDefInfo.Option].includes(def.info)
? (def.sub as TypeDef).type
: def.type;
switch (type) {
case 'AccountIndex':
case 'Balance':
case 'BalanceOf':
case 'BlockNumber':
case 'Compact':
case 'Gas':
case 'Index':
case 'Nonce':
case 'ParaId':
case 'PropIndex':
case 'ProposalIndex':
case 'ReferendumIndex':
case 'i8':
case 'i16':
case 'i32':
case 'i64':
case 'i128':
case 'u8':
case 'u16':
case 'u32':
case 'u64':
case 'u128':
case 'VoteIndex':
return BN_ZERO;
case 'bool':
return false;
case 'Bytes':
return undefined;
case 'String':
case 'Text':
return '';
case 'Moment':
return BN_ZERO;
case 'Vote':
return -1;
case 'VoteThreshold':
return 0;
case 'BlockHash':
case 'CodeHash':
case 'Hash':
case 'H256':
return registry.createType('H256');
case 'H512':
return registry.createType('H512');
case 'H160':
return registry.createType('H160');
case 'Raw':
case 'Keys':
return '';
case 'AccountId':
return keyring.getAccounts()[0].address;
case 'AccountIdOf':
case 'Address':
case 'Call':
case 'CandidateReceipt':
case 'Digest':
case 'Header':
case 'KeyValue':
case 'LookupSource':
case 'MisbehaviorReport':
case 'Proposal':
case 'Signature':
case 'SessionKey':
case 'StorageKey':
case 'ValidatorId':
return undefined;
case 'Extrinsic':
return registry.createType('Raw');
case 'Null':
return null;
default: {
let error: string | null = null;
try {
const instance = registry.createType(type as 'u32');
const raw = getTypeDef(instance.toRawType());
if (isBn(instance)) {
return BN_ZERO;
} else if ([TypeDefInfo.Struct].includes(raw.info)) {
return undefined;
} else if ([TypeDefInfo.Enum, TypeDefInfo.Tuple].includes(raw.info)) {
return getInitValue(registry, keyring, raw);
}
} catch (e) {
error = (e as Error).message;
}
// we only want to warn once, not spam
if (!warnList.includes(type)) {
warnList.push(type);
error && console.error(`params: initValue: ${error}`);
console.info(
`params: initValue: No default value for type ${type} from ${JSON.stringify(
def
)}, using defaults`
);
}
return '0x';
}
}
}