polkadot-js/api

View on GitHub

Showing 173 of 2,507 total issues

Function tsEnum has a Cognitive Complexity of 18 (exceeds 5 allowed). Consider refactoring.
Open

function tsEnum (registry: Registry, definitions: Record<string, ModuleTypes>, { lookupIndex, name: enumName, sub }: TypeDef, imports: TypeImports, withShortcut = false): string {
  setImports(definitions, imports, ['Enum']);

  const indent = withShortcut ? '  ' : '';
  const named = (sub as TypeDef[]).filter(({ name }) => !!name && !name.startsWith('__Unused'));
Severity: Minor
Found in packages/typegen/src/generate/tsDef.ts - About 2 hrs to fix

Cognitive Complexity

Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

A method's cognitive complexity is based on a few simple rules:

  • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
  • Code is considered more complex for each "break in the linear flow of the code"
  • Code is considered more complex when "flow breaking structures are nested"

Further reading

Function generateForMeta has 59 lines of code (exceeds 25 allowed). Consider refactoring.
Open

function generateForMeta (registry: Registry, meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean, customLookupDefinitions?: Definitions): void {
  writeFile(dest, (): string => {
    const allTypes: ExtraTypes = {
      '@polkadot/types-augment': {
        lookup: {
Severity: Major
Found in packages/typegen/src/generate/query.ts - About 2 hrs to fix

    File toV14.ts has 263 lines of code (exceeds 250 allowed). Consider refactoring.
    Open

    // Copyright 2017-2024 @polkadot/types authors & contributors
    // SPDX-License-Identifier: Apache-2.0
    
    import type { Text, Type } from '@polkadot/types-codec';
    import type { ErrorMetadataV13, EventMetadataV13, ExtrinsicMetadataV13, ExtrinsicMetadataV14, FunctionMetadataV13, MetadataV13, MetadataV14, ModuleConstantMetadataV13, ModuleMetadataV13, PalletCallMetadataV14, PalletConstantMetadataV14, PalletErrorMetadataV14, PalletEventMetadataV14, PalletMetadataV14, PalletStorageMetadataV14, StorageEntryMetadataV14, StorageEntryTypeV14, StorageHasherV13, StorageMetadataV13 } from '../../interfaces/metadata/index.js';
    Severity: Minor
    Found in packages/types/src/metadata/v13/toV14.ts - About 2 hrs to fix

      Function generateForMeta has 57 lines of code (exceeds 25 allowed). Consider refactoring.
      Open

      function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean, customLookupDefinitions?: Definitions): void {
        writeFile(dest, (): string => {
          const allTypes = {
            '@polkadot/types-augment': {
              lookup: {
      Severity: Major
      Found in packages/typegen/src/generate/consts.ts - About 2 hrs to fix

        Function generateForMeta has 57 lines of code (exceeds 25 allowed). Consider refactoring.
        Open

        function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean, customLookupDefinitions?: Definitions): void {
          writeFile(dest, (): string => {
            const allTypes = {
              '@polkadot/types-augment': {
                lookup: {
        Severity: Major
        Found in packages/typegen/src/generate/events.ts - About 2 hrs to fix

          Getters has 21 functions (exceeds 20 allowed). Consider refactoring.
          Open

          export abstract class Getters<ApiType extends ApiTypes> extends Init<ApiType> implements ApiDecoration<ApiType> {
            /**
             * @description Runtime call interfaces (currently untyped, only decorated via API options)
             */
            public get call (): QueryableCalls<ApiType> {
          Severity: Minor
          Found in packages/api/src/base/Getters.ts - About 2 hrs to fix

            Function allMethods has 54 lines of code (exceeds 25 allowed). Consider refactoring.
            Open

                  const allMethods = Object.keys(rpc).sort().map((methodName) => {
                    const def = rpc[methodName];
            
                    let args;
                    let type;
            Severity: Major
            Found in packages/typegen/src/generate/rpc.ts - About 2 hrs to fix

              Function getAuthorDetailsWithAt has 52 lines of code (exceeds 25 allowed). Consider refactoring.
              Open

              function getAuthorDetailsWithAt (header: Header, queryAt: QueryableStorage<'rxjs'>): Observable<[Header, Vec<AccountId> | null, AccountId | null]> {
                const validators = queryAt.session?.validators
                  ? queryAt.session.validators()
                  : of(null);
              
              
              Severity: Major
              Found in packages/api-derive/src/chain/util.ts - About 2 hrs to fix

                Function parseRewards has 51 lines of code (exceeds 25 allowed). Consider refactoring.
                Open

                function parseRewards (api: DeriveApi, stashId: AccountId, [erasPoints, erasPrefs, erasRewards]: ErasResult, exposures: DeriveStakerExposure[]): DeriveStakerReward[] {
                  return exposures.map(({ era, isEmpty, isValidator, nominating, validators: eraValidators }): DeriveStakerReward => {
                    const { eraPoints, validators: allValPoints } = erasPoints.find((p) => p.era.eq(era)) || { eraPoints: BN_ZERO, validators: {} as DeriveEraValPoints };
                    const { eraReward } = erasRewards.find((r) => r.era.eq(era)) || { eraReward: api.registry.createType('Balance') };
                    const { validators: allValPrefs } = erasPrefs.find((p) => p.era.eq(era)) || { validators: {} as DeriveEraValPrefs };
                Severity: Major
                Found in packages/api-derive/src/staking/stakerRewards.ts - About 2 hrs to fix

                  Function mainPromise has 49 lines of code (exceeds 25 allowed). Consider refactoring.
                  Open

                  async function mainPromise (): Promise<void> {
                    const { chain, endpoint } = yargs(hideBin(process.argv)).strict().options({
                      chain: {
                        description: 'The chain name to use for the output (defaults to "Substrate")',
                        type: 'string'
                  Severity: Minor
                  Found in packages/typegen/src/metadataMd.ts - About 1 hr to fix

                    Function addRpc has 46 lines of code (exceeds 25 allowed). Consider refactoring.
                    Open

                    function addRpc (_runtimeDesc: string, rpcMethods?: string[]): string {
                      return renderPage({
                        description: 'The following sections contain known RPC methods that may be available on specific nodes (depending on configuration and available pallets) and allow you to interact with the actual node, query, and submit.',
                        sections: Object
                          .keys(definitions)
                    Severity: Minor
                    Found in packages/typegen/src/metadataMd.ts - About 1 hr to fix

                      Function generate has 45 lines of code (exceeds 25 allowed). Consider refactoring.
                      Open

                      async function generate (metaHex: HexString, pkg: string | undefined, output: string, isStrict?: boolean): Promise<void> {
                        console.log(`Generating from metadata, ${formatNumber((metaHex.length - 2) / 2)} bytes`);
                      
                        const outputPath = assertDir(path.join(process.cwd(), output));
                        let extraTypes: Record<string, any> = {};
                      Severity: Minor
                      Found in packages/typegen/src/fromChain.ts - About 1 hr to fix

                        Function addRuntime has 44 lines of code (exceeds 25 allowed). Consider refactoring.
                        Open

                        function addRuntime (_runtimeDesc: string, apis?: ApiDef[]): string {
                          return renderPage({
                            description: 'The following section contains known runtime calls that may be available on specific runtimes (depending on configuration and available pallets). These call directly into the WASM runtime for queries and operations.',
                            sections: Object
                              .keys(definitions)
                        Severity: Minor
                        Found in packages/typegen/src/metadataMd.ts - About 1 hr to fix

                          Function filterRewards has 41 lines of code (exceeds 25 allowed). Consider refactoring.
                          Open

                          function filterRewards (stashIds: AccountId[], eras: number[], claimedRewards: [StorageKey<[u32, AccountId]>, Vec<u32>][], stakersOverview: [StorageKey<[u32, AccountId]>, Option<SpStakingPagedExposureMetadata>][]): number[][] {
                            const claimedData: Record<string, Map<number, u32[]>> = {};
                            const overviewData: Record<string, Map<number, u32>> = {};
                            const ids = stashIds.map((i) => i.toString());
                          
                          
                          Severity: Minor
                          Found in packages/api-derive/src/staking/query.ts - About 1 hr to fix

                            Function queryCurrent has 40 lines of code (exceeds 25 allowed). Consider refactoring.
                            Open

                            function queryCurrent (api: DeriveApi, accountId: AccountId | string, balanceInstances: string[] = ['balances']): Observable<ResultBalance> {
                              const [lockEmpty, lockQueries] = createCalls<Vec<PalletBalancesBalanceLock>>(
                                balanceInstances.map((m) =>
                                  (api.derive as DeriveCustomLocks)[m]?.customLocks || api.query[m as 'balances']?.locks
                                )
                            Severity: Minor
                            Found in packages/api-derive/src/balances/all.ts - About 1 hr to fix

                              Function extendPrefixedMap has a Cognitive Complexity of 13 (exceeds 5 allowed). Consider refactoring.
                              Open

                              function extendPrefixedMap (registry: Registry, itemFn: CreateItemFn, storageFn: StorageEntry): StorageEntry {
                                const { meta: { type }, method, section } = itemFn;
                              
                                storageFn.iterKey = extendHeadMeta(registry, itemFn, storageFn, (...args: unknown[]): Raw => {
                                  if (args.length && (type.isPlain || (args.length >= type.asMap.hashers.length))) {
                              Severity: Minor
                              Found in packages/types/src/metadata/decorate/storage/createFunction.ts - About 1 hr to fix

                              Cognitive Complexity

                              Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

                              A method's cognitive complexity is based on a few simple rules:

                              • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
                              • Code is considered more complex for each "break in the linear flow of the code"
                              • Code is considered more complex when "flow breaking structures are nested"

                              Further reading

                              Function _stakerRewards has 39 lines of code (exceeds 25 allowed). Consider refactoring.
                              Open

                              export function _stakerRewards (instanceId: string, api: DeriveApi): (accountIds: (Uint8Array | string)[], eras: EraIndex[], withActive?: boolean) => Observable<DeriveStakerReward[][]> {
                                return memo(instanceId, (accountIds: (Uint8Array | string)[], eras: EraIndex[], withActive = false): Observable<DeriveStakerReward[][]> =>
                                  combineLatest([
                                    api.derive.staking.queryMulti(accountIds, { withClaimedRewardsEras: true, withLedger: true }),
                                    api.derive.staking._stakerExposures(accountIds, eras, withActive),
                              Severity: Minor
                              Found in packages/api-derive/src/staking/stakerRewards.ts - About 1 hr to fix

                                Function entrySignature has 37 lines of code (exceeds 25 allowed). Consider refactoring.
                                Open

                                function entrySignature (lookup: PortableRegistry, allDefs: Record<string, ModuleTypes>, registry: Registry, section: string, storageEntry: StorageEntryMetadataLatest, imports: TypeImports): [boolean, string, string, string] {
                                  try {
                                    const outputType = lookup.getTypeDef(unwrapStorageSi(storageEntry.type));
                                
                                    if (storageEntry.type.isPlain) {
                                Severity: Minor
                                Found in packages/typegen/src/generate/query.ts - About 1 hr to fix

                                  Function generateInterfaceTypes has 37 lines of code (exceeds 25 allowed). Consider refactoring.
                                  Open

                                  export function generateInterfaceTypes (importDefinitions: Record<string, Record<string, ModuleTypes>>, dest: string): void {
                                    const registry = new TypeRegistry();
                                  
                                    writeFile(dest, (): string => {
                                      Object.entries(importDefinitions).reduce((acc, def) => Object.assign(acc, def), {});
                                  Severity: Minor
                                  Found in packages/typegen/src/generate/interfaceRegistry.ts - About 1 hr to fix

                                    Function keys has 36 lines of code (exceeds 25 allowed). Consider refactoring.
                                    Open

                                      const keys = named.map((def): string => {
                                        const { info, lookupName, name = '', sub, type } = def;
                                        const getter = stringPascalCase(name.replace(' ', '_'));
                                        const isComplex = [TypeDefInfo.Option, TypeDefInfo.Range, TypeDefInfo.RangeInclusive, TypeDefInfo.Result, TypeDefInfo.Struct, TypeDefInfo.Tuple, TypeDefInfo.Vec, TypeDefInfo.VecFixed].includes(info);
                                    
                                    
                                    Severity: Minor
                                    Found in packages/typegen/src/generate/tsDef.ts - About 1 hr to fix
                                      Severity
                                      Category
                                      Status
                                      Source
                                      Language