Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/wonders lords cost #2384

Merged
merged 25 commits into from
Dec 10, 2024
Merged

Fix/wonders lords cost #2384

merged 25 commits into from
Dec 10, 2024

Conversation

bob0005
Copy link
Collaborator

@bob0005 bob0005 commented Dec 10, 2024

Closes #2354

Summary by CodeRabbit

  • New Features
    • Enhanced cost calculations for resources and buildings based on the presence of a wonder in the realm.
    • Added prefetch links for improved resource loading efficiency in the HTML.
  • Bug Fixes
    • Streamlined checks for cost existence, improving accuracy in cost display.
  • Chores
    • Updated configuration to include error handling for environment variables.
    • Removed redundant code and improved formatting in various components for clarity and consistency.

Copy link

vercel bot commented Dec 10, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
eternum ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 10, 2024 4:45pm
eternum-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 10, 2024 4:45pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
eternum-landing ⬜️ Ignored (Inspect) Visit Preview Dec 10, 2024 4:45pm

Copy link
Contributor

coderabbitai bot commented Dec 10, 2024

Warning

Rate limit exceeded

@bob0005 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 21 minutes and 20 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between e1092f3 and e912561.

📒 Files selected for processing (1)
  • .github/workflows/test-contracts.yml (1 hunks)

Walkthrough

The changes in this pull request enhance the SelectPreviewBuilding.tsx component by updating how resource costs are calculated based on the presence of a "wonder" in the realm. Adjustments are made to the ResourceInfo and BuildingInfo components, where cost variables are changed from constants to mutable variables. The logic for cost calculations has been refined, streamlining checks for resource costs and ensuring the UI accurately reflects these updates. Additionally, several other components and configuration files have been modified for consistency and clarity.

Changes

File Path Change Summary
client/src/ui/components/construction/SelectPreviewBuilding.tsx Updated cost calculations in ResourceInfo and BuildingInfo to adjust based on realm wonders. Changed cost variables from constants to mutable variables (let). Streamlined checks for cost existence.
client/src/ui/utils/utils.tsx Added adjustWonderLordsCost function to modify resource costs for lords.
client/index.html Added multiple <link rel="prefetch"> elements for resource preloading; removed a redundant <meta> tag.
client/src/dojo/modelManager/ResourceManager.ts Refactored _netRate method for clarity; no changes to logic or signatures.
.knip.json Updated ignore section to add new paths for ignored files.
common/addresses/addresses.MAINNET.json Removed trailing comma from JSON structure.
config/index.ts Added error handling for environment variables and improved configuration structure.
contracts/.tool-versions Updated dojo dependency version from 1.0.3 to 1.0.5.
landing/public/resource_addresses/mainnet/resource_addresses.json Added a newline character at the end of the file for formatting.
landing/src/components/modules/bridge-in.tsx Adjusted button's disabled state logic and ensured consistent prop usage in SelectResourceToBridge.
landing/src/components/modules/bridge-out-step-1.tsx Removed commented-out code for total fee calculation; minor formatting adjustments made.
landing/src/components/modules/bridge-out-step-2.tsx Streamlined import statements and improved state initialization formatting.
landing/src/components/modules/season-start-timer.tsx Modified formatting of destructured assignment for clarity.
landing/src/components/ui/elements/CountdownTimer.tsx Added semicolon for consistency; reformatted destructuring assignment for readability.
landing/src/hooks/useBridge.tsx Improved formatting in _bridgeIntoRealm and related functions without changing logic.
landing/src/routeTree.gen.ts Changed all string literals from single quotes to double quotes for consistency.
sdk/packages/eternum/src/provider/index.ts Enhanced EternumProvider class with batching functionality and improved console log formatting.

Possibly related PRs

  • fix: resource precision on production #1978: This PR modifies the SelectPreviewBuilding.tsx component, focusing on resource production calculations, which is closely related to the cost adjustments made in the main PR for the same component.
  • feat: force to accept terms of service #2370: This PR introduces a requirement for users to accept the terms of service, which may relate to the user experience enhancements in the main PR, particularly if the changes involve user interactions with the bridge features.
  • refactor bridge - prepare for main merge #2371: This PR refactors the bridge functionality, which is closely related to the main PR's focus on enhancing the BridgeIn component and its associated logic.
  • feat: add countdown backdrop to client page #2383: This PR adds a countdown backdrop to the client page, which may relate to the overall user interface improvements in the main PR, especially if it involves timing or resource management features.

