Skip to content

refactor: migrates another part of console-api to strict types#1488

Merged
stalniy merged 1 commit intomainfrom
refactor/console-api-strict-5
Jun 17, 2025
Merged

refactor: migrates another part of console-api to strict types#1488
stalniy merged 1 commit intomainfrom
refactor/console-api-strict-5

Conversation

@stalniy
Copy link
Contributor

@stalniy stalniy commented Jun 16, 2025

Why

to improve project stability

What

migrates another part of console-api to strict types

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling and type safety for deployment and provider responses, including fixing a typo in deployment events.
    • Ensured required fields are always present in API responses, such as transactionHash and provider address.
    • Added explicit handling for missing or undefined values in several services and tests.
  • Refactor

    • Standardized the use of non-null assertions for wallet addresses and improved type annotations across multiple services.
    • Streamlined internal logic for caching and conditional operations to reduce redundancy and prevent potential runtime errors.
  • Tests

    • Enhanced test reliability and type consistency in deployment-related test suites.
  • Chores

    • Expanded TypeScript strict checks to cover additional source directories for improved code quality.

@stalniy stalniy requested a review from a team as a code owner June 16, 2025 02:01
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 16, 2025

Walkthrough

This update introduces explicit TypeScript typing, non-null assertions, and schema refinements across deployment, billing, and provider modules. It enhances type safety, clarifies nullable fields, and standardizes object properties. Internal logic remains largely unchanged, with improvements focused on code correctness, error handling, and test consistency.

Changes

File(s) Change Summary
managed-signer.service.ts, provider.service.ts Added explicit Promise return types to methods; imported necessary types for type assertions.
deployment.controller.ts, deployment-writer.service.ts, lease.service.ts, draining-deployment.service.ts, stale-managed-deployments-cleaner.service.ts Added non-null assertions (!) to wallet address usage; improved error handling in controller.
deployment.schema.ts Refined schema: made certain fields optional or nullable, removed unused fields, and fixed a typo in event property names.
top-up-summarizer.ts Made several summary and class properties optional instead of required, updating type/interface declarations.
deployment-setting.repository.ts Added type cast to yielded items and noted a potential join bug in a comment.
cached-balance.service.ts Refactored cache retrieval logic to avoid redundant lookups and overwrites.
deployment-reader.service.ts Ensured provider objects always include explicit address fields and are not incomplete; improved conditional assignment.
draining-deployment.service.spec.ts Adjusted test to use undefined instead of null for missing user wallet scenario.
top-up-custodial-balance.service.ts Added type check before subtracting fees from balance to prevent runtime errors.
top-up-managed-deployments.service.ts, top-up-managed-deployments.service.spec.ts Added explicit error typing in catch blocks; clarified Boolean filtering; improved test type casting for billing config mock.
gpu.ts Changed variable initializations from null to undefined and made minor SQL formatting adjustments.
deployments.spec.ts Improved type safety in tests; ensured transaction responses consistently include both hash and transactionHash.
tsconfig.strict.json Included additional directories for strict TypeScript checks.

Sequence Diagram(s)

sequenceDiagram
    participant Controller
    participant Service
    participant Repository
    participant Cache

    Controller->>Service: executeDecodedTxByUserId(userId, messages)
    Service->>Repository: Execute transaction
    Repository-->>Service: Transaction result (code, hash, rawLog)
    Service-->>Controller: { code, hash, transactionHash, rawLog }

    Controller->>Service: get(address)
    Service->>Cache: Check for cached balance
    alt Cache miss
        Service->>Repository: Fetch fresh limits
        Service->>Cache: Store new CachedBalance
    end
    Cache-->>Service: Return CachedBalance
    Service-->>Controller: CachedBalance
Loading

Suggested reviewers

  • baktun14

Poem

In the warren, code grows neat and strong,
With types and checks, we all belong.
Non-null asserts make bunnies cheer,
Schemas trimmed, intentions clear.
Tests now hop with safer feet—
This patch makes our burrow sweet!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-17T07_30_23_927Z-debug-0.log


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a97b6bc and ca49adf.