Suggested reviewers

  • edisontim

🐰 In the realm where wonders gleam,
Costs now dance, a new-found dream.
With lords and markets, changes flow,
Mutable magic makes costs glow!
A rabbit's cheer for code so bright,
Adjustments made, all feels just right! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Experiment)
  • @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.

Copy link
Contributor

mentatbot bot commented Dec 10, 2024

You are out of MentatBot reviews. Your usage will refresh December 16 at 08:00 AM.

Copy link

Failed to generate code suggestions for PR

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: 2

🧹 Outside diff range and nitpick comments (1)
client/src/ui/components/construction/SelectPreviewBuilding.tsx (1)

Line range hint 602-621: Simplify conditional rendering of ongoing costs

You can simplify the conditional rendering by using logical AND (&&) instead of a ternary operator returning null. This improves readability.

Apply this change:

-{ongoingCost.length > 0 ? (
+{ongoingCost.length > 0 && (
   <>
     <div className="font-bold uppercase">consumed per/s</div>
     <div className="grid grid-cols-2 gap-2">
       {resourceProduced !== 0 &&
         Object.keys(ongoingCost).map((resourceId, index) => {
           const balance = getBalance(entityId || 0, ongoingCost[Number(resourceId)].resource);
           return (
             <ResourceCost
               key={`ongoing-cost-${index}`}
               type="horizontal"
               resourceId={ongoingCost[Number(resourceId)].resource}
               amount={ongoingCost[Number(resourceId)].amount}
               balance={balance.balance}
             />
           );
         })}
     </div>
   </>
- ) : null}
+)}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cc79639 and 7024782.

📒 Files selected for processing (1)
  • client/src/ui/components/construction/SelectPreviewBuilding.tsx (3 hunks)

Comment on lines 536 to 543
let ongoingCost = resourceProduced !== undefined ? configManager.resourceInputs[resourceProduced] || [] : [];