📒 Files selected for processing (19)
  • apps/api/src/billing/services/managed-signer/managed-signer.service.ts (4 hunks)
  • apps/api/src/deployment/controllers/deployment/deployment.controller.ts (2 hunks)
  • apps/api/src/deployment/http-schemas/deployment.schema.ts (3 hunks)
  • apps/api/src/deployment/lib/top-up-summarizer/top-up-summarizer.ts (2 hunks)
  • apps/api/src/deployment/repositories/deployment-setting/deployment-setting.repository.ts (1 hunks)
  • apps/api/src/deployment/services/cached-balance/cached-balance.service.ts (1 hunks)
  • apps/api/src/deployment/services/deployment-reader/deployment-reader.service.ts (2 hunks)
  • apps/api/src/deployment/services/deployment-writer/deployment-writer.service.ts (4 hunks)
  • apps/api/src/deployment/services/draining-deployment/draining-deployment.service.spec.ts (1 hunks)
  • apps/api/src/deployment/services/draining-deployment/draining-deployment.service.ts (1 hunks)
  • apps/api/src/deployment/services/lease/lease.service.ts (2 hunks)
  • apps/api/src/deployment/services/stale-managed-deployments-cleaner/stale-managed-deployments-cleaner.service.ts (2 hunks)
  • apps/api/src/deployment/services/top-up-custodial-balance/top-up-custodial-balance.service.ts (1 hunks)
  • apps/api/src/deployment/services/top-up-managed-deployments/top-up-managed-deployments.service.spec.ts (2 hunks)
  • apps/api/src/deployment/services/top-up-managed-deployments/top-up-managed-deployments.service.ts (3 hunks)
  • apps/api/src/provider/services/provider/provider.service.ts (2 hunks)
  • apps/api/src/routes/v1/gpu.ts (3 hunks)
  • apps/api/test/functional/deployments.spec.ts (10 hunks)
  • apps/api/tsconfig.strict.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (19)
  • apps/api/tsconfig.strict.json
  • apps/api/src/deployment/services/draining-deployment/draining-deployment.service.ts
  • apps/api/src/deployment/services/draining-deployment/draining-deployment.service.spec.ts
  • apps/api/src/deployment/services/top-up-custodial-balance/top-up-custodial-balance.service.ts
  • apps/api/src/deployment/services/top-up-managed-deployments/top-up-managed-deployments.service.ts
  • apps/api/src/deployment/services/top-up-managed-deployments/top-up-managed-deployments.service.spec.ts
  • apps/api/src/deployment/services/deployment-writer/deployment-writer.service.ts
  • apps/api/src/deployment/repositories/deployment-setting/deployment-setting.repository.ts
  • apps/api/src/deployment/services/stale-managed-deployments-cleaner/stale-managed-deployments-cleaner.service.ts
  • apps/api/src/routes/v1/gpu.ts
  • apps/api/test/functional/deployments.spec.ts
  • apps/api/src/provider/services/provider/provider.service.ts
  • apps/api/src/deployment/controllers/deployment/deployment.controller.ts
  • apps/api/src/deployment/services/cached-balance/cached-balance.service.ts
  • apps/api/src/deployment/services/lease/lease.service.ts
  • apps/api/src/deployment/services/deployment-reader/deployment-reader.service.ts
  • apps/api/src/deployment/http-schemas/deployment.schema.ts
  • apps/api/src/deployment/lib/top-up-summarizer/top-up-summarizer.ts
  • apps/api/src/billing/services/managed-signer/managed-signer.service.ts
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test-api-build
  • GitHub Check: validate-api
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@stalniy stalniy force-pushed the refactor/console-api-strict-5 branch from ec68ac5 to bd3360d Compare June 16, 2025 02:03
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🔭 Outside diff range comments (4)
apps/api/src/deployment/services/lease/lease.service.ts (1)

22-27: 🛠️ Refactor suggestion

Non-null assertion hides missing-address edge case

wallet.address! compiles but will still throw at runtime if the address is actually undefined (e.g. wallet not fully onboarded). Prefer an explicit guard with a domain-specific error:

- owner: wallet.address!,
+ if (!wallet.address) {
+   throw new Error("WALLET_ADDRESS_MISSING");
+ }
+ owner: wallet.address,
apps/api/src/deployment/controllers/deployment/deployment.controller.ts (1)

100-108: 🛠️ Refactor suggestion

Same unchecked address issue repeated

Replicate the explicit address check here too to keep behaviour consistent and avoid accidental undefined look-ups.

apps/api/src/deployment/services/deployment-reader/deployment-reader.service.ts (1)

160-170: 🛠️ Refactor suggestion

ID concatenation is collision-prone

id is built by simply concatenating dseq, gseq, and oseq without a delimiter.
1-11-1 and 11-1-1 both evaluate to the same string "1111", which may break look-ups, caching, or React key re-use.

-id: lease.lease.lease_id.dseq + lease.lease.lease_id.gseq + lease.lease.lease_id.oseq,
+id: `${lease.lease.lease_id.dseq}-${lease.lease.lease_id.gseq}-${lease.lease.lease_id.oseq}`,
apps/api/src/billing/services/managed-signer/managed-signer.service.ts (1)

84-94: ⚠️ Potential issue

Type cast drops transactionHash; risk of runtime undefined

pick(...).as Pick<IndexedTx, ...> discards transactionHash from the type system, yet you rely on it afterwards.
If tx lacks hash, the fallback branch assumes transactionHash is present but TS cannot help you.

-const result = pick(tx, ["code", "hash", "transactionHash", "rawLog"]) as Pick<
-  IndexedTx,
-  "code" | "hash" | "rawLog"
->;
+const result = pick(tx, ["code", "hash", "rawLog"]) as Pick<
+  IndexedTx,
+  "code" | "hash" | "rawLog"
+> & { transactionHash?: string };

Even better—avoid the cast completely:

const { code, hash, rawLog } = tx;
return { code, hash, rawLog, transactionHash: hash };
♻️ Duplicate comments (1)
apps/api/src/deployment/services/lease/lease.service.ts (1)

39-41: Same non-null assertion – please apply the guard here too

🧹 Nitpick comments (7)
apps/api/src/deployment/services/top-up-custodial-balance/top-up-custodial-balance.service.ts (1)

1-7: Optional: default feesBalance to zero to simplify branching

If feesBalance logically behaves like a numeric counter, consider initialising it to 0 in the Balances producer and drop the typeof === "number" guard. That keeps mutation paths uniform.

apps/api/src/deployment/services/top-up-managed-deployments/top-up-managed-deployments.service.spec.ts (1)

8-9: Type-unsafe double cast – tighten the mock instead

billingConfig as unknown as BillingConfigService defeats the purpose of strict mode. Have MockConfigService implement BillingConfigService (or a narrowed interface) and skip the cast:

-import type { BillingConfigService } from "@src/billing/services/billing-config/billing-config.service";
...
-billingConfig as unknown as BillingConfigService,
+billingConfig,
apps/api/test/functional/deployments.spec.ts (1)

80-85: Duplicated hash vs transactionHash – consider converging on one field

Tests now expect both properties with identical values. Unless there is a compelling API reason, keeping a single canonical property reduces noise and risk of drift.

Also applies to: 505-510

apps/api/src/deployment/services/cached-balance/cached-balance.service.ts (1)

28-35: Possible race condition on first fetch

Two concurrent get() calls for the same address with an empty cache may both fetch limits and overwrite each other. To avoid duplicate RPC hits consider caching a Promise<CachedBalance> or using Map#has/Map#set guard with a mutex.

-let cachedBalance = this.balanceCache.get(address);
-if (!cachedBalance) {
-  const limits = await this.balancesService.getFreshLimits({ address });
-  cachedBalance = new CachedBalance(limits.deployment);
-  this.balanceCache.set(address, cachedBalance);
-}
+if (!this.balanceCache.has(address)) {
+  const limits = await this.balancesService.getFreshLimits({ address });
+  this.balanceCache.set(address, new CachedBalance(limits.deployment));
+}
+const cachedBalance = this.balanceCache.get(address)!;
apps/api/src/deployment/services/deployment-reader/deployment-reader.service.ts (1)

164-169: Leaking extra provider fields

{ ...provider, address: provider.owner } spreads every column returned by getProviderList() (uptime, ip, etc.).
ListWithResourcesResponseSchema allows only address and hostUri.
The current implementation implicitly relies on Zod’s non-strict behaviour; once .strict() is enabled (or OpenAPI client generation is used), this will fail validation.

Either:

  1. Limit the spread to required keys, e.g. { address: provider.owner, hostUri: provider.hostUri }, or
  2. Mark the schema as non-strict explicitly to avoid accidental breakage.
apps/api/src/billing/services/managed-signer/managed-signer.service.ts (1)

54-63: Return-type definition duplicates information

You manually expanded the shape instead of extracting it into a reusable type alias.
This inflates the signature and invites drift.