const realm = getComponentValue(dojo.setup.components.Realm, getEntityIdFromKeys([BigInt(entityId || 0)]));
if (buildingId == BuildingType.Market && realm?.has_wonder && ongoingCost.length > 0) {
ongoingCost = ongoingCost.map((cost) =>
cost.resource === ResourcesIds.Lords ? { ...cost, amount: cost.amount * 0.1 } : cost,
);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use the helper function for consistent cost adjustment

Apply the adjustLordsCost helper function here as well to maintain consistency and reduce code duplication.

Update the ongoing cost adjustment:

 if (buildingId == BuildingType.Market && realm?.has_wonder && ongoingCost.length > 0) {
-  ongoingCost = ongoingCost.map((cost) =>
-    cost.resource === ResourcesIds.Lords ? { ...cost, amount: cost.amount * 0.1 } : cost,
-  );
+  ongoingCost = adjustLordsCost(ongoingCost);
 }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 399 to 404
let cost = configManager.resourceInputs[resourceId];

const realm = getComponentValue(dojo.setup.components.Realm, getEntityIdFromKeys([BigInt(entityId || 0)]));
if (resourceId == ResourcesIds.Donkey && realm?.has_wonder) {
cost = cost.map((cost) => (cost.resource === ResourcesIds.Lords ? { ...cost, amount: cost.amount * 0.1 } : cost));
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor duplicate cost adjustment logic into a helper function

The logic for adjusting the Lords resource cost when the realm has a wonder is duplicated in lines 402-404 and 539-543. Consider extracting this logic into a reusable helper function to improve maintainability and reduce code duplication.

Apply the following changes:

  1. Create a helper function adjustLordsCost:
+const adjustLordsCost = (cost: ResourceCostType[]): ResourceCostType[] => {
+  return cost.map((item) =>
+    item.resource === ResourcesIds.Lords ? { ...item, amount: item.amount * 0.1 } : item,
+  );
+};
  1. Update the cost adjustment in lines 402-404:
 if (resourceId == ResourcesIds.Donkey && realm?.has_wonder) {
-  cost = cost.map((cost) => (cost.resource === ResourcesIds.Lords ? { ...cost, amount: cost.amount * 0.1 } : cost));
+  cost = adjustLordsCost(cost);
 }

Committable suggestion skipped: line range outside the PR's diff.

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: 4

🧹 Outside diff range and nitpick comments (1)
sdk/packages/eternum/src/provider/index.ts (1)

306-306: Enhance debug logging for better traceability.

The current console.log could be more informative by including additional context about the operation being performed.

-    console.log({ resources });
+    console.log('Starting withdrawal from realm:', { resources, through_bank_id, from_realm_entity_id });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7024782 and e1092f3.

📒 Files selected for processing (17)
  • .knip.json (2 hunks)
  • client/index.html (0 hunks)
  • client/src/dojo/modelManager/ResourceManager.ts (1 hunks)
  • client/src/ui/components/construction/SelectPreviewBuilding.tsx (4 hunks)
  • client/src/ui/utils/utils.tsx (2 hunks)
  • common/addresses/addresses.MAINNET.json (1 hunks)
  • config/index.ts (1 hunks)
  • contracts/.tool-versions (1 hunks)
  • landing/public/resource_addresses/mainnet/resource_addresses.json (1 hunks)
  • landing/src/components/modules/bridge-in.tsx (2 hunks)
  • landing/src/components/modules/bridge-out-step-1.tsx (1 hunks)
  • landing/src/components/modules/bridge-out-step-2.tsx (4 hunks)
  • landing/src/components/modules/season-start-timer.tsx (1 hunks)
  • landing/src/components/ui/elements/CountdownTimer.tsx (1 hunks)
  • landing/src/hooks/useBridge.tsx (1 hunks)
  • landing/src/routeTree.gen.ts (2 hunks)
  • sdk/packages/eternum/src/provider/index.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • client/index.html
✅ Files skipped from review due to trivial changes (9)
  • contracts/.tool-versions
  • landing/public/resource_addresses/mainnet/resource_addresses.json
  • common/addresses/addresses.MAINNET.json
  • landing/src/components/modules/season-start-timer.tsx
  • landing/src/components/modules/bridge-out-step-1.tsx
  • landing/src/hooks/useBridge.tsx
  • landing/src/components/ui/elements/CountdownTimer.tsx
  • client/src/dojo/modelManager/ResourceManager.ts
  • landing/src/routeTree.gen.ts
🔇 Additional comments (6)
.knip.json (1)

15-16: LGTM: Configuration updates for ignored paths.

The additions to the ignore list are appropriate for excluding documentation and configuration files from processing.

Also applies to: 29-32

client/src/ui/utils/utils.tsx (1)

499-501: Well-implemented helper function!

The adjustWonderLordsCost function is a clean, pure function that handles a single responsibility well. It correctly adjusts the Lords resource cost while maintaining immutability.

client/src/ui/components/construction/SelectPreviewBuilding.tsx (2)

400-405: Good implementation of wonder cost adjustment!

The code correctly applies the wonder cost adjustment for donkeys while maintaining clean variable scoping.


537-543: Good implementation of market building cost adjustment!

The code correctly applies the wonder cost adjustment for the market building, following the same pattern as the resource cost adjustment.

landing/src/components/modules/bridge-in.tsx (1)

250-250: Clean formatting improvement!

The removal of the unnecessary line break improves code readability while maintaining the same logical condition.

sdk/packages/eternum/src/provider/index.ts (1)

308-312: Verify the contract address resolution for resource bridge systems.

The contract address resolution is critical for this financial operation. Let's verify that the contract name resolution is consistent across the codebase.

✅ Verification successful

The search results show consistent usage of the contract name ${NAMESPACE}-resource_bridge_systems across the codebase:

  1. In the SDK (sdk/packages/eternum/src/provider/index.ts), it's used with getContractByName for various operations like deposit, withdraw, etc.
  2. In deployment scripts (season_resources/scripts/deployment/libs/commands.js), it follows the same pattern
  3. In the contracts (contracts/src/systems/resources/contracts/resource_bridge_systems.cairo), it's properly defined and tested
  4. In manifest files (contracts/manifest_*.json), it's consistently registered with the tag s0_eternum-resource_bridge_systems

The contract name resolution in the code under review matches the pattern used throughout the codebase and is correctly implemented.

Contract name resolution for resource bridge systems is correctly implemented.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify contract name usage consistency
# Test: Search for resource bridge systems contract references
rg -A 2 "resource_bridge_systems" 

Length of output: 31726

Comment on lines +127 to +131
(setupConfig.bridge = {
...EternumGlobalConfig.bridge,
velords_fee_recipient: BigInt('0x045c587318c9ebcf2fbe21febf288ee2e3597a21cd48676005a5770a50d433c5'), // burner
velords_fee_recipient: BigInt("0x045c587318c9ebcf2fbe21febf288ee2e3597a21cd48676005a5770a50d433c5"), // burner
season_pool_fee_recipient: BigInt(getContractByName(manifest, `${NAMESPACE}-season_systems`)),
},

// Season Pass
setupConfig.season = {
...EternumGlobalConfig.season,
seasonPassAddress: process.env.VITE_SEASON_PASS_ADDRESS!,
realmsAddress: process.env.VITE_REALMS_ADDRESS!,
lordsAddress: process.env.VITE_LORDS_ADDRESS!,
};
}),
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid hardcoding wallet addresses in production code.

The bridge configuration uses a hardcoded burner address for velords_fee_recipient. This could be risky in production and makes the code less maintainable.

Consider using an environment variable instead:

- velords_fee_recipient: BigInt("0x045c587318c9ebcf2fbe21febf288ee2e3597a21cd48676005a5770a50d433c5"), // burner
+ velords_fee_recipient: BigInt(process.env.VITE_VELORDS_FEE_RECIPIENT!),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
(setupConfig.bridge = {
...EternumGlobalConfig.bridge,
velords_fee_recipient: BigInt('0x045c587318c9ebcf2fbe21febf288ee2e3597a21cd48676005a5770a50d433c5'), // burner
velords_fee_recipient: BigInt("0x045c587318c9ebcf2fbe21febf288ee2e3597a21cd48676005a5770a50d433c5"), // burner
season_pool_fee_recipient: BigInt(getContractByName(manifest, `${NAMESPACE}-season_systems`)),
},
// Season Pass
setupConfig.season = {
...EternumGlobalConfig.season,
seasonPassAddress: process.env.VITE_SEASON_PASS_ADDRESS!,
realmsAddress: process.env.VITE_REALMS_ADDRESS!,
lordsAddress: process.env.VITE_LORDS_ADDRESS!,
};
}),
(setupConfig.bridge = {
...EternumGlobalConfig.bridge,
velords_fee_recipient: BigInt(process.env.VITE_VELORDS_FEE_RECIPIENT!),
season_pool_fee_recipient: BigInt(getContractByName(manifest, `${NAMESPACE}-season_systems`)),
}),

Comment on lines +133 to +138
(setupConfig.season = {
...EternumGlobalConfig.season,
seasonPassAddress: process.env.VITE_SEASON_PASS_ADDRESS!,
realmsAddress: process.env.VITE_REALMS_ADDRESS!,
lordsAddress: process.env.VITE_LORDS_ADDRESS!,
});
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Environment variables are validated but documentation needs improvement

The environment variables are properly validated using Zod schema in both client/env.ts and landing/env.ts:

VITE_SEASON_PASS_ADDRESS: z.string().startsWith("0x"),
VITE_REALMS_ADDRESS: z.string().startsWith("0x"),
VITE_LORDS_ADDRESS: z.string().startsWith("0x"),

However, there are a few concerns:

  • The variables are populated through deployment scripts (scripts/deploy.sh and scripts/indexer.sh)
  • No sample .env file or documentation found to guide developers on setting up these required variables
  • The use of non-null assertion (!) in the config suggests these variables are required but this isn't documented
🔗 Analysis chain

Verify environment variables for season configuration.

The season configuration relies on multiple environment variables without validation.

Let's verify these environment variables are properly documented:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if these environment variables are documented
echo "Checking for environment variables documentation..."
rg -l "VITE_SEASON_PASS_ADDRESS|VITE_REALMS_ADDRESS|VITE_LORDS_ADDRESS" .env* README.md docs/

Length of output: 306


Script:

#!/bin/bash
# Let's first find any .env files and documentation files in the repository
echo "Finding environment and documentation files..."
fd -t f "^\.env" -t f "^README" -t f "\.md$"