-async executeDecodedTxByUserId(
-  userId: UserWalletOutput["userId"],
-  messages: EncodeObject[]
-): Promise<{
-  code: number;
-  hash: string;
-  transactionHash: string;
-  rawLog: string;
-}> {
+type TxExecutionResult = {
+  code: number;
+  hash: string;
+  transactionHash: string;
+  rawLog: string;
+};
+
+async executeDecodedTxByUserId(
+  userId: UserWalletOutput["userId"],
+  messages: EncodeObject[]
+): Promise<TxExecutionResult> {
apps/api/src/deployment/lib/top-up-summarizer/top-up-summarizer.ts (1)

25-32: Ensure set() handles undefined gracefully

set() still requires value: number.
When callers intentionally skip setting a height, they must now pass undefined, which is disallowed by the signature.

Consider:

-set(param: keyof Pick<TopUpSummary, "startBlockHeight" | "endBlockHeight">, value: number) {
+set(param: keyof Pick<TopUpSummary, "startBlockHeight" | "endBlockHeight">, value: number | undefined) {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between edbd80f and bd3360d.

📒 Files selected for processing (19)
  • apps/api/src/billing/services/managed-signer/managed-signer.service.ts (4 hunks)
  • apps/api/src/deployment/controllers/deployment/deployment.controller.ts (3 hunks)
  • apps/api/src/deployment/http-schemas/deployment.schema.ts (3 hunks)
  • apps/api/src/deployment/lib/top-up-summarizer/top-up-summarizer.ts (2 hunks)
  • apps/api/src/deployment/repositories/deployment-setting/deployment-setting.repository.ts (1 hunks)
  • apps/api/src/deployment/services/cached-balance/cached-balance.service.ts (1 hunks)
  • apps/api/src/deployment/services/deployment-reader/deployment-reader.service.ts (2 hunks)
  • apps/api/src/deployment/services/deployment-writer/deployment-writer.service.ts (4 hunks)
  • apps/api/src/deployment/services/draining-deployment/draining-deployment.service.spec.ts (1 hunks)
  • apps/api/src/deployment/services/draining-deployment/draining-deployment.service.ts (1 hunks)
  • apps/api/src/deployment/services/lease/lease.service.ts (2 hunks)
  • apps/api/src/deployment/services/stale-managed-deployments-cleaner/stale-managed-deployments-cleaner.service.ts (2 hunks)
  • apps/api/src/deployment/services/top-up-custodial-balance/top-up-custodial-balance.service.ts (1 hunks)
  • apps/api/src/deployment/services/top-up-managed-deployments/top-up-managed-deployments.service.spec.ts (2 hunks)
  • apps/api/src/deployment/services/top-up-managed-deployments/top-up-managed-deployments.service.ts (3 hunks)
  • apps/api/src/provider/services/provider/provider.service.ts (2 hunks)
  • apps/api/src/routes/v1/gpu.ts (3 hunks)
  • apps/api/test/functional/deployments.spec.ts (10 hunks)
  • apps/api/tsconfig.strict.json (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (6)
apps/api/src/deployment/controllers/deployment/deployment.controller.ts (1)
apps/indexer/drizzle/schema.ts (1)
  • deployment (180-203)
apps/api/src/deployment/services/top-up-managed-deployments/top-up-managed-deployments.service.ts (1)
packages/logging/src/servicies/logger/logger.service.ts (1)
  • error (107-109)
apps/api/src/deployment/services/deployment-writer/deployment-writer.service.ts (3)
apps/indexer/drizzle/schema.ts (1)
  • deployment (180-203)
apps/api/src/billing/repositories/user-wallet/user-wallet.repository.ts (1)
  • UserWalletOutput (16-20)
apps/api/src/deployment/http-schemas/deployment.schema.ts (2)
  • GetDeploymentResponse (252-252)
  • UpdateDeploymentRequest (259-259)
apps/api/src/provider/services/provider/provider.service.ts (1)
apps/api/src/types/provider.ts (1)
  • ProviderList (1-94)
apps/api/src/deployment/services/deployment-reader/deployment-reader.service.ts (1)
apps/indexer/drizzle/schema.ts (1)
  • provider (205-237)
apps/api/src/billing/services/managed-signer/managed-signer.service.ts (1)
apps/api/src/billing/repositories/user-wallet/user-wallet.repository.ts (1)
  • UserWalletOutput (16-20)
🔇 Additional comments (16)
apps/api/tsconfig.strict.json (1)

32-34: Included additional source folders in strict compile – looks good

Expanding strict-mode coverage to provider, certificate, and deployment code is exactly what we want for the gradual migration. No functional concerns spotted here.

apps/api/src/deployment/services/top-up-custodial-balance/top-up-custodial-balance.service.ts (1)

19-21: Good defensive guard for optional feesBalance

The extra type check prevents NaN subtraction when feesBalance is undefined. No further issues.

apps/api/src/deployment/services/top-up-managed-deployments/top-up-managed-deployments.service.ts (2)

108-116: Prefer unknown over any in catch blocks

Using error: any disables type-safety. Capture as unknown and narrow only when necessary:

-} catch (error: any) {
+} catch (error: unknown) {
+  const err = error as Error;

or introduce a helper to normalise errors.

[ suggest_essential_refactor ]


129-130: filter does not narrow the element type – use a type-guard

messageInputs.filter(x => !!x) returns (CollectedMessage | undefined)[], conflicting with the declared return type CollectedMessage[]. Provide an explicit type-guard to preserve the narrower array type:

-return messageInputs.filter(x => !!x);
+return messageInputs.filter(
+  (input): input is CollectedMessage => input !== undefined
+);

This avoids the need for later non-null assertions.
[ raise_critical_issue ]

apps/api/src/deployment/services/draining-deployment/draining-deployment.service.ts (1)

75-76: Repeated non-null assertions hide real nullability

userWallet.address! presumes the repository never stores wallets without an address.
Expose this guarantee in the type instead of suppressing the compiler:

  1. Make address non-optional in UserWalletOutput (preferred), or
  2. Guard once and early:
if (!userWallet?.address) { return 0; }
const deploymentSetting = await this.leaseRepository.findOneByDseqAndOwner(
  dseq,
  userWallet.address
);

This removes the need for ! and prevents runtime undefined dereferencing.
[ suggest_essential_refactor ]

apps/api/src/deployment/services/draining-deployment/draining-deployment.service.spec.ts (1)

210-214: LGTM – test now mirrors service contract

Changing the mock to undefined correctly follows the service’s if (!userWallet) branch.
[ approve_code_changes ]

apps/api/src/deployment/services/deployment-writer/deployment-writer.service.ts (2)

50-58: Centralise owner variable to avoid multiple ! assertions

wallet.address! is sprinkled throughout the class, repeating noise and risking missed checks. Capture once:

public async create(wallet: UserWalletOutput, input: CreateDeploymentRequest["data"]) {
-  let sdl = input.sdl;
+  const owner = wallet.address;
+  assert(owner, 400, "Wallet without address");
+  let sdl = input.sdl;

Then use owner everywhere (owner instead of wallet.address!).
Benefits: readability, single assertion, and compile-time safety.

[ suggest_optional_refactor ]


90-93: Redundant network call

After deposit, you retrieve the deployment again:

await this.signerService.executeDecodedTxByUserId(...);
return await this.deploymentReaderService.findByOwnerAndDseq(owner, dseq);

If the RPC succeeds the local deployment object is already available; consider updating its balance field locally or returning the transaction result to save one query.
[ suggest_optional_refactor ]

apps/api/src/deployment/services/stale-managed-deployments-cleaner/stale-managed-deployments-cleaner.service.ts (2)

52-57: Same narrowing issue as above

wallet.address! occurs three times; apply the same centralised guard pattern to improve safety and readability.
[ suggest_optional_refactor ]


67-76: Type-safe error handling

Use unknown for error and narrow. Also, the string check error.message.includes("not allowed to pay fees") will throw if error is not an Error. Guard first:

} catch (error: unknown) {
  if (error instanceof Error && error.message.includes("not allowed to pay fees")) {

[ suggest_essential_refactor ]

apps/api/src/deployment/controllers/deployment/deployment.controller.ts (1)

133-136: 👍 Explicit 404 for missing deployment

The new null-check using assert(deployment, 404 …) makes the intent clear and avoids leaking internal errors.

apps/api/src/routes/v1/gpu.ts (1)

64-66: LGTM – switch to undefined aligns with query replacement logic

Initialising provider_address/provider_hosturi as undefined matches the later ?? null coercion and removes double-null semantics.

apps/api/src/provider/services/provider/provider.service.ts (1)

15-16: Return type annotation adds clarity

Importing ProviderList and annotating getProviderList’s return type strengthens the public contract and will surface mismatches at compile time.

Also applies to: 102-102

apps/api/src/deployment/http-schemas/deployment.schema.ts (2)

221-233: Consider marking nested properties optional when provider is nullable

When provider is null, everything is fine, but when it’s defined the inner fields are still required.
If any of them becomes nullable in the DB (e.g. provider goes offline and loses hostUri), schema validation will fail.

Recommend mirroring the DB constraints (hostUri is NOT NULL now, but worth keeping an eye on).
No action required if that invariant is guaranteed.


244-245: Typo fix LGTM

txHash rename aligns the schema with actual field names used elsewhere.

apps/api/src/deployment/lib/top-up-summarizer/top-up-summarizer.ts (1)

9-12: Optional properties align with actual usage

Making heights optional removes the need for sentinel values.
No issues spotted.

@stalniy stalniy force-pushed the refactor/console-api-strict-5 branch 2 times, most recently from a97b6bc to 81776cf Compare June 16, 2025 03:12
@codecov
Copy link

codecov bot commented Jun 16, 2025

Codecov Report

Attention: Patch coverage is 66.66667% with 11 lines in your changes missing coverage. Please review.

Project coverage is 40.08%. Comparing base (9f7c89e) to head (ca49adf).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...ces/deployment-reader/deployment-reader.service.ts 28.57% 3 Missing and 2 partials ⚠️
apps/api/src/routes/v1/gpu.ts 0.00% 2 Missing ⚠️
.../services/managed-signer/managed-signer.service.ts 66.66% 1 Missing ⚠️
...eployment-setting/deployment-setting.repository.ts 0.00% 1 Missing ⚠️
...eaner/stale-managed-deployments-cleaner.service.ts 0.00% 1 Missing ⚠️
...todial-balance/top-up-custodial-balance.service.ts 0.00% 1 Missing ⚠️

❌ Your patch status has failed because the patch coverage (66.66%) is below the target coverage (80.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1488      +/-   ##
==========================================
- Coverage   40.09%   40.08%   -0.01%     
==========================================
  Files         870      870              
  Lines       21016    21023       +7     
  Branches     3857     3863       +6     
==========================================
+ Hits         8427     8428       +1     
- Misses      12410    12414       +4     
- Partials      179      181       +2     
Flag Coverage Δ *Carryforward flag
api 71.08% <66.66%> (-0.07%) ⬇️
deploy-web 18.37% <ø> (ø) Carriedforward from 9f7c89e
notifications 89.21% <ø> (ø) Carriedforward from 9f7c89e
provider-proxy 80.09% <ø> (ø) Carriedforward from 9f7c89e

*This pull request uses carry forward flags. Click here to find out more.

Files with missing lines Coverage Δ
...nt/controllers/deployment/deployment.controller.ts 100.00% <100.00%> (ø)
...i/src/deployment/http-schemas/deployment.schema.ts 100.00% <ø> (ø)
...loyment/lib/top-up-summarizer/top-up-summarizer.ts 100.00% <ø> (ø)
.../services/cached-balance/cached-balance.service.ts 100.00% <100.00%> (ø)
...ces/deployment-writer/deployment-writer.service.ts 98.43% <100.00%> (ø)
...draining-deployment/draining-deployment.service.ts 100.00% <100.00%> (ø)
...api/src/deployment/services/lease/lease.service.ts 100.00% <100.00%> (ø)
...-deployments/top-up-managed-deployments.service.ts 98.93% <100.00%> (ø)
...src/provider/services/provider/provider.service.ts 64.38% <100.00%> (ø)
.../services/managed-signer/managed-signer.service.ts 96.42% <66.66%> (ø)
... and 5 more

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@stalniy
Copy link
Contributor Author

stalniy commented Jun 16, 2025

this PR is about refactoring to strict types without introducing any new logic. That's why coverage report failure will be ignored

@stalniy stalniy force-pushed the refactor/console-api-strict-5 branch from 81776cf to ca49adf Compare June 17, 2025 07:28
@stalniy stalniy merged commit 6a41b0c into main Jun 17, 2025
26 of 27 checks passed
@stalniy stalniy deleted the refactor/console-api-strict-5 branch June 17, 2025 07:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

Comments