# Let's also check for environment variable usage in the codebase
echo -e "\nChecking environment variable usage..."
rg "VITE_(SEASON_PASS|REALMS|LORDS)_ADDRESS"

# Let's check if there's any validation logic for these variables
echo -e "\nChecking for validation logic..."
rg "process\.env\.VITE_(SEASON_PASS|REALMS|LORDS)_ADDRESS" -A 2 -B 2

Length of output: 5352

Comment on lines +97 to +99
setSelectedResourceIds(
currentDonkeyInfo!.donkeyResources.map((resource) => resource.resourceId as never) ?? 0,
);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve type safety and error handling in resource selection.

The current implementation has several issues:

  1. Unsafe null assertion with currentDonkeyInfo!
  2. Type casting with as never is a code smell
  3. Missing error handling for edge cases

Consider this safer implementation:

- setSelectedResourceIds(
-   currentDonkeyInfo!.donkeyResources.map((resource) => resource.resourceId as never) ?? 0,
- );
+ if (currentDonkeyInfo?.donkeyResources) {
+   setSelectedResourceIds(
+     currentDonkeyInfo.donkeyResources.map((resource) => resource.resourceId)
+   );
+ } else {
+   setSelectedResourceIds([]);
+ }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
setSelectedResourceIds(
currentDonkeyInfo!.donkeyResources.map((resource) => resource.resourceId as never) ?? 0,
);
if (currentDonkeyInfo?.donkeyResources) {
setSelectedResourceIds(
currentDonkeyInfo.donkeyResources.map((resource) => resource.resourceId)
);
} else {
setSelectedResourceIds([]);
}

Comment on lines +318 to +325

return await this.executeAndCheckTransaction(signer, [
{
contractAddress: getContractByName(this.manifest, `${NAMESPACE}-resource_bridge_systems`),
entrypoint: "finish_withdraw",
calldata: [through_bank_id, from_entity_id, tokenAddress, recipient_address, client_fee_recipient],
},
]);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding error handling for invalid addresses.

While the formatting improvements look good, this critical financial operation should include validation for the input addresses.

 public async bridge_finish_withdraw_from_realm(props: SystemProps.BridgeFinishWithdrawFromRealmProps) {
     const { tokenAddress, through_bank_id, from_entity_id, recipient_address, client_fee_recipient, signer } = props;
+    
+    // Validate addresses
+    if (!tokenAddress || !recipient_address || !client_fee_recipient) {
+      throw new Error('Invalid addresses provided for bridge withdrawal completion');
+    }

     return await this.executeAndCheckTransaction(signer, [
       {
         contractAddress: getContractByName(this.manifest, `${NAMESPACE}-resource_bridge_systems`),
         entrypoint: "finish_withdraw",
         calldata: [through_bank_id, from_entity_id, tokenAddress, recipient_address, client_fee_recipient],
       },
     ]);
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return await this.executeAndCheckTransaction(signer, [
{
contractAddress: getContractByName(this.manifest, `${NAMESPACE}-resource_bridge_systems`),
entrypoint: "finish_withdraw",
calldata: [through_bank_id, from_entity_id, tokenAddress, recipient_address, client_fee_recipient],
},
]);
public async bridge_finish_withdraw_from_realm(props: SystemProps.BridgeFinishWithdrawFromRealmProps) {
const { tokenAddress, through_bank_id, from_entity_id, recipient_address, client_fee_recipient, signer } = props;
// Validate addresses
if (!tokenAddress || !recipient_address || !client_fee_recipient) {
throw new Error('Invalid addresses provided for bridge withdrawal completion');
}
return await this.executeAndCheckTransaction(signer, [
{
contractAddress: getContractByName(this.manifest, `${NAMESPACE}-resource_bridge_systems`),
entrypoint: "finish_withdraw",
calldata: [through_bank_id, from_entity_id, tokenAddress, recipient_address, client_fee_recipient],
},
]);
}

@ponderingdemocritus ponderingdemocritus merged commit 1cfe4ff into next Dec 10, 2024
24 of 29 checks passed
@ponderingdemocritus ponderingdemocritus deleted the fix/wonders-lords-cost branch December 10, 2024 20:02
This was referenced Dec 10, 2024
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.

[client] wonder prod + info panel
4 participants