-
Notifications
You must be signed in to change notification settings - Fork 20
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
feat: add Initia widget #1182
feat: add Initia widget #1182
Conversation
The latest updates on your projects. Learn more about Vercel for Git ↗︎
6 Skipped Deployments
|
WalkthroughThis pull request introduces significant architectural changes to the application, focusing on transaction handling, wallet integration, and code organization. The primary modifications include replacing the existing signing client approach with a more abstracted Changes
Sequence DiagramsequenceDiagram
participant User
participant WalletWidget
participant App
participant SignAndBroadcast
participant Blockchain
User->>WalletWidget: Connect Wallet
WalletWidget->>App: Provide Wallet Context
App->>SignAndBroadcast: Prepare Transaction
SignAndBroadcast->>Blockchain: Sign and Broadcast
Blockchain-->>SignAndBroadcast: Transaction Response
SignAndBroadcast-->>App: Transaction Result
App->>User: Display Transaction Outcome
Poem
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 comments (2)
src/lib/providers/cosmos-kit/index.tsx (1)
Line range hint
39-43
: Security: Move WalletConnect projectId to environment variables.The WalletConnect projectId should not be hardcoded in the source code as it could be misused if exposed.
Consider moving it to environment variables:
walletConnectOptions={{ signClient: { - projectId: "89b53d909ae6d042df584d8fb0491a77", + projectId: process.env.REACT_APP_WALLET_CONNECT_PROJECT_ID, relayUrl: "wss://relay.walletconnect.org", }, }}src/lib/components/modal/WasmCodeSnippet.tsx (1)
Line range hint
156-156
: Fix template literal escaping in Axios code snippet.The template literal syntax in the Axios code snippet might cause issues as the backticks and
${}
are not properly escaped.Apply this fix:
- const res = await axios.get(\`$\{lcdURL}/cosmwasm/wasm/v1/contract/$\{contractAddress}/smart/$\{queryB64Encoded}\`); + const res = await axios.get(`${lcdURL}/cosmwasm/wasm/v1/contract/${contractAddress}/smart/${queryB64Encoded}`);Also applies to: 157-157, 158-158
🧹 Nitpick comments (26)
src/lib/utils/tx/createTxHash.ts (1)
4-5
: Add JSDoc comments for better documentation.Consider adding JSDoc comments to document the function's purpose, parameters, and return value. This would help other developers understand the expected format of
txRaw
and the resulting hash format.+/** + * Creates a transaction hash from a base64-encoded transaction. + * @param txRaw - The raw transaction encoded in base64 + * @returns The uppercase hex-encoded SHA256 hash of the transaction + */ export const createTxHash = (txRaw: string) => toHex(sha256(Uint8Array.from(Buffer.from(txRaw, "base64")))).toUpperCase();src/lib/app-provider/tx/submitProposal.ts (1)
35-36
: Enhance error handling for better debugging.Consider making the error message more specific about requirements and consistent with the store code proposal implementation that checks both address and chain name.
- if (!address) - throw new Error("No address provided (useSubmitWhitelistProposalTx)"); + if (!address || !chainName) + throw new Error("Missing required parameters: address or chain name (useSubmitWhitelistProposalTx)");src/lib/app-provider/tx/updateAdmin.ts (1)
Line range hint
1-53
: Great architectural improvement in transaction handling!The refactoring from
useGetSigningClient
touseSignAndBroadcast
is a positive architectural change that:
- Simplifies the transaction flow by combining signing and broadcasting
- Makes the code more maintainable by reducing complexity
- Provides a more consistent pattern across the application
Consider documenting this new transaction pattern in the project's technical documentation to help other developers understand the preferred approach.
src/lib/app-provider/tx/storeCode.ts (1)
41-41
: Consider adding error handling for WASM processing.While the WASM byte code handling works correctly, consider adding try-catch blocks around the gzip operation as it could fail for invalid or large WASM files.
- wasmByteCode: Uint8Array.from(await gzip(await wasmCode)), + wasmByteCode: await (async () => { + try { + const buffer = await wasmCode; + const compressed = await gzip(buffer); + return Uint8Array.from(compressed); + } catch (error) { + throw new Error(`Failed to process WASM code: ${error.message}`); + } + })(),Also applies to: 53-57
src/lib/pages/proposal/store-code/index.tsx (2)
Line range hint
293-356
: Optimize dependency array and enhance error handling inproceed
function.The
proceed
function's dependency array includes JSON.stringify of addresses, which could cause unnecessary re-renders. Consider these improvements:
- Move the address transformation outside the dependency array:
-JSON.stringify(addresses), +addresses.length, // Only depend on the length if order doesn't matter
- Add error handling for WASM file operations:
const submitStoreCodeProposalMsg = async () => { if (!walletAddress) return []; + try { + const wasmBuffer = await wasmFile.arrayBuffer(); + const gzippedWasm = await gzip(wasmBuffer); return [ composeStoreCodeProposalMsg({ proposer: walletAddress, title, description: proposalDesc, runAs, - wasmByteCode: Uint8Array.from( - await gzip(await wasmFile.arrayBuffer()) - ), + wasmByteCode: new Uint8Array(gzippedWasm.buffer), // ... rest of the parameters }), ]; + } catch (error) { + setSimulateStatus({ + status: "failed", + message: `Failed to process WASM file: ${error.message}`, + }); + return []; + } };
Line range hint
132-146
: Enhance simulation status management.The simulation status management could be more robust. Consider creating a custom hook to manage simulation states and provide type safety:
type SimulationStatus = { status: 'default' | 'simulating' | 'succeeded' | 'failed'; message: string; error?: Error; }; const useSimulationStatus = () => { const [status, setStatus] = useState<SimulationStatus>({ status: 'default', message: '', }); return { status, setSimulating: () => setStatus({ status: 'simulating', message: 'Checking Wasm file and proposal conditions validity', }), setSuccess: (message: string) => setStatus({ status: 'succeeded', message, }), setError: (error: Error) => setStatus({ status: 'failed', message: error.message, error, }), reset: () => setStatus({ status: 'default', message: '', }), }; };src/lib/app-provider/hooks/useCurrentChain.ts (2)
12-27
: NewCurrentChain
interface
This interface is well-structured, separating chain properties and wallet provider context. Consider adding documentation comments for each interface property to explain usage.
30-53
: Conditional return for Initia vs. CosmosKit
This logic is clear and properly checksisInitia
, returning the correct chain context. If more wallets or chain integrations are expected, you may want to refactor into smaller specialized hooks or use a factory pattern to handle each provider elegantly.src/lib/app-provider/hooks/useSignAndBroadcast.ts (2)
14-62
:getTxResponse
polling logic
Polling for the transaction response is well-structured. However, consider parameterizingTIME_OUT_MS
andPOLL_INTERVAL_MS
if you anticipate needing different intervals for varied network conditions.
64-68
:SignAndBroadcastParams
interface
Straightforward definition. Validate if additional fields (memo, gasPrice, etc.) are needed for your transaction flow.src/lib/app-fns/tx/instantiate.tsx (1)
Line range hint
46-47
: Address the TODO comment about type hack.The comment indicates a type hack that should be addressed to maintain type safety.
Would you like me to help implement a proper type-safe solution for this return type?
src/lib/app-provider/hooks/useDummyWallet.ts (1)
48-49
: Consider memoizing registry and aminoTypes.The
registry
andaminoTypes
are recreated on every render since they're outside the effect. Consider memoizing them to prevent unnecessary recreations.+const { registry, aminoTypes } = useMemo( + () => getCustomedSigningCosmwasm(), + [] +);src/lib/app-provider/tx/instantiate.ts (2)
41-42
: Fix typo in error message.There's a typo in the error message: "useInstantiatetContractTx" has an extra 't'.
-throw new Error("No address provided (useInstantiatetContractTx)"); +throw new Error("No address provided (useInstantiateContractTx)");
61-65
: Consider enhancing analytics tracking.The success tracking could include more context about the instantiated contract for better analytics insights.
onTxSucceed: (txResult, contractLabel, contractAddress) => { - trackTxSucceed(); + trackTxSucceed({ + type: 'instantiate', + label: contractLabel, + address: contractAddress + }); onTxSucceed?.(txResult, contractLabel, contractAddress); },src/lib/app-provider/tx/clearAdmin.ts (1)
Line range hint
45-57
: Consider batching query invalidation.The multiple query invalidations could be optimized by using a single invalidation with an array of keys.
-Promise.all([ - queryClient.invalidateQueries({ - queryKey: [CELATONE_QUERY_KEYS.ADMINS_BY_CONTRACTS], - }), - queryClient.invalidateQueries({ - queryKey: [CELATONE_QUERY_KEYS.CONTRACT_DATA], - }), -]); +queryClient.invalidateQueries({ + queryKey: [ + [CELATONE_QUERY_KEYS.ADMINS_BY_CONTRACTS], + [CELATONE_QUERY_KEYS.CONTRACT_DATA] + ] +});src/lib/app-provider/tx/execute.ts (1)
12-18
: Consider improving type safety for message handling.The
msg
parameter accepts both string and object types, which could lead to runtime errors. Consider using a more specific type.-msg: string | object; +type ExecuteMsg = string | Record<string, unknown>; +msg: ExecuteMsg;src/lib/app-provider/hooks/useSimulateFee.ts (1)
18-67
: Consider enhancing error handling for non-dummy clients.While the implementation is solid, error handling could be improved for non-dummy client paths.
Consider wrapping the Initia widget and CosmosKit paths with try-catch blocks:
if (walletProvider.type === "initia-widget") { const { estimateTx } = walletProvider.context; - return estimateTx({ messages }, chainId).then(zGas(z.number()).parse); + try { + return estimateTx({ messages }, chainId).then(zGas(z.number()).parse); + } catch (error) { + throw new Error(`Failed to estimate fee with Initia widget: ${error.message}`); + } } // Otherwise, use the CosmosKit const client = await getSigningClient(); -return client - .simulate(address, messages, undefined) - .then(zGas(z.number()).parse); +try { + return client + .simulate(address, messages, undefined) + .then(zGas(z.number()).parse); +} catch (error) { + throw new Error(`Failed to simulate fee with CosmosKit: ${error.message}`); +}src/lib/components/wallet-section/index.tsx (1)
Line range hint
53-76
: Consider extracting common button props to reduce duplication.The implementation is good, but there's some duplication in the ConnectWalletButton props.
Consider extracting common props:
+const commonButtonProps = { + icon: "wallet", + iconColor: "text.main", +}; +const connectedButtonProps = { + icon: "wallet-solid", + variant: "ghost-primary", +}; <WalletConnectComponent walletStatus={walletProvider.context.status} disconnect={ <ConnectWalletButton buttonText="Connect Wallet" onClick={onClickConnect} - iconColor="text.main" - icon="wallet" + {...commonButtonProps} /> } connecting={<ConnectWalletButton isLoading />} connected={ <ConnectWalletButton buttonText={truncate(address)} - icon="wallet-solid" onClick={onClickOpenView} - variant="ghost-primary" + {...connectedButtonProps} /> }src/lib/app-fns/tx/updateAdmin.tsx (1)
36-36
: Consider moving callback after transaction validation.The
onTxSucceed
callback is called after getting txInfo but before validating the transaction fee. Consider moving it after all validations to ensure the transaction truly succeeded.- ({ value: txInfo }) => { - onTxSucceed?.(); - const txFee = findAttr(txInfo.events, "tx", "fee"); + ({ value: txInfo }) => { + const txFee = findAttr(txInfo.events, "tx", "fee"); + onTxSucceed?.();src/lib/app-provider/hooks/useGetSigningClient.ts (2)
51-52
: Improve error message clarity.The error message could be more descriptive to help with troubleshooting.
- if (!signer || !("signAmino" in signer)) - throw new Error("Unsupport signAmino type for getSigningClient"); + if (!signer || !("signAmino" in signer)) + throw new Error( + "Invalid signer: SignAmino capability is required for Ledger wallet integration" + );
61-65
: Consider extracting wallet-specific logic.The function handles multiple responsibilities. Consider extracting the wallet-specific logic into separate functions for better maintainability.
+ const getLedgerSigningClient = async (walletClient: WalletClient) => { + const signer = walletClient.getOfflineSignerAmino?.(chainId) ?? + (await walletClient.getOfflineSigner?.(chainId, "amino")); + + if (!signer || !("signAmino" in signer)) + throw new Error( + "Invalid signer: SignAmino capability is required for Ledger wallet integration" + ); + + return SigningCosmWasmClient.connectWithSigner( + rpcEndpoint, + signer, + getCustomedSigningCosmwasm() + ); + }; + return async () => { if (walletClient && (await isLedger(walletClient, chainId))) { - const signer = walletClient.getOfflineSignerAmino?.(chainId) ?? - (await walletClient.getOfflineSigner?.(chainId, "amino")); - - if (!signer || !("signAmino" in signer)) - throw new Error("Unsupport signAmino type for getSigningClient"); - - return SigningCosmWasmClient.connectWithSigner( - rpcEndpoint, - signer, - getCustomedSigningCosmwasm() - ); + return getLedgerSigningClient(walletClient); } if (walletProvider.type === "cosmos-kit") { return await walletProvider.context.getSigningCosmWasmClient(); } throw new Error("Unsupported wallet provider type for getSigningClient"); };src/lib/app-fns/tx/execute.tsx (2)
24-24
: Consider enhancing error handling for activity tracking.While the migration to
signAndBroadcast
is clean, consider wrapping the activity callback in a try-catch block to ensure errors don't propagate up the chain.({ value: txInfo }) => { + try { onTxSucceed?.({ type: "execute", action, sender: address, contractAddress, msg: base64Message, timestamp: getCurrentDate(), }); + } catch (error) { + console.error('Failed to track activity:', error); + // Continue with the transaction success flow + }Also applies to: 36-36, 43-43
6-6
: Excellent architectural improvement!The migration from direct client usage to
SignAndBroadcast
represents a solid architectural improvement that:
- Reduces coupling to specific client implementations
- Provides a more consistent transaction handling pattern
- Makes the codebase more maintainable and testable
src/lib/components/modal/RedoModal.tsx (1)
Line range hint
52-94
: Consider enhancing the error message for better UX.The current message about unsupported
MsgInstantiateContract2
could be more user-friendly by:
- Explaining why MsgInstantiateContract2 isn't supported
- Clarifying if there are any functional differences between the two message types
- Indicating if MsgInstantiateContract2 support is planned
src/lib/app-fns/tx/storeCode.tsx (1)
58-58
: Consider adding error handling for signAndBroadcast.The new transaction handling approach should include proper error handling and retries if necessary.
- postFn: () => signAndBroadcast({ address, messages, fee }), + postFn: async () => { + try { + return await signAndBroadcast({ address, messages, fee }); + } catch (error) { + console.error('Transaction failed:', error); + throw error; + } + },src/lib/app-fns/tx/submitProposal.tsx (1)
7-7
: Good architectural improvement with transaction abstraction.The replacement of direct client usage with
signAndBroadcast
improves modularity and maintainability of transaction handling.Also applies to: 23-23, 34-34, 41-41
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
pnpm-lock.yaml
is excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (78)
package.json
(1 hunks)src/lib/app-fns/tx/clearAdmin.tsx
(2 hunks)src/lib/app-fns/tx/execute.tsx
(3 hunks)src/lib/app-fns/tx/instantiate.tsx
(2 hunks)src/lib/app-fns/tx/migrate.tsx
(2 hunks)src/lib/app-fns/tx/move/executeModule.tsx
(3 hunks)src/lib/app-fns/tx/publish.tsx
(2 hunks)src/lib/app-fns/tx/resend.tsx
(4 hunks)src/lib/app-fns/tx/script.tsx
(2 hunks)src/lib/app-fns/tx/storeCode.tsx
(3 hunks)src/lib/app-fns/tx/submitProposal.tsx
(3 hunks)src/lib/app-fns/tx/updateAdmin.tsx
(3 hunks)src/lib/app-provider/hooks/index.ts
(1 hunks)src/lib/app-provider/hooks/useAddress.ts
(2 hunks)src/lib/app-provider/hooks/useConvertHexAddress.ts
(1 hunks)src/lib/app-provider/hooks/useCurrentChain.ts
(1 hunks)src/lib/app-provider/hooks/useDummyWallet.ts
(1 hunks)src/lib/app-provider/hooks/useExampleAddresses.ts
(2 hunks)src/lib/app-provider/hooks/useGetSigningClient.ts
(2 hunks)src/lib/app-provider/hooks/useLcdEndpoint.ts
(1 hunks)src/lib/app-provider/hooks/useRpcEndpoint.ts
(0 hunks)src/lib/app-provider/hooks/useSignAndBroadcast.ts
(1 hunks)src/lib/app-provider/hooks/useSimulateFee.ts
(1 hunks)src/lib/app-provider/queries/simulateFee.ts
(9 hunks)src/lib/app-provider/tx/clearAdmin.ts
(4 hunks)src/lib/app-provider/tx/execute.ts
(3 hunks)src/lib/app-provider/tx/instantiate.ts
(4 hunks)src/lib/app-provider/tx/migrate.ts
(4 hunks)src/lib/app-provider/tx/move/executeModule.ts
(4 hunks)src/lib/app-provider/tx/publish.tsx
(4 hunks)src/lib/app-provider/tx/resend.ts
(3 hunks)src/lib/app-provider/tx/script.tsx
(3 hunks)src/lib/app-provider/tx/storeCode.ts
(4 hunks)src/lib/app-provider/tx/submitProposal.ts
(5 hunks)src/lib/app-provider/tx/updateAdmin.ts
(4 hunks)src/lib/components/abi/args-form/field/ArgFieldWidget.tsx
(2 hunks)src/lib/components/button/InstantiateButton.tsx
(2 hunks)src/lib/components/button/RedoButton.tsx
(2 hunks)src/lib/components/button/ResendButton.tsx
(1 hunks)src/lib/components/modal/MoveCodeSnippet.tsx
(2 hunks)src/lib/components/modal/RedoModal.tsx
(1 hunks)src/lib/components/modal/WasmCodeSnippet.tsx
(2 hunks)src/lib/components/wallet-section/WalletConnect.tsx
(2 hunks)src/lib/components/wallet-section/index.tsx
(2 hunks)src/lib/components/wallet/index.ts
(0 hunks)src/lib/layout/Header.tsx
(1 hunks)src/lib/pages/account-details/components/tables/txs/full.tsx
(1 hunks)src/lib/pages/code-details/components/code-info/table/NoContracts.tsx
(1 hunks)src/lib/pages/contract-details/components/InstantiateInfo.tsx
(1 hunks)src/lib/pages/custom-network/manual/index.tsx
(2 hunks)src/lib/pages/custom-network/types.ts
(5 hunks)src/lib/pages/instantiate/InstantiateFormPage.tsx
(2 hunks)src/lib/pages/interact-contract/components/execute-area/schema-execute/ExecuteBox.tsx
(1 hunks)src/lib/pages/interact/component/form/ExecuteArea.tsx
(2 hunks)src/lib/pages/interact/hooks/useValidateModuleInput.ts
(3 hunks)src/lib/pages/migrate/components/MigrateContract.tsx
(2 hunks)src/lib/pages/past-txs/full.tsx
(1 hunks)src/lib/pages/past-txs/lite.tsx
(1 hunks)src/lib/pages/past-txs/sequencer.tsx
(1 hunks)src/lib/pages/proposal-details/components/NoVotingPeriodTally.tsx
(1 hunks)src/lib/pages/proposal/store-code/index.tsx
(1 hunks)src/lib/providers/cosmos-kit/index.tsx
(1 hunks)src/lib/providers/index.tsx
(2 hunks)src/lib/providers/initia-widget.tsx
(1 hunks)src/lib/services/block/index.ts
(2 hunks)src/lib/services/evm/index.ts
(1 hunks)src/lib/services/name/index.ts
(1 hunks)src/lib/services/nft-collection/index.ts
(3 hunks)src/lib/services/nft/index.ts
(2 hunks)src/lib/services/searchService.ts
(1 hunks)src/lib/services/tx/index.ts
(12 hunks)src/lib/services/validator/index.ts
(5 hunks)src/lib/types/chainConfig.ts
(4 hunks)src/lib/types/currency/token.ts
(1 hunks)src/lib/types/wallet.ts
(2 hunks)src/lib/utils/index.ts
(1 hunks)src/lib/utils/sleep.ts
(1 hunks)src/lib/utils/tx/createTxHash.ts
(1 hunks)
💤 Files with no reviewable changes (2)
- src/lib/components/wallet/index.ts
- src/lib/app-provider/hooks/useRpcEndpoint.ts
✅ Files skipped from review due to trivial changes (4)
- src/lib/utils/sleep.ts
- src/lib/layout/Header.tsx
- src/lib/services/validator/index.ts
- src/lib/services/tx/index.ts
🔇 Additional comments (102)
src/lib/utils/tx/createTxHash.ts (1)
5-5
: Verify sha256 input type requirements.The conversion to
Uint8Array
looks good and likely ensures better type safety withsha256
. Let's verify the input type requirements:✅ Verification successful
The Uint8Array conversion is correct and necessary
The sha256 function in the codebase explicitly requires Uint8Array input, and all other usages across the codebase consistently work with Uint8Array. The conversion from Buffer to Uint8Array ensures proper type safety and maintains consistency with the rest of the implementation.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify sha256 input type requirements in @cosmjs/crypto # Check the sha256 function signature and documentation rg -A 5 "export (function|const) sha256" --type ts # Look for other usages of sha256 in the codebase for consistency rg "sha256\(" --type tsLength of output: 1003
src/lib/app-provider/tx/submitProposal.ts (4)
5-5
: LGTM! Clean import of the new transaction handling hook.The addition of
useSignAndBroadcast
aligns well with the architectural changes for transaction handling abstraction.
24-24
: LGTM! Clean integration of the new transaction handling approach.The refactoring to use
signAndBroadcast
simplifies the transaction flow and reduces coupling with the signing client.Also applies to: 44-44, 52-52
66-67
: LGTM! Well-structured implementation of the store code proposal flow.The implementation:
- Properly handles all required parameters (address and chainName)
- Correctly integrates the new signAndBroadcast approach
- Maintains proper dependency tracking in the useCallback hook
Also applies to: 78-79, 83-83, 88-88, 96-96
Line range hint
1-98
: Verify consistent implementation across the codebase.Let's ensure this refactoring pattern is consistently applied across other transaction-related files.
✅ Verification successful
Implementation is consistent across transaction-related files ✅
The codebase demonstrates uniform patterns for:
- Error handling for address and fee validation
- Integration of signAndBroadcast hook
- Transaction function structure and organization
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check for consistent usage of signAndBroadcast and error handling patterns # across transaction-related files # Look for other transaction files echo "Checking for other transaction files..." fd -e ts -e tsx -p "tx/.+\.(ts|tsx)$" src/ # Check for consistent error handling patterns echo "Checking error handling patterns..." rg -A 2 "throw new Error\(" src/lib/app-provider/tx/ # Verify signAndBroadcast integration echo "Checking signAndBroadcast usage..." rg "useSignAndBroadcast|signAndBroadcast" src/lib/app-provider/tx/Length of output: 9270
src/lib/app-provider/tx/updateAdmin.ts (5)
5-5
: LGTM! Import changes align with the new transaction handling approach.The replacement of
useGetSigningClient
withuseSignAndBroadcast
is consistent with the architectural changes described in the PR objectives.
21-21
: LGTM! Hook implementation follows the new transaction pattern.The use of
signAndBroadcast
simplifies the transaction flow by combining signing and broadcasting into a single abstraction.
31-32
: LGTM! Improved error handling with more specific error message.The error message now includes the hook name
useUpdateAdminTx
, making it easier to debug issues in production.
51-51
: LGTM! Dependencies correctly updated for the new implementation.The useCallback dependency array properly includes
signAndBroadcast
to match the function's dependencies.
43-43
: Verify type compatibility with updateAdminTx function.The change from
client
tosignAndBroadcast
parameter looks good, but let's verify the type definitions.✅ Verification successful
Type compatibility verified successfully
The
signAndBroadcast
parameter is correctly typed in the function definition and properly passed in the implementation.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check if updateAdminTx function is properly typed for signAndBroadcast # Look for the function definition and its parameter types ast-grep --pattern 'export const updateAdminTx = ({ $$$, signAndBroadcast, $$$ }: { $$$, signAndBroadcast: $_, $$$ }) => $$$'Length of output: 127
Script:
#!/bin/bash # Search for updateAdminTx definition with context rg "updateAdminTx" -A 5 -B 2Length of output: 2987
src/lib/app-provider/tx/storeCode.ts (4)
5-5
: LGTM! Clean import refactoring.The replacement of
useGetSigningClient
withuseSignAndBroadcast
aligns well with the architectural changes to abstract transaction handling.
24-24
: LGTM! Clear error handling.The error handling is well-implemented with a descriptive message that includes the hook name for easier debugging.
Also applies to: 36-36
60-60
: LGTM! Correct dependency array.The dependency array properly includes all external values used in the callback, ensuring proper hook behavior.
24-24
: Verify consistent usage of signAndBroadcast across the codebase.Let's ensure this architectural change is consistently applied across other transaction handlers.
✅ Verification successful
✓ Consistent usage of signAndBroadcast verified
The architectural change has been consistently applied across all transaction handlers in the codebase, with proper encapsulation of the signing client functionality.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for any remaining instances of useGetSigningClient echo "Checking for remaining useGetSigningClient usage..." rg "useGetSigningClient" # Search for consistent adoption of useSignAndBroadcast echo "Checking for useSignAndBroadcast adoption..." rg "useSignAndBroadcast.*=.*useSignAndBroadcast\(\)"Length of output: 871
Script:
#!/bin/bash # Search for any usage of useSignAndBroadcast with more flexible pattern echo "Checking for all useSignAndBroadcast usages..." rg "useSignAndBroadcast" # Search for transaction handler files echo "Checking for transaction handler files..." fd "tx" --type fLength of output: 6581
src/lib/pages/proposal/store-code/index.tsx (1)
293-294
: Verify memory efficiency of Buffer to Uint8Array conversion.The change in how
wasmByteCode
is created might impact memory usage for large WASM files. Consider these alternatives:
- If
gzip
returns a Buffer, useBuffer.prototype.buffer
to get the underlying ArrayBuffer:-wasmByteCode: Uint8Array.from(await gzip(await wasmFile.arrayBuffer())), +wasmByteCode: new Uint8Array( + (await gzip(await wasmFile.arrayBuffer())).buffer +),
- If
gzip
returns a Uint8Array, no conversion is needed:-wasmByteCode: Uint8Array.from(await gzip(await wasmFile.arrayBuffer())), +wasmByteCode: await gzip(await wasmFile.arrayBuffer()),Let's verify the return type of the
gzip
function and measure the impact on memory usage:src/lib/app-provider/hooks/useCurrentChain.ts (4)
7-7
: ImportedzBechAddr20
Nice choice for type validation. Remember to also validate complex address constraints (e.g., length and prefix) in your address schema if needed.
10-10
: Custom logic foruseInitia
Ensure that logic returningtrue
/false
for theisInitia
hook is consistent with the user’s wallet usage, particularly in multi-wallet scenarios.
56-65
: Fallback to CosmosKit context
Looks good. Make sure thebech32Prefix
from CosmosKit matches your chain’s official prefix.
1-4
: Use of renamed import from "@cosmos-kit/core" and new import from "@initia/react-wallet-widget"
Good job on clearly distinguishing the CosmosKit chain context vs. the Initia wallet context. However, verify that obsolete references to the oldChainContext
type are updated throughout the code to avoid mismatches.Here is a quick script to confirm usage of the old
ChainContext
type is entirely removed:✅ Verification successful
ChainContext import and usage verified
All references to ChainContext are properly using the renamed CosmosKitChainContext import, with no obsolete references found in the codebase.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash rg 'ChainContext' -A 5Length of output: 1030
src/lib/app-provider/hooks/useSignAndBroadcast.ts (4)
1-6
: Imports for transaction signing and broadcasting
Every required dependency is imported. Confirm that the correct versions of @cosmjs libraries are being used to ensure compatibility.
7-13
: Usage ofuseCelatoneApp
context
No issues here. The context usage is consistent with the rest of the codebase.
70-73
:SignAndBroadcast
type
Good practice to differentiate your function signature. This helps maintain a consistent contract for various broadcast implementations.
74-105
:useSignAndBroadcast
hook
Centralized hooking for signing and broadcasting is a major improvement in maintainability. Great job.src/lib/app-provider/hooks/useLcdEndpoint.ts (1)
5-5
: Simplified return of the LCD endpoint
This change eliminates fallback logic. Confirm that removing any fallback doesn't break edge cases where chain wallets might provide overrides. If you plan to add dynamic endpoints in the future, consider reintroducing an optional fallback mechanism.src/lib/providers/initia-widget.tsx (2)
4-6
: LGTM! Clean provider implementation.The component follows React best practices with proper typing and minimal implementation.
1-1
: Verify @initia/react-wallet-widget version compatibility.Let's ensure we're using a stable version of the package.
✅ Verification successful
Version ^0.185.0 is appropriately specified for @initia/react-wallet-widget
The package is used consistently across multiple files and the version constraint (^0.185.0) allows for compatible updates while preventing breaking changes. Since it's a pre-1.0 version, monitor the package's stability and updates closely.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check for the latest stable version and recent releases curl -s "https://registry.npmjs.org/@initia/react-wallet-widget" | jq -r '.["dist-tags"].latest, .time | to_entries | .[] | select(.key|test("^[0-9]")) | [.key, .value] | @tsv' | sort -k2 -r | head -n 5Length of output: 259
Script:
#!/bin/bash # Check package.json for the dependency and registry configurations echo "=== Package.json Contents ===" cat package.json | jq '.dependencies["@initia/react-wallet-widget"], .resolutions["@initia/react-wallet-widget"]' echo -e "\n=== Checking for Registry Configurations ===" fd -H "\.npmrc$" fd -H "\.yarnrc$" echo -e "\n=== Similar Imports Usage ===" rg -l "@initia/react-wallet-widget"Length of output: 565
src/lib/types/wallet.ts (1)
20-20
: LGTM! Type enhancement for wallet connectivity.The addition of the onClick handler aligns with React event handling best practices and provides better type safety for button interactions.
src/lib/types/currency/token.ts (1)
8-9
: LGTM! Enhanced type safety with zod branding.Good improvement using zod's branded types for better type safety and validation.
Let's verify the migration of existing gas calculations:
✅ Verification successful
Gas type migration verified successfully
The migration to zod branded Gas type is clean with only one usage point in useFabricateFee that's already compatible with the new type definition. No breaking changes or migration issues found.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for existing gas type usage to ensure compatibility rg -l "Gas<" | xargs rg "Gas<|NominalType<\"gas\">" -A 2Length of output: 430
Script:
#!/bin/bash # Check implementation of useFabricateFee echo "=== useFabricateFee Implementation ===" cat src/lib/app-provider/hooks/useFabricateFee.ts echo -e "\n=== Gas Calculations ===" # Look for gas calculations or conversions rg -g '!*.test.*' -g '!*.spec.*' "gas.*as Gas|Gas.*as|\.gas\s*=" -C 2Length of output: 66940
src/lib/components/button/RedoButton.tsx (1)
15-15
: Verify consistent chainName usage across components.The property access change improves naming consistency, but we should verify the usage pattern across all components.
Also applies to: 25-25
✅ Verification successful
Property access pattern is consistent across the codebase
The chainName destructuring is properly implemented and follows a consistent pattern across all components. The only instance of
chain.chain_name
is in theuseCurrentChain
hook itself, which is the correct source of this property.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check for any remaining chain.chain_name usage that should be updated rg "chain\.chain_name" --type ts --type tsx # Verify consistent chainName destructuring pattern rg "const.*chainName.*useCurrentChain" --type ts --type tsxLength of output: 163
Script:
#!/bin/bash # Check for chain.chain_name usage with correct type flag rg "chain\.chain_name" -t typescript # Check chainName destructuring from useCurrentChain rg "const.*chainName.*useCurrentChain" -t typescript # Use ast-grep to find property access patterns ast-grep --pattern 'const { chainName } = useCurrentChain()' # Check all useCurrentChain hook usages rg "useCurrentChain" -t typescriptLength of output: 551
Script:
#!/bin/bash # Search without type flags for chain.chain_name rg "chain\.chain_name" # Search for useCurrentChain usage patterns rg "useCurrentChain" # Search for any chainName references rg "chainName"Length of output: 19927
src/lib/app-provider/hooks/index.ts (1)
22-23
: Verify the removal of useRpcEndpoint.The addition of
useSignAndBroadcast
anduseSimulateFee
aligns with the new transaction handling architecture. However, we should verify that the removal ofuseRpcEndpoint
doesn't impact existing functionality.✅ Verification successful
Removal of useRpcEndpoint is verified
The hook has been completely removed from the codebase with no remaining references, indicating a clean migration to the new transaction handling architecture.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for any remaining usage of useRpcEndpoint rg "useRpcEndpoint" --type ts --type tsxLength of output: 68
Script:
#!/bin/bash # Search for any remaining usage of useRpcEndpoint without type restrictions rg "useRpcEndpoint" # Search for files containing the old hook file fd "useRpcEndpoint" # Search for specific import patterns rg "import.*useRpcEndpoint" rg "from.*useRpcEndpoint"Length of output: 97
src/lib/app-provider/hooks/useConvertHexAddress.ts (1)
10-10
: LGTM! Clean refactor of bech32Prefix destructuring.The simplified destructuring improves code clarity while maintaining the same functionality.
src/lib/app-provider/hooks/useExampleAddresses.ts (1)
10-10
: LGTM! Clean improvements to the code.The changes improve code quality through:
- Consistent naming with
bech32Prefix
- Modern array initialization using
Uint8Array.from
- Properly updated dependency array in
useMemo
Also applies to: 15-16, 21-22, 34-34
src/lib/providers/index.tsx (2)
18-26
: LGTM! Clean provider hierarchy restructuring.The new provider hierarchy with CosmosKitProvider and InitiaWidgetProvider is well-structured and maintains a logical flow of context providers.
5-6
: Verify InitiaWidgetProvider implementation.Please ensure that the InitiaWidgetProvider is properly configured with the necessary wallet widget settings from
@initia/react-wallet-widget
.✅ Verification successful
Implementation of InitiaWidgetProvider is correct
The current implementation properly wraps the
WalletWidgetProvider
from@initia/react-wallet-widget
following React best practices. The provider is correctly implemented as a pass-through component without requiring additional configuration.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check InitiaWidgetProvider implementation cat src/lib/providers/initia-widget.tsxLength of output: 300
Script:
#!/bin/bash # Search for WalletWidgetProvider usage and configuration rg -l "WalletWidgetProvider" --type ts --type tsx # Look for any Initia-related configuration files fd -e ts -e tsx -e json "initia|wallet" -t fLength of output: 970
Script:
#!/bin/bash # Check theme configuration and hooks cat src/config/theme/initia.ts cat src/lib/app-provider/hooks/useInitia.ts # Search for any WalletWidgetProvider configuration examples in documentation fd README -e md | xargs rg -l "WalletWidgetProvider|@initia/react-wallet-widget"Length of output: 4810
src/lib/app-provider/tx/resend.ts (1)
5-5
: LGTM! Clean transition to the new transaction handling pattern.The changes effectively implement the new
signAndBroadcast
pattern:
- Import and hook usage are correctly updated
- Dependencies are properly maintained in useCallback
- Error handling is simplified while remaining robust
Also applies to: 18-18, 33-33, 41-41
src/lib/pages/code-details/components/code-info/table/NoContracts.tsx (1)
35-36
: Verify wallet connection edge cases.While checking
address
directly is cleaner, please verify the behavior in edge cases where a wallet might be connected but the address is not yet available (e.g., during wallet initialization).src/lib/app-provider/tx/script.tsx (1)
27-28
: Consider consistent error message format.The error message format is good, but we should ensure it's consistent across all transaction hooks.
✅ Verification successful
Error message format is consistent with codebase standards
The error message "No address provided (useDeployScriptTx)" follows the exact same pattern used across all transaction hooks in the codebase, where each error includes both the message and the specific hook name in parentheses.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check error message consistency across tx hooks rg "No address provided" --type ts --type tsxLength of output: 75
Script:
#!/bin/bash # Search for address-related error messages with context rg "address.*provided|provided.*address" -A 2 --type typescript --type-add 'typescript:*.{ts,tsx}' # Search for general error message patterns in transaction hooks rg "throw new Error\(" -A 2 --type typescript --type-add 'typescript:*.{ts,tsx}' ./src/lib/app-provider/tx/Length of output: 7261
src/lib/app-provider/tx/publish.tsx (1)
19-19
: LGTM! Consistent implementation with other transaction hooks.The changes maintain consistency with other transaction hooks:
- Error handling follows the established pattern
- Callback handling is properly typed
- Dependencies are correctly updated
Also applies to: 28-28, 32-32, 42-42
src/lib/utils/index.ts (1)
43-43
: Verify the sleep utility's usage across the codebase.The addition of the sleep utility suggests new asynchronous operations. Let's verify its usage to ensure it's not being used for critical timing-dependent operations.
✅ Verification successful
Sleep utility is properly implemented for transaction polling
The sleep utility is being used correctly in a transaction polling mechanism with appropriate timeout handling and fixed intervals. The implementation follows best practices for asynchronous operations.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check how the sleep utility is being used across the codebase rg -A 3 "sleep\(" --type ts --type tsxLength of output: 68
Script:
#!/bin/bash # Search for sleep function usage and imports rg -t ts "sleep\(" rg -t ts "import.*sleep" # Search for sleep-related patterns using ast-grep ast-grep --pattern 'await sleep($_)' ast-grep --pattern 'import { sleep } from $_'Length of output: 392
Script:
#!/bin/bash # Get context around the sleep usage and constant definition rg -t ts "POLL_INTERVAL_MS" -B 2 -A 2 cat src/lib/app-provider/hooks/useSignAndBroadcast.tsLength of output: 3871
src/lib/app-fns/tx/instantiate.tsx (1)
6-7
: LGTM! Type safety improvements.The changes enhance type safety by:
- Using specific
BechAddr20
type for addresses- Adding explicit
SignAndBroadcast
type for transaction handlingAlso applies to: 15-15, 19-19
src/lib/providers/cosmos-kit/index.tsx (1)
11-15
: LGTM! Improved component naming.The rename from
ChainProvider
toCosmosKitProvider
better reflects its purpose and implementation.src/lib/services/evm/index.ts (1)
48-48
: LGTM! Consistent naming convention applied.The renaming from
bech32_prefix
tobech32Prefix
aligns with JavaScript/TypeScript camelCase conventions and maintains consistency across the codebase.Also applies to: 54-54, 57-57
src/lib/app-provider/tx/migrate.ts (3)
5-5
: LGTM! Improved architecture for transaction handling.The migration to
useSignAndBroadcast
simplifies the transaction flow and the renamed hook better describes its purpose.Also applies to: 20-22
47-47
: LGTM! Clean parameter updates.The changes to use
address
andsignAndBroadcast
align with the new architecture, and the dependencies array is correctly updated.Also applies to: 50-50, 58-58
33-34
: Verify error handling in other transaction hooks.The error message is clear and specific. However, we should ensure consistent error handling across other transaction hooks.
✅ Verification successful
Error handling is consistent across all transaction hooks
All transaction hooks in the codebase follow the same pattern for address validation, throwing an error with a clear, hook-specific message in the format "No address provided ()".
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for similar error handling patterns in other transaction hooks rg -A 1 'throw new Error.*No address provided' 'src/lib/app-provider/tx/'Length of output: 2286
src/lib/app-provider/tx/move/executeModule.ts (3)
7-7
: LGTM! Consistent architectural pattern.The changes align with the new transaction handling architecture using
signAndBroadcast
.Also applies to: 24-24
37-37
: LGTM! Clear error message.The error message follows the same pattern as other transaction hooks, maintaining consistency.
55-55
: LGTM! Clean implementation.The parameter updates and dependency array changes are consistent with the new architecture.
Also applies to: 63-63
src/lib/components/wallet-section/WalletConnect.tsx (3)
12-12
: LGTM! Improved prop naming.The change from
onClickConnectBtn
toonClick
follows standard React naming conventions.Also applies to: 20-20
43-43
: LGTM! Consistent prop usage.The
Others
component correctly uses the renamedonClick
prop.
Line range hint
46-78
: Verify wallet widget integration.The component structure has been simplified, presumably relying on the Initia wallet widget. Let's verify the integration is complete.
✅ Verification successful
Wallet widget integration is properly implemented and complete
The component handles both widget and non-widget wallet providers appropriately, with proper state management and consistent user interaction patterns. The simplified structure maintains full functionality while adding widget support.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check for Initia wallet widget integration rg -l '@initia/react-wallet-widget' 'src/' # Check for any remaining old wallet connection patterns rg -l 'onClickConnectBtn' 'src/'Length of output: 153
Script:
#!/bin/bash # Check the implementation of initia-widget provider cat src/lib/providers/initia-widget.tsx # Find where WalletConnectComponent is imported/used rg -l "WalletConnectComponent" src/ # Look for WalletStatus enum usage rg "WalletStatus\." src/ -A 2Length of output: 1531
Script:
#!/bin/bash # Check wallet section index implementation cat src/lib/components/wallet-section/index.tsx # Look for wallet widget hook usage rg "from '@initia/react-wallet-widget'" src/ -A 3Length of output: 2180
src/lib/app-provider/tx/execute.ts (1)
Line range hint
52-53
: Enhance action extraction robustness.The current action extraction assumes the first key of an object message is the action. This could be unreliable if the message structure changes.
-const action = typeof msg === "string" ? msg : Object.keys(msg)[0]; +const action = typeof msg === "string" + ? msg + : Object.keys(msg)[0] ?? "execute"; // Provide fallbacksrc/lib/app-provider/hooks/useSimulateFee.ts (1)
12-16
: LGTM! Well-structured interface definition.The
SimulateFeeParams
interface is clean, well-typed, and provides good documentation of the expected parameters.src/lib/components/wallet-section/index.tsx (1)
29-49
: LGTM! Clean implementation of Initia widget integration.The conditional rendering for the Initia widget is well-structured and maintains consistency with the existing wallet UI patterns.
src/lib/components/button/ResendButton.tsx (1)
44-44
: LGTM! Type change aligns with the broader transaction handling refactor.The change from
Option<Gas<number>>
toOption<Gas>
is consistent with the codebase-wide standardization of gas handling.src/lib/services/name/index.ts (1)
47-47
: LGTM! Consistent with naming convention updates.The change from
bech32_prefix
tobech32Prefix
aligns with the standardization of camelCase naming conventions across the codebase.src/lib/app-fns/tx/updateAdmin.tsx (1)
20-22
: LGTM! Good abstraction of transaction signing.The replacement of direct client usage with
SignAndBroadcast
improves modularity and makes the interface more focused.src/lib/app-fns/tx/script.tsx (2)
20-22
: LGTM! Consistent with other transaction handlers.The interface changes align well with the new transaction handling pattern.
40-41
: Consider moving callback after transaction validation.Similar to updateAdmin.tsx, the success callback should be moved after all validations.
src/lib/app-provider/hooks/useGetSigningClient.ts (1)
8-8
: LGTM! Good use of context for configuration.The change to use
useCelatoneApp
for configuration is a good improvement.Also applies to: 40-43
src/lib/app-fns/tx/migrate.tsx (2)
19-22
: LGTM! Clean interface refactoring.The interface changes align well with the new transaction handling architecture, replacing the direct client dependency with a more abstract
signAndBroadcast
function.
28-31
: Verify transaction signing behavior across the application.The migration to
signAndBroadcast
looks good, but we should ensure consistent behavior across all transaction types.Also applies to: 38-38
✅ Verification successful
Transaction signing behavior is consistent across the application
All transaction files consistently use the
signAndBroadcast
function with uniform parameter structure (address, messages, fee). No legacy signing methods or inconsistencies were found.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify consistent usage of signAndBroadcast across tx files # Look for any remaining uses of SigningCosmWasmClient or direct client usage echo "Checking for remaining SigningCosmWasmClient usage..." rg "SigningCosmWasmClient" "src/lib/app-fns/tx" echo "Checking for direct client.signAndBroadcast calls..." rg "client\.signAndBroadcast" "src/lib/app-fns/tx"Length of output: 328
Script:
#!/bin/bash # Cast a wider net to find all transaction signing patterns echo "Checking all imports in tx files..." rg "^import.*from" "src/lib/app-fns/tx" -A 1 echo "Looking for signing-related patterns..." rg -i "sign|broadcast|transaction" "src/lib/app-fns/tx" -A 1 echo "Finding function calls related to signing..." ast-grep --pattern 'signAndBroadcast($_)' echo "Checking for any broadcast function calls..." ast-grep --pattern '$_.broadcast($_)'Length of output: 30729
src/lib/app-fns/tx/move/executeModule.tsx (1)
9-9
: LGTM! Consistent implementation of the new transaction pattern.The changes maintain consistency with the new architecture while preserving the existing error handling and transaction flow.
Also applies to: 21-21, 30-30, 37-37
src/lib/app-fns/tx/resend.tsx (1)
19-19
: LGTM! Clean implementation of the new transaction pattern.The resend transaction implementation correctly adopts the new
signAndBroadcast
pattern while maintaining proper error handling and user feedback.Also applies to: 28-28, 37-37
src/lib/components/abi/args-form/field/ArgFieldWidget.tsx (1)
65-65
: LGTM! Property access refactor looks good.The change from nested destructuring to direct property access improves code consistency and readability while maintaining the same functionality.
Also applies to: 79-79
src/lib/components/modal/RedoModal.tsx (1)
29-29
: LGTM! Property access refactor looks good.The simplified destructuring of
chainName
aligns with the codebase-wide refactoring pattern.src/lib/pages/past-txs/sequencer.tsx (1)
45-45
: LGTM! Property access refactor looks good.The simplified destructuring of
chainId
maintains the same functionality while improving code consistency. The useEffect dependency is correctly preserved.src/lib/app-fns/tx/storeCode.tsx (3)
5-5
: LGTM! Type imports look good.The change from
BechAddr
toBechAddr20
provides better type specificity for address handling.Also applies to: 10-11
Line range hint
122-122
: Address the TODO comment about type hack.The comment indicates a type hack that should be addressed to maintain type safety.
35-35
: Verify the impact of removing the client parameter.The architectural change from client-based to function-based transaction handling is significant. Please ensure:
- All transaction flows have been tested with the new approach
- Error handling remains consistent
- Transaction signing behavior is unchanged
Also applies to: 41-41
✅ Verification successful
The client parameter removal aligns with the codebase architecture
The verification confirms that:
- Error handling remains consistent through the centralized
catchTxError
pattern- Transaction signing follows a standardized flow using common utilities
- The change is part of a broader architectural pattern where client management is handled at a higher level
The architectural change is consistently implemented across all transaction types in the codebase.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for other files that might still be using the old client-based approach rg "SigningCosmWasmClient" --type tsLength of output: 1546
Script:
#!/bin/bash # Check for other transaction-related files and patterns echo "=== Transaction Files ===" fd "tx" --type f --extension tsx --extension ts echo -e "\n=== Function-based Pattern ===" rg "export (async )?function \w+Tx" --type ts echo -e "\n=== Store Code Usage ===" rg "storeCode" --type ts -A 3Length of output: 10104
Script:
#!/bin/bash # Check the implementation details echo "=== Store Code Implementation ===" ast-grep --pattern 'export const storeCodeTx = $_' -f src/lib/app-fns/tx/storeCode.tsx echo -e "\n=== Error Handling Pattern ===" rg "catchTxError" --type ts -A 2Length of output: 4609
src/lib/pages/past-txs/lite.tsx (1)
47-47
: LGTM! Clean destructuring syntax.The simplified destructuring of
chainId
directly fromuseCurrentChain
aligns with the codebase-wide standardization of hook usage patterns.src/lib/app-provider/hooks/useAddress.ts (1)
77-77
: LGTM! Consistent hook usage pattern.The simplified destructuring of
bech32Prefix
maintains consistent patterns across the codebase while preserving all validation functionality.Also applies to: 100-100
src/lib/app-fns/tx/submitProposal.tsx (1)
107-107
: Verify consistent usage of new transaction pattern.Ensure all transaction-related code has been migrated to use the new
signAndBroadcast
pattern.Also applies to: 119-119, 126-126
✅ Verification successful
Migration to new transaction pattern is complete ✅
All transaction submission code has been migrated to use the new
signAndBroadcast
pattern. The implementation is centralized in theuseSignAndBroadcast
hook, and all transaction files insrc/lib/app-fns/tx/
are using the new pattern consistently.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for any remaining direct client.signAndBroadcast usage rg "client\.signAndBroadcast" -l # Search for new pattern adoption rg "signAndBroadcast\(\{" -lLength of output: 485
Script:
#!/bin/bash # Check the implementation in useSignAndBroadcast.ts cat src/lib/app-provider/hooks/useSignAndBroadcast.ts # Find all potential transaction files that might need the pattern fd -e tsx -e ts -p "tx|transaction" --type fLength of output: 15309
src/lib/pages/custom-network/manual/index.tsx (1)
11-11
: LGTM! Consistent type renaming.The renaming from
zGasFeeDetailsForm
tozGasConfigFeeDetailsForm
improves naming clarity.Also applies to: 115-115
✅ Verification successful
Type migration successfully completed
The renaming from
zGasFeeDetailsForm
tozGasConfigFeeDetailsForm
has been consistently applied across the codebase.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify complete migration of gas-related type names rg "zGasFeeDetailsForm" -l # Check for consistent naming pattern rg "zGasConfig" -lLength of output: 158
src/lib/app-provider/queries/simulateFee.ts (4)
6-6
: LGTM! Clean dependency management.The changes improve code organization by:
- Using
useCelatoneApp
for RPC endpoint access- Consolidating simulation logic into a dedicated
useSimulateFee
hookAlso applies to: 8-8
17-17
: Type enhancement improves null safety.The change from
Gas<number> | undefined
toOption<Gas>
provides better type safety and aligns with the functional programming paradigm.
29-34
: Clean refactor of client management.The refactoring simplifies the code by:
- Removing redundant client management logic
- Using the new
useSimulateFee
hook for simulation
39-40
: Enhanced error messages improve debugging.The error messages now include the source hook name, making it easier to trace issues:
- "No address provided (useSimulateFeeQuery)"
- "No address provided (useSimulateFeeForStoreCode)"
- "No Wasm file provided (useSimulateFeeForStoreCode)"
- "No address provided (useSimulateFeeForProposalStoreCode)"
- "No Wasm file provided (useSimulateFeeForProposalStoreCode)"
Also applies to: 83-86, 158-165
src/lib/pages/past-txs/full.tsx (1)
30-30
: LGTM! Clean destructuring.The simplified destructuring of
chainId
fromuseCurrentChain
improves code readability.src/lib/types/chainConfig.ts (2)
88-89
: LGTM! Consistent naming for gas costs configuration.The rename from
zGasCosts
tozGasConfigCosts
improves clarity and maintains consistency with other config-related types.Also applies to: 99-99
184-187
: LGTM! Consistent naming for gas configuration.The rename from
zGas
tozGasConfig
aligns with the naming pattern of other configuration types in the codebase.Also applies to: 221-221
src/lib/pages/account-details/components/tables/txs/full.tsx (1)
60-60
: LGTM! Clean destructuring.The simplified destructuring of
chainId
fromuseCurrentChain
improves code readability.src/lib/pages/interact/component/form/ExecuteArea.tsx (2)
75-75
: LGTM: Improved fee simulation trigger condition.The change from checking
composedTxMsgs.length > 0
to usingenableExecute
is more robust as it ensures all prerequisites (type arguments, no ABI errors, and address presence) are met before enabling fee simulation.
134-136
: Good addition: Fee state cleanup on disconnect.Adding fee state reset when the user disconnects prevents stale fee information from being displayed.
src/lib/services/nft-collection/index.ts (1)
94-94
: LGTM: Consistent naming convention.The renaming from
bech32_prefix
tobech32Prefix
aligns with camelCase naming conventions used throughout the codebase.Also applies to: 105-105, 120-120
src/lib/services/nft/index.ts (1)
149-149
: LGTM: Consistent naming convention.The renaming from
prefix
tobech32Prefix
maintains consistency with the standardized naming conventions across the codebase.Also applies to: 161-161, 169-169
src/lib/components/modal/WasmCodeSnippet.tsx (1)
27-27
: LGTM: Simplified endpoint access.Consolidating endpoint access through chainConfig reduces the number of hooks and simplifies the code.
Also applies to: 62-62
src/lib/components/modal/MoveCodeSnippet.tsx (1)
24-24
: LGTM! Clean refactor of endpoint retrieval.The changes improve code organization by consolidating endpoint retrieval into the chainConfig object, reducing the number of hooks while maintaining the same functionality.
Also applies to: 68-68
src/lib/pages/migrate/components/MigrateContract.tsx (1)
14-14
: LGTM! Improved naming consistency.The hook rename from
useMigrateTx
touseMigrateContractTx
better reflects its purpose and aligns with the broader refactoring effort.Also applies to: 53-53
src/lib/services/searchService.ts (1)
97-97
: LGTM! Simplified destructuring and consistent naming.The change improves code clarity by directly accessing
bech32Prefix
and aligns with the consistent naming convention across the codebase.src/lib/pages/custom-network/types.ts (4)
12-13
: LGTM! Import statements updated for consistency.The imports have been updated to use the new gas configuration types (
zGasConfig
,zGasConfigCosts
), aligning with the broader refactoring of gas-related types.
Line range hint
137-151
: LGTM! Gas fee details schema definition updated.The schema definition has been updated to use the new gas configuration types, maintaining the same validation logic while improving naming consistency.
216-219
: LGTM! Gas fee details form validation updated.The form validation has been updated to use the new gas configuration types, maintaining the same validation logic.
330-330
: LGTM! Network form schema updated.The network form schema has been updated to use the new gas configuration types, maintaining consistency across the codebase.
src/lib/pages/instantiate/InstantiateFormPage.tsx (1)
19-19
: LGTM! Transaction hook renamed for clarity.The hook has been renamed from
useInstantiateTx
touseInstantiateContractTx
for better clarity and consistency with other transaction hooks.Also applies to: 88-88
src/lib/pages/proposal-details/components/NoVotingPeriodTally.tsx (1)
7-7
: LGTM! Simplified property destructuring.The destructuring has been simplified from nested
chain.chain_id
to directchainId
, improving code readability.src/lib/app-fns/tx/publish.tsx (2)
6-6
: LGTM! Transaction handling refactored to use SignAndBroadcast.The transaction handling has been refactored to use the new
SignAndBroadcast
type, improving modularity and consistency across the codebase.Also applies to: 25-27
34-36
: LGTM! Transaction posting logic updated.The transaction posting logic has been updated to use the new
signAndBroadcast
function, maintaining the same functionality while improving code organization.Also applies to: 41-41
src/lib/components/button/InstantiateButton.tsx (1)
58-58
: LGTM! Simplified wallet connection check.The changes improve code clarity by using address truthiness directly instead of a separate isWalletConnected flag.
Also applies to: 77-77, 85-85
src/lib/services/block/index.ts (1)
56-56
: LGTM! Standardized naming convention.The renaming of
bech32_prefix
tobech32Prefix
improves code consistency without affecting functionality.Also applies to: 71-71, 75-78
package.json (1)
77-77
: Verify the latest stable version of @initia/react-wallet-widget.The package version uses a caret range (
^0.185.0
), which allows minor version updates. Let's ensure this is the latest stable version.src/lib/pages/contract-details/components/InstantiateInfo.tsx (1)
119-119
: LGTM! Simplified hook usage.The direct destructuring of
chainId
fromuseCurrentChain
improves code readability.
src/lib/pages/interact-contract/components/execute-area/schema-execute/ExecuteBox.tsx
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (4)
src/lib/app-provider/queries/simulateFee.ts (2)
94-96
: Consider extracting common WASM byte code handling logic.The WASM byte code processing logic is duplicated. Consider extracting it into a utility function:
const getWasmByteCode = async (wasmFile: File) => Uint8Array.from(await gzip(await wasmFile.arrayBuffer()));This would reduce duplication and make the code more maintainable.
Also applies to: 176-176
Line range hint
194-206
: Consider using a type for query key components.The query key array contains multiple elements of different types. Consider creating a type to document the expected structure and order of these query key components.
type StoreCodeProposalQueryKey = [ typeof CELATONE_QUERY_KEYS.SIMULATE_FEE_STORE_CODE_PROPOSAL, string, // chainId string, // runAs Coin, // initialDeposit boolean, // unpinCode string, // builder string, // source string, // codeHash File | null, // wasmFile AccessType, // permission BechAddr[], // addresses boolean, // enabled ];src/lib/components/table/AccordionTx.tsx (1)
33-35
: Consider memoizing RenderButton componentSince RenderButton is recreated on each render and used within a SlideFade animation component, consider memoizing it with useCallback to optimize performance.
-const RenderButton = ({ message, txHash, msgIndex }: RenderButtonProps) => { +const RenderButton = useCallback(({ message, txHash, msgIndex }: RenderButtonProps) => { if ( extractMsgType(message.type) === "MsgExecuteContract" || extractMsgType(message.type) === "MsgInstantiateContract" ) return <RedoButton message={message} />; if (extractMsgType(message.type) === "MsgSend") return ( <ResendButton messages={[message]} txHash={txHash} msgIndex={msgIndex} /> ); return null; -}; +}, []);src/lib/components/button/ResendButton.tsx (1)
57-58
: Consider adding error details to onTxFailed callbackThe error handling could be improved by passing error details to the onTxFailed callback.
-onTxFailed: () => setIsProcessing(false), +onTxFailed: (error: Error) => { + console.error('Transaction failed:', error); + setIsProcessing(false); +},
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/lib/app-provider/queries/simulateFee.ts
(9 hunks)src/lib/components/button/ResendButton.tsx
(4 hunks)src/lib/components/table/AccordionTx.tsx
(2 hunks)src/lib/components/table/transactions/FurtherActionButton.tsx
(1 hunks)src/lib/components/table/transactions/TransactionsTableRow.tsx
(1 hunks)
🔇 Additional comments (10)
src/lib/app-provider/queries/simulateFee.ts (5)
6-6
: Improved type safety and architectural organization.Good improvements in the codebase:
- The change from
Gas<number> | undefined
toOption<Gas>
makes the optional nature of the gas value more explicit- The introduction of centralized hooks (
useCelatoneApp
,useSimulateFee
, etc.) improves code organization and reusabilityAlso applies to: 8-8, 18-18, 70-70, 136-136
31-36
: Good use of centralized hooks and configuration.The refactoring to use
useCelatoneApp
and other centralized hooks improves maintainability and consistency.
161-168
: Good error handling with context.The error messages now include the context (hook name) which will make debugging easier.
Line range hint
1-215
: Overall good refactoring with improved maintainability.The changes demonstrate good practices:
- Consistent error handling
- Better type safety
- Centralized configuration and hooks
- More maintainable query structure
The code is ready to be merged, with optional improvements suggested above.
38-43
: Verify fallback behavior for dummy address.Using
dummyAddress
as a fallback whenaddress
is not available might mask potential issues. Consider if this is the intended behavior or if we should fail fast when a real address is required.✅ Verification successful
Fallback behavior for dummy address is correctly implemented
The usage of
dummyAddress
as a fallback is intentional and consistent with the codebase's simulation patterns. The code properly validates address availability and throws an error when neither a real nor dummy address is available.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for other instances of dummyAddress usage to verify consistent behavior rg "dummyAddress" --type tsLength of output: 729
src/lib/components/table/transactions/FurtherActionButton.tsx (1)
40-42
: LGTM! Clean addition of txHash propThe addition of the txHash prop to ResendButton is well-integrated and maintains type safety.
src/lib/components/table/AccordionTx.tsx (1)
13-18
: Well-structured interface definitionClean and clear interface definition with proper typing for the new props.
src/lib/components/table/transactions/TransactionsTableRow.tsx (1)
120-121
: LGTM! Proper prop passingClean addition of txHash and msgIndex props, maintaining type safety and component hierarchy.
src/lib/components/button/ResendButton.tsx (2)
67-69
: Good use of extraQueryKey for cache optimizationThe addition of txHash and msgIndex to extraQueryKey will help in properly caching query results for different transactions.
50-61
: Verify Gas type compatibilityThe type change from
Gas<number>
toGas
might affect type safety. Please ensure this change is compatible with the rest of the codebase.✅ Verification successful
Type change from
Gas<number>
toGas
is safe ✅The change is safe as
Gas
is defined with a default type parameter<T = number>
, makingGas
equivalent toGas<number>
when used without explicit type arguments.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for other usages of Gas type to verify compatibility rg "Gas<number>" -A 2 rg "type Gas =" -A 2Length of output: 46
Script:
#!/bin/bash # Search for Gas type definitions and imports with broader patterns echo "=== Searching for Gas type definitions ===" rg "type.*Gas" -A 2 echo -e "\n=== Searching for Gas imports ===" rg "import.*\{.*Gas.*\}" -A 1 echo -e "\n=== Searching for Gas type usage ===" rg ": Gas(\s|[<>]|$)" -A 2Length of output: 5703
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (3)
src/lib/app-provider/queries/simulateFee.ts (3)
6-8
: LGTM! Consider adding JSDoc comments.The type changes and new imports look good. The shift to
Option<Gas>
and the addition ofextraQueryKey
improve type safety and flexibility.Consider adding JSDoc comments to document the purpose of
extraQueryKey
and how it should be used.Also applies to: 17-18
Line range hint
82-110
: Consider memoizing the message composition function.The implementation looks good, but the message composition function could benefit from memoization to prevent unnecessary recomputations of the gzipped wasm byte code.
Consider this optimization:
+ const memoizedSubmitStoreCodeMsg = useMemo( + async () => { return composeStoreCodeMsg({ sender: address, wasmByteCode: await gzip(new Uint8Array(await wasmFile.arrayBuffer())), permission, addresses, }); + }, + [address, wasmFile, permission, addresses] + );
Line range hint
155-205
: Consider breaking down the complex proposal message composition.While the implementation is functionally correct, the hook handles many parameters and has a large queryKey array. Consider:
- Breaking down the message composition into smaller, focused functions
- Creating a dedicated type for the queryKey parameters
Example refactor:
type ProposalQueryKey = { chainId: string; runAs: BechAddr; initialDeposit: Coin; // ... other fields }; const getQueryKey = (params: ProposalQueryKey) => [ CELATONE_QUERY_KEYS.SIMULATE_FEE_STORE_CODE_PROPOSAL, params.chainId, params.runAs, // ... other fields ];
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/lib/app-provider/queries/simulateFee.ts
(10 hunks)src/lib/app-provider/tx/storeCode.ts
(4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/lib/app-provider/tx/storeCode.ts
🔇 Additional comments (1)
src/lib/app-provider/queries/simulateFee.ts (1)
31-55
: LGTM! Verify error handling in integration tests.The refactoring improves the code by:
- Removing direct client dependency
- Adding more specific error messages
- Simplifying the simulation function
Please ensure that error scenarios are covered in integration tests, particularly for:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🔭 Outside diff range comments (1)
src/lib/app-provider/hooks/useDummy.ts (1)
Security Risk: Exposed Dummy Wallet in Production Build
The dummy wallet implementation has several security concerns:
- The mnemonic is exposed client-side via NEXT_PUBLIC_ environment variable
- No explicit development/production environment controls
- Could potentially be misused in production builds
Recommendations:
- Move fee simulation to server-side API endpoints
- Restrict dummy wallet usage to development/testing environments
- Remove NEXT_PUBLIC_ prefix and handle simulations server-side
- Add explicit environment checks (NODE_ENV === 'development')
🔗 Analysis chain
Line range hint
12-35
: Consider security implications of dummy wallet usage.The dummy wallet functionality might pose security risks if used in production. Ensure:
- This is only used in development/testing environments
- The dummy mnemonic is properly secured
Run this check to ensure dummy wallet usage is properly controlled:
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check for potential production usage of dummy wallet rg -l "DUMMY_MNEMONIC|useDummyWallet" "src/**/*.{ts,tsx}" | \ rg -v "test|spec|mock|stories|cypress|e2e|__tests__"Length of output: 172
Script:
#!/bin/bash # Check for DUMMY_MNEMONIC definition and environment controls echo "=== DUMMY_MNEMONIC definitions and usage ===" rg "DUMMY_MNEMONIC" --type ts --type tsx echo -e "\n=== Environment-related configurations ===" rg "process\.env|NODE_ENV" --type ts --type tsx -C 2 echo -e "\n=== useDummyWallet usage ===" rg "useDummyWallet" --type ts --type tsxLength of output: 493
Script:
#!/bin/bash # Search for dummy wallet related code and configurations echo "=== DUMMY_MNEMONIC definitions and usage ===" rg "DUMMY_MNEMONIC" -g "*.{ts,tsx}" -C 3 echo -e "\n=== Environment and configuration files ===" fd -e ts -e tsx -e json -e js "config|env" --exec rg -l "DUMMY|NODE_ENV|process\.env" echo -e "\n=== useDummyWallet usage ===" rg "useDummyWallet" -g "*.{ts,tsx}" -C 2 echo -e "\n=== Test-related imports and configurations ===" rg "(import|export).*Dummy" -g "*.{ts,tsx}" -C 1Length of output: 5539
🧹 Nitpick comments (13)
src/lib/services/tx/simulateFee.ts (2)
Line range hint
88-103
: Consider adding input validation.While the error handling is good, consider adding validation for the wasmFile size and format before attempting to process it.
const simulateFn = async () => { if (!address) throw new Error("No address provided (useSimulateFeeForStoreCode)"); if (!wasmFile) throw new Error("No Wasm file provided (useSimulateFeeForStoreCode)"); + if (wasmFile.size > 10 * 1024 * 1024) // 10MB limit + throw new Error("Wasm file size exceeds limit"); + if (!wasmFile.name.endsWith('.wasm')) + throw new Error("Invalid file format. Expected .wasm file"); const submitStoreCodeMsg = async () => {
Line range hint
161-190
: Consider implementing retry strategy for large files.For proposal store code operations that might involve large files, consider implementing a custom retry strategy.
const simulateFn = async () => { if (!address) throw new Error( "No address provided (useSimulateFeeForProposalStoreCode)" ); if (!wasmFile) throw new Error( "No Wasm file provided (useSimulateFeeForProposalStoreCode)" ); + + const retryWithBackoff = async (fn: () => Promise<any>, maxRetries = 3) => { + for (let i = 0; i < maxRetries; i++) { + try { + return await fn(); + } catch (error) { + if (i === maxRetries - 1) throw error; + await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000)); + } + } + }; const submitStoreCodeProposalMsg = async () => { return composeStoreCodeProposalMsg({src/lib/pages/proposal/store-code/index.tsx (1)
59-59
: LGTM! Specialized hook improves transaction handling.The use of a dedicated
useSimulateFeeForProposalStoreCode
hook demonstrates good architectural design by providing specialized functionality for different transaction types.Consider applying this pattern of specialized hooks for other transaction types to maintain consistency and improve code maintainability.
src/lib/app-provider/hooks/useSimulateFee.ts (2)
29-38
: Add comprehensive error handling for all async operations.While the dummy client initialization error is handled, consider adding error handling for the
simulate
call and providing more descriptive error messages.if (isDummyUser) { const dummyClient = await getDummyClient(); if (!dummyClient) { throw new Error("Dummy client is not initialized (useSimulateFee)"); } // Simulate fee using the dummy client - return dummyClient - .simulate(address, messages, undefined) - .then(zGas(z.number()).parse); + try { + const result = await dummyClient.simulate(address, messages, undefined); + return zGas(z.number()).parse(result); + } catch (error) { + throw new Error(`Failed to simulate fee with dummy client: ${error.message}`); + } }
18-60
: Well-implemented hook with good practices!The implementation demonstrates several good practices:
- Clean separation of concerns for different wallet types
- Proper use of useCallback with correct dependencies
- Type safety with zod validation
- Clear code organization and comments
Consider applying the same error handling pattern to the Initia widget and CosmosKit cases as suggested above.
src/lib/hooks/useExecuteCmds.ts (5)
3-4
: LGTM! Good architectural improvement.Moving transaction-related functionality to a dedicated services directory improves separation of concerns and code organization.
Line range hint
31-33
: Consider extracting regex patterns to constants.The Sylvia framework regex pattern is a magic string that could be moved to a constant for better maintainability and reusability.
+const SYLVIA_COMMANDS_REGEX = /Messages supported by this contract: (.*?): execute wasm contract failed/; + // Check if Sylvia framework -const sylviaRegex = - /Messages supported by this contract: (.*?): execute wasm contract failed/; -const contentMatch = e.message?.match(sylviaRegex); +const contentMatch = e.message?.match(SYLVIA_COMMANDS_REGEX);
Line range hint
18-29
: Consider adding type safety for simulation messages.The simulation message construction could benefit from stronger typing to prevent potential runtime errors.
+type SimulationMessage = { + sender: string; + contract: string; + msg: Buffer; + funds: never[]; +}; + const { isFetching } = useSimulateFeeQuery({ isDummyUser: true, enabled: !!contractAddress && !!dummyAddress, messages: dummyAddress ? [ composeMsg(MsgType.EXECUTE, { sender: dummyAddress, contract: contractAddress, msg: Buffer.from('{"": {}}'), funds: [], - }), + } as SimulationMessage), ] : [],
Line range hint
8-50
: Add documentation explaining the command discovery logic.The current implementation uses error message parsing for command discovery, which is non-obvious. Consider adding JSDoc comments explaining this approach and its limitations.
+/** + * Hook for discovering available execute commands in a smart contract. + * + * @remarks + * This hook uses error message parsing from simulation attempts to discover + * available commands. It supports two formats: + * 1. Sylvia framework error messages + * 2. Generic error parsing for type errors + * + * @param contractAddress - The address of the contract to query + * @returns Object containing loading state and discovered commands + */ export const useExecuteCmds = (contractAddress: BechAddr32) => {
Line range hint
8-50
: Consider a more robust approach for command discovery.The current implementation relies on parsing error messages to discover available commands, which is fragile and could break if error message formats change. Consider implementing one of these more robust approaches:
- Use contract metadata or schema for command discovery
- Implement dedicated API endpoints for querying available commands
- Cache discovered commands to reduce simulation attempts
Would you like me to help design a more robust solution using one of these approaches?
src/lib/components/button/ResendButton.tsx (1)
34-38
: Consider adding component documentation.The component would benefit from JSDoc documentation explaining its purpose, usage, and the significance of each prop, especially since it handles critical transaction resending functionality.
+/** + * ResendButton allows users to retry a failed transaction with updated gas estimates. + * @param messages - Array of messages to be included in the transaction + * @param txHash - Hash of the original transaction + * @param msgIndex - Optional index of the specific message to resend (defaults to 0) + */ export const ResendButton = ({ messages, txHash, msgIndex = 0, }: ResendButtonProps) => {src/lib/app-provider/hooks/useDummy.ts (2)
Line range hint
12-35
: Add error handling and loading state management.The wallet initialization could fail, but there's no error handling in place. Consider:
- Adding error state management
- Including a loading state
- Adding a cleanup function in useEffect
export const useDummyWallet = () => { const { bech32Prefix } = useCurrentChain(); const [dummyWallet, setDummyWallet] = useState<DirectSecp256k1HdWallet>(); const [dummyAddress, setDummyAddress] = useState<BechAddr20>(); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState<Error>(); useEffect(() => { + let mounted = true; + setError(undefined); + setIsLoading(true); (async () => { if (DUMMY_MNEMONIC) { - const wallet = await DirectSecp256k1HdWallet.fromMnemonic( - DUMMY_MNEMONIC, - { - prefix: bech32Prefix, - } - ); + try { + const wallet = await DirectSecp256k1HdWallet.fromMnemonic( + DUMMY_MNEMONIC, + { + prefix: bech32Prefix, + } + ); + if (!mounted) return; + setDummyWallet(wallet); + const { address } = (await wallet.getAccounts())[0]; + setDummyAddress(address as BechAddr20); + } catch (err) { + if (!mounted) return; + setError(err instanceof Error ? err : new Error('Failed to initialize wallet')); + } + } + })().finally(() => { + if (mounted) setIsLoading(false); + }); - setDummyWallet(wallet); - const { address } = (await wallet.getAccounts())[0]; - setDummyAddress(address as BechAddr20); - } - })(); + return () => { + mounted = false; + }; }, [bech32Prefix]); - return { dummyWallet, dummyAddress }; + return { dummyWallet, dummyAddress, isLoading, error }; };
38-53
: Consider enhancing client connection robustness.The client connection implementation could benefit from additional error handling and connection management:
export const useGetDummyClient = () => { const { dummyWallet } = useDummyWallet(); const { chainConfig: { rpc: rpcEndpoint }, } = useCelatoneApp(); + const [isConnecting, setIsConnecting] = useState(false); + const CONNECTION_TIMEOUT = 10000; // 10 seconds return useCallback(async () => { if (!dummyWallet) throw new Error("No dummy wallet provided"); + setIsConnecting(true); + try { + const timeoutPromise = new Promise((_, reject) => + setTimeout(() => reject(new Error('Connection timeout')), CONNECTION_TIMEOUT) + ); + const clientPromise = SigningCosmWasmClient.connectWithSigner( + rpcEndpoint, + dummyWallet, + getCustomedSigningCosmwasm() + ); + return await Promise.race([clientPromise, timeoutPromise]); + } catch (error) { + throw error instanceof Error + ? error + : new Error('Failed to connect to client'); + } finally { + setIsConnecting(false); + } - return SigningCosmWasmClient.connectWithSigner( - rpcEndpoint, - dummyWallet, - getCustomedSigningCosmwasm() - ); }, [dummyWallet, rpcEndpoint]); };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (20)
src/lib/app-provider/hooks/index.ts
(2 hunks)src/lib/app-provider/hooks/useDummy.ts
(2 hunks)src/lib/app-provider/hooks/useSimulateFee.ts
(1 hunks)src/lib/app-provider/index.ts
(0 hunks)src/lib/app-provider/queries/index.ts
(0 hunks)src/lib/components/button/ResendButton.tsx
(4 hunks)src/lib/hooks/useExecuteCmds.ts
(1 hunks)src/lib/hooks/useUploadCode.ts
(1 hunks)src/lib/pages/admin/index.tsx
(1 hunks)src/lib/pages/deploy-script/index.tsx
(2 hunks)src/lib/pages/instantiate/InstantiateFormPage.tsx
(3 hunks)src/lib/pages/interact-contract/components/execute-area/JsonExecute.tsx
(1 hunks)src/lib/pages/interact-contract/components/execute-area/schema-execute/ExecuteBox.tsx
(2 hunks)src/lib/pages/interact/component/form/ExecuteArea.tsx
(3 hunks)src/lib/pages/migrate/components/MigrateContract.tsx
(3 hunks)src/lib/pages/proposal/store-code/index.tsx
(1 hunks)src/lib/pages/proposal/whitelist/index.tsx
(1 hunks)src/lib/pages/publish-module/publish.tsx
(1 hunks)src/lib/services/tx/index.ts
(13 hunks)src/lib/services/tx/simulateFee.ts
(10 hunks)
💤 Files with no reviewable changes (2)
- src/lib/app-provider/index.ts
- src/lib/app-provider/queries/index.ts
🚧 Files skipped from review as they are similar to previous changes (6)
- src/lib/pages/instantiate/InstantiateFormPage.tsx
- src/lib/pages/interact/component/form/ExecuteArea.tsx
- src/lib/app-provider/hooks/index.ts
- src/lib/pages/interact-contract/components/execute-area/schema-execute/ExecuteBox.tsx
- src/lib/services/tx/index.ts
- src/lib/pages/migrate/components/MigrateContract.tsx
🔇 Additional comments (15)
src/lib/hooks/useUploadCode.ts (1)
15-15
: LGTM! Good architectural organization.The relocation of
useSimulateFeeForStoreCode
tolib/services/tx
improves code organization by centralizing transaction-related services.src/lib/services/tx/simulateFee.ts (3)
6-12
: LGTM! Clean dependency organization.The imports have been reorganized to use the new app provider structure, improving code organization and maintainability.
21-22
: Type enhancement for better flexibility.The addition of
extraQueryKey
and the change toOption<Gas>
type improves type safety and query customization capabilities.
35-46
: Improved error handling and user feedback.The error message now provides better context by specifying the hook name in the error message. The use of
simulateFee
hook centralizes the simulation logic.src/lib/pages/deploy-script/index.tsx (1)
Line range hint
7-16
: LGTM! Consistent architectural changes.The relocation of
useSimulateFeeQuery
tolib/services/tx
maintains consistency with the architectural improvements across the codebase.src/lib/pages/admin/index.tsx (1)
28-28
: LGTM! Consistent architectural changes.The relocation of
useSimulateFeeQuery
tolib/services/tx
maintains consistency with the architectural improvements across the codebase.src/lib/pages/interact-contract/components/execute-area/JsonExecute.tsx (1)
31-31
: LGTM! Verify the hook's functionality after relocation.The import change aligns with the architectural decision to centralize transaction-related services. This improves code organization by separating concerns.
Run the following script to verify consistent usage across the codebase:
✅ Verification successful
Import migration successfully verified
All usages of
useSimulateFeeQuery
consistently import fromlib/services/tx
with no remaining references to the old location.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify that all imports of useSimulateFeeQuery are from the new location # Test: Check for any remaining imports from the old location rg "useSimulateFeeQuery.*lib/app-provider" # Test: Verify consistent usage of the new import path rg "useSimulateFeeQuery.*lib/services/tx"Length of output: 1235
src/lib/pages/publish-module/publish.tsx (1)
23-23
: LGTM! Import change aligns with architectural updates.The relocation of
useSimulateFeeQuery
tolib/services/tx
maintains consistency with the codebase-wide refactoring of transaction-related services.src/lib/pages/proposal/whitelist/index.tsx (1)
46-46
: LGTM! Import update maintains architectural consistency.The relocation of
useSimulateFeeQuery
to the services directory aligns with the codebase's architectural improvements.src/lib/app-provider/hooks/useSimulateFee.ts (1)
1-16
: Well-structured type definitions and imports!The code demonstrates good type safety with clear interface definitions and appropriate use of custom types for blockchain addresses.
src/lib/hooks/useExecuteCmds.ts (1)
Line range hint
31-47
: Add error handling for malformed error messages.The current implementation assumes error messages will always match expected patterns. Consider adding fallback handling for unexpected formats.
Consider adding robust error handling:
onError: (e) => { const executeCmds: string[] = []; + if (!e.message) { + setExecCmds([["", "{}"]]); + return; + } // Check if Sylvia framework const sylviaRegex =src/lib/components/button/ResendButton.tsx (3)
62-66
: Well-implemented query cache management.Good addition of
extraQueryKey
to properly cache simulation results per transaction and message. This prevents unnecessary simulations for the same transaction.
13-16
: Verify the integration of new props with parent components.The interface has been updated with new required prop
txHash
. Ensure all parent components are updated to provide this prop.✅ Verification successful
Props integration verified successfully
All parent components correctly provide the required
txHash
prop and handle the optionalmsgIndex
prop appropriately.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Find all usage of ResendButton to verify prop passing rg -l "ResendButton" | xargs rg "<ResendButton" -A 5Length of output: 1012
47-55
: Review the Gas type change and verify error handling.The type change from
Option<Gas<number>>
toOption<Gas>
might affect other components. Additionally, the error handling has been improved with explicit success and failure callbacks.✅ Verification successful
Type change is safe and error handling is properly implemented.
The change from
Option<Gas<number>>
toOption<Gas>
is not breaking sinceGas
type defaults toGas<number>
. The error handling implementation with symmetric success and failure callbacks is correct.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Find all usages of Gas type to verify compatibility rg "Gas[<]number[>]" --type typescriptLength of output: 75
Script:
#!/bin/bash # Search for Gas type usage with explicit file extensions rg "Gas" --type-add 'ts:*.{ts,tsx}' --type ts -A 2 # Also search for type declarations ast-grep --pattern 'type Gas = $_'Length of output: 68896
src/lib/app-provider/hooks/useDummy.ts (1)
1-9
: LGTM! Well-organized imports.The imports are properly organized and all are being utilized in the implementation.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (2)
src/lib/components/wallet-section/index.tsx (2)
31-51
: Consider adding error boundaries for widget rendering.The Initia widget implementation looks good with proper conditional rendering and fallbacks. However, consider wrapping the widget-specific code in an error boundary to gracefully handle any widget-specific failures.
Example implementation:
import { Component, ErrorInfo, ReactNode } from 'react'; class WalletWidgetErrorBoundary extends Component< { children: ReactNode }, { hasError: boolean } > { state = { hasError: false }; static getDerivedStateFromError() { return { hasError: true }; } componentDidError(error: Error, errorInfo: ErrorInfo) { console.error('Wallet Widget Error:', error, errorInfo); } render() { if (this.state.hasError) { return <Others buttonText="Wallet Error" onClick={onClickConnect} />; } return this.props.children; } }
56-56
: Consider enhancing loading state feedback.The implementation looks good with consistent button usage across states. Consider adding a loading text or progress indicator to improve user feedback during the connecting state.
- connecting={<ConnectWalletButton isLoading />} + connecting={<ConnectWalletButton isLoading buttonText="Connecting..." />}Also applies to: 65-65
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/lib/components/wallet-section/index.tsx
(2 hunks)
🔇 Additional comments (3)
src/lib/components/wallet-section/index.tsx (3)
Line range hint
1-80
: Overall implementation looks solid!The wallet section refactor successfully:
- Integrates the Initia wallet widget
- Maintains consistent UI patterns
- Handles all wallet states appropriately
- Uses proper type safety throughout
The code is well-structured and maintainable.
16-16
: Verify chain context API changes.The change from
openView
toview
suggests an API change in the chain context. The implementation looks correct, but we should verify the chain context API.Let's check the chain context implementation:
Also applies to: 27-28
✅ Verification successful
API change from
openView
toview
is correctly implementedThe chain context implementation in
useCurrentChain
hook properly supports both wallet providers with the newview
property. The change is consistent and well-implemented.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check the chain context implementation for the view method ast-grep --pattern 'export function useCurrentChain() { $$$ return { $$$ view: $_, $$$ } }'Length of output: 111
Script:
#!/bin/bash # Find files containing useCurrentChain rg "useCurrentChain" -l # Look for context definitions with either openView or view rg "(openView|view).*=" -A 5Length of output: 66786
6-6
: LGTM! Verify the hook implementation.The integration of the Initia username hook is clean and follows React conventions.
Let's verify the hook implementation:
Also applies to: 17-17
✅ Verification successful
Hook implementation verified and approved
The
useInitiaUsernameByAddress
hook is well-implemented with proper:
- Error handling and type safety
- React Query integration
- Conditional execution controls
- Address validation and formatting
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check the hook implementation and its error handling ast-grep --pattern 'export function useInitiaUsernameByAddress($_) { $$$ }'Length of output: 79
Script:
#!/bin/bash # Search for the hook implementation using ripgrep rg "useInitiaUsernameByAddress" -A 5 # Find username-related files in services directory fd username "src/lib/services"Length of output: 3606
Script:
#!/bin/bash # Check the implementation of getInitiaUsernameByAddress rg "getInitiaUsernameByAddress" -A 5 # Check the full username service file cat src/lib/services/username/index.tsLength of output: 2805
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🔭 Outside diff range comments (1)
src/lib/services/tx/simulateFee.ts (1)
Line range hint
161-190
: Add validation for codeHash format.The codeHash is converted from hex without validation, which could lead to runtime errors if the format is invalid.
Consider adding validation:
+ const isValidHex = (hash: string) => /^[0-9a-fA-F]+$/.test(hash); + const simulateFn = async () => { if (!address) throw new Error( "No address provided (useSimulateFeeForProposalStoreCode)" ); if (!wasmFile) throw new Error( "No Wasm file provided (useSimulateFeeForProposalStoreCode)" ); + if (!isValidHex(codeHash)) + throw new Error( + "Invalid codeHash format. Expected hexadecimal string" + );
🧹 Nitpick comments (2)
src/lib/services/tx/simulateFee.ts (2)
35-46
: Enhance error message clarity.While the error handling is good, the error message could be more descriptive to help with debugging.
Consider this improvement:
- throw new Error("No address provided (useSimulateFeeQuery)"); + throw new Error( + `No ${isDummyUser ? "dummy" : "wallet"} address available for fee simulation` + );
Line range hint
88-103
: Add file size and type validation for Wasm files.Consider adding validation for the Wasm file size and type before processing.
Here's a suggested improvement:
if (!wasmFile) throw new Error("No Wasm file provided (useSimulateFeeForStoreCode)"); + + const MAX_WASM_SIZE = 600 * 1024; // 600KB + if (wasmFile.size > MAX_WASM_SIZE) + throw new Error(`Wasm file size exceeds maximum allowed size of ${MAX_WASM_SIZE / 1024}KB`); + + if (!wasmFile.name.endsWith('.wasm')) + throw new Error('Invalid file type. Only .wasm files are allowed');
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/lib/app-provider/hooks/useGetSigningClient.ts
(2 hunks)src/lib/pages/instantiate/InstantiateFormPage.tsx
(5 hunks)src/lib/providers/initia-widget.tsx
(1 hunks)src/lib/services/tx/simulateFee.ts
(10 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- src/lib/pages/instantiate/InstantiateFormPage.tsx
- src/lib/providers/initia-widget.tsx
- src/lib/app-provider/hooks/useGetSigningClient.ts
🔇 Additional comments (2)
src/lib/services/tx/simulateFee.ts (2)
6-12
: LGTM! Well-structured import changes and type improvements.The changes improve type safety with
Option<Gas>
and add flexibility withextraQueryKey
. The new imports align well with the architectural changes.Also applies to: 21-22
49-57
: LGTM! Well-structured query keys.The query keys are consistently structured across all hooks and include all necessary dependencies for proper cache invalidation.
Also applies to: 105-112, 194-207
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (3)
src/lib/components/wallet-section/index.tsx (3)
16-24
: Consider handling loading states for username resolutionWhile the conditional fetching is good, there's no visible handling of loading states for username resolution. This could lead to UI flickers when switching between addresses or wallet types.
Consider adding loading states:
- const { data: initiaUsername } = useInitiaUsernameByAddress( + const { data: initiaUsername, isLoading: isInitiaLoading } = useInitiaUsernameByAddress( address, isInitia ); - const { data: icnsNames } = useIcnsNamesByAddressLcd(address, !isInitia); + const { data: icnsNames, isLoading: isIcnsLoading } = useIcnsNamesByAddressLcd(address, !isInitia);
37-87
: Consider extracting common button configurationsThere's some duplication in the ConnectWalletButton props across different render conditions. This could be simplified by extracting common configurations.
Consider creating a shared configuration:
const commonButtonProps = { iconColor: "text.main", icon: "wallet", } as const; const connectedButtonProps = { icon: "wallet-solid", variant: "ghost-primary", } as const; // Then use like: <ConnectWalletButton {...commonButtonProps} buttonText="Connect Wallet" onClick={onClickConnect} />
16-88
: Well-structured component with clean integrationThe component successfully integrates the new Initia widget while maintaining clean separation of concerns and consistent behavior across different wallet types. The architecture aligns well with the broader changes mentioned in the PR summary.
Consider documenting the supported wallet types and their respective flows in the component's documentation or README to help future maintainers understand the different integration paths.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/lib/components/wallet-section/index.tsx
(1 hunks)
🔇 Additional comments (2)
src/lib/components/wallet-section/index.tsx (2)
1-14
: LGTM! Well-organized importsThe imports are logically grouped and all dependencies are properly utilized within the component.
74-74
: Ensure address sanitization before displayWhile truncation is implemented, consider adding sanitization for the address display to prevent potential XSS attacks if the address comes from an untrusted source.
Let's check if there's any address sanitization in the codebase:
Also applies to: 41-41
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (8)
src/lib/services/proposal/index.ts (1)
57-59
: LGTM: Consistent refactoring pattern across hooksThe replacement of
useLcdEndpoint
withuseCelatoneApp
is implemented consistently across all hooks. The destructuring patternchainConfig: { lcd: lcdEndpoint }
maintains type safety and follows best practices.However, consider extracting this common pattern into a custom hook for better reusability:
// src/lib/hooks/useLcdEndpoint.ts import { useCelatoneApp } from "lib/app-provider"; export const useLcdEndpoint = () => { const { chainConfig: { lcd } } = useCelatoneApp(); return lcd; };This would simplify the code in each hook to:
const lcdEndpoint = useLcdEndpoint();Also applies to: 120-122, 199-201, 215-217, 233-235
src/lib/services/distribution/index.ts (1)
26-31
: Consider memoizing the query keys.The query keys array is recreated on every render. Consider memoizing it with
useMemo
to optimize performance.+ const queryKey = useMemo( + () => [ + CELATONE_QUERY_KEYS.DELEGATION_REWARDS_BY_ADDRESS_LCD, + lcdEndpoint, + address, + ], + [lcdEndpoint, address] + ); - [ - CELATONE_QUERY_KEYS.DELEGATION_REWARDS_BY_ADDRESS_LCD, - lcdEndpoint, - address, - ]Also applies to: 51-51, 56-56
src/lib/services/bank/index.ts (1)
31-31
: LGTM! Consider adding type annotation for chainConfig destructuring.The refactoring to use
chainConfig
directly fromuseCelatoneApp
improves code organization. For better type safety, consider adding explicit type annotation:- chainConfig: { chain, lcd: lcdEndpoint }, + chainConfig: { chain, lcd: lcdEndpoint }: { chain: string; lcd: string },src/lib/services/account/index.ts (1)
77-79
: Consider memoizing the endpoint selection.Since the endpoint selection depends on
isFullTier
, consider memoizing the final endpoint to prevent unnecessary recalculations.+ const endpoint = useMemo( + () => (isFullTier ? apiEndpoint : lcdEndpoint), + [isFullTier, apiEndpoint, lcdEndpoint] + );src/lib/services/wasm/code/index.ts (1)
51-57
: Consider adding error boundary for LCD queries.Since LCD queries can fail, consider adding error boundaries or fallback mechanisms for better error handling.
return useInfiniteQuery( [CELATONE_QUERY_KEYS.CODES_LCD, lcdEndpoint], - ({ pageParam }) => getCodesLcd(lcdEndpoint, pageParam), + async ({ pageParam }) => { + try { + return await getCodesLcd(lcdEndpoint, pageParam); + } catch (error) { + console.error('Failed to fetch codes from LCD:', error); + throw error; + } + },src/lib/services/move/module/index.ts (1)
201-201
: Consider moving the endpoint path to configuration.The hardcoded path
/initia/move/v1/script/abi
should be moved to a configuration constant or derived from the chain configuration.- `${lcdEndpoint}/initia/move/v1/script/abi` + `${lcdEndpoint}${config.paths.scriptAbi}`src/lib/services/wasm/contract/index.ts (1)
99-101
: Consider simplifying the endpoint selection logic.In
useContractData
, the endpoint selection could be simplified by moving the logic to a custom hook or utility function, making it more reusable across similar cases.const useEndpoint = (isFullTier: boolean) => { const { chainConfig: { lcd } } = useCelatoneApp(); const apiEndpoint = useBaseApiRoute("contracts"); return isFullTier ? apiEndpoint : lcd; };Also applies to: 210-214
src/lib/services/move/resource/index.ts (1)
Line range hint
34-89
: Consider memoizing resource grouping operations.The resource grouping logic performs multiple array operations. Consider memoizing the transformation results using
useMemo
to prevent unnecessary recalculations on re-renders.const groupResources = useCallback((resources: Resource[]) => { // existing grouping logic }, []); const groupedResources = useMemo(() => groupResources(resources), [resources, groupResources] );
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (22)
src/lib/app-provider/hooks/index.ts
(2 hunks)src/lib/app-provider/hooks/useLcdEndpoint.ts
(0 hunks)src/lib/hooks/useOpenTab.ts
(1 hunks)src/lib/pages/block-details/components/BlockDetailsTop.tsx
(2 hunks)src/lib/pages/proposal-details/components/proposal-top/ViewProposalJson.tsx
(3 hunks)src/lib/services/account/index.ts
(3 hunks)src/lib/services/bank/index.ts
(1 hunks)src/lib/services/block/index.ts
(6 hunks)src/lib/services/distribution/index.ts
(3 hunks)src/lib/services/evm/index.ts
(4 hunks)src/lib/services/move/module/index.ts
(9 hunks)src/lib/services/move/resource/index.ts
(3 hunks)src/lib/services/name/index.ts
(4 hunks)src/lib/services/nft-collection/index.ts
(6 hunks)src/lib/services/nft/index.ts
(8 hunks)src/lib/services/proposal/index.ts
(6 hunks)src/lib/services/staking/index.ts
(5 hunks)src/lib/services/tx/index.ts
(13 hunks)src/lib/services/validator/index.ts
(5 hunks)src/lib/services/wasm/code/index.ts
(4 hunks)src/lib/services/wasm/contract/index.ts
(8 hunks)src/lib/services/wasm/contractState/index.ts
(2 hunks)
💤 Files with no reviewable changes (1)
- src/lib/app-provider/hooks/useLcdEndpoint.ts
🚧 Files skipped from review as they are similar to previous changes (6)
- src/lib/services/block/index.ts
- src/lib/services/validator/index.ts
- src/lib/services/name/index.ts
- src/lib/services/tx/index.ts
- src/lib/app-provider/hooks/index.ts
- src/lib/services/nft-collection/index.ts
🔇 Additional comments (22)
src/lib/services/proposal/index.ts (2)
17-17
: LGTM: Import addition is consistent with the refactoringThe addition of
useCelatoneApp
import aligns with the architectural changes to centralize LCD endpoint management.
Line range hint
1-316
: Verify the impact of LCD endpoint changesThe refactoring from direct LCD endpoint usage to
chainConfig.lcd
might affect error handling and loading states.Let's verify the usage and error handling patterns:
✅ Verification successful
LCD endpoint refactoring is properly implemented with consistent error handling
The changes show consistent usage of
chainConfig.lcd
with proper error handling (retry: 1
) and loading states managed through React Query's built-in mechanisms.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check for error handling patterns around LCD endpoint usage rg -A 3 "chainConfig.*lcd" --type typescript # Look for potential error boundaries or loading states rg -A 3 "useQuery.*lcd" --type typescript # Check for any remaining direct LCD endpoint usage rg "useLcdEndpoint" --type typescriptLength of output: 233
Script:
#!/bin/bash # Check for LCD endpoint usage patterns rg -A 5 "chainConfig.*lcd" # Look for error handling in LCD queries rg -A 5 "useQuery.*LCD" # Check for any direct LCD endpoint references rg -B 2 -A 2 "lcdEndpoint(?!.*chainConfig)"Length of output: 28261
src/lib/pages/proposal-details/components/proposal-top/ViewProposalJson.tsx (2)
4-4
: LGTM! Good architectural improvement.The transition from direct hook usage to the context-based approach using
useCelatoneApp
aligns well with the broader architectural changes. This centralization of configuration access improves maintainability and consistency.Also applies to: 16-18
27-27
: Verify the LCD endpoint path construction.The URL path construction looks correct, but please ensure that:
- The path segments
cosmos
andinitia
are the correct API endpoints for both networks- The version parameter in the path matches the API versions of both networks
✅ Verification successful
The LCD endpoint path construction is correctly implemented
The verification confirms that:
- Both 'cosmos' and 'initia' are valid API path segments used consistently across the codebase
- The version parameter is properly typed and can only be 'v1' or 'v1beta1', matching the API versions supported by both networks
- The implementation follows the same pattern as other authenticated endpoints in the codebase
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for other LCD endpoint usages to verify consistency rg -g '*.{ts,tsx}' "lcd.*cosmos/gov|initia/gov" --no-filenameLength of output: 119
Script:
#!/bin/bash # Search for config.version and version related to API endpoints rg -g '*.{ts,tsx,json}' "version.*gov|gov.*version" -A 2 -B 2 # Search for more initia endpoints rg -g '*.{ts,tsx}' "initia.*gov" -A 2 -B 2 # Look for configuration files that might define these endpoints fd -e json -e ts -e tsx -e js configLength of output: 1872
Script:
#!/bin/bash # Check chain config type definitions and usage cat src/lib/types/chainConfig.ts # Look for version configurations in chain config files cat src/config/chain/devChainConfigs.ts # Search for network-specific endpoint patterns rg -g '*.{ts,tsx}' "lcdEndpoint.*=|LCD_ENDPOINT" -A 2 -B 2Length of output: 10379
src/lib/pages/block-details/components/BlockDetailsTop.tsx (3)
11-11
: LGTM! Import change aligns with the architectural updates.The replacement of
useLcdEndpoint
withuseCelatoneApp
follows the broader refactoring effort to centralize configuration access.
33-35
: LGTM! Clean implementation of the new configuration access pattern.The destructuring pattern provides type-safe access to the LCD endpoint through the centralized app configuration.
40-40
: Verify API endpoint compatibility.The URL construction uses the Cosmos SDK v1beta1 API endpoint. Please ensure this endpoint is supported across all chain configurations that will be using this component.
✅ Verification successful
Endpoint compatibility verified
The endpoint
/cosmos/base/tendermint/v1beta1/blocks/${height}
is a standard Cosmos SDK Tendermint RPC endpoint that is guaranteed to be supported across all chain configurations.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for any custom LCD endpoint implementations across chain configs # Search for LCD endpoint configurations rg -A 5 'lcd[\":\s]' --type ts --type tsx # Search for any custom block details API implementations ast-grep --pattern 'blocks/${$_}'Length of output: 160
Script:
#!/bin/bash # Search for LCD/RPC endpoint configurations rg -i "lcdEndpoint|lcd.*endpoint|rpc.*endpoint" --type ts --type tsx -A 3 # Search for block details API endpoint patterns rg "/blocks/\$|/blocks/\${" --type ts --type tsx -A 2 # Search for chain configuration patterns rg "chain.*config" --type ts --type tsx -A 3Length of output: 336
Script:
#!/bin/bash # Search for LCD endpoint configurations rg -i "lcdEndpoint|lcd.*endpoint|rpc.*endpoint" -A 3 # Search for block details API patterns rg "/blocks/" -A 2 # Search for chain configurations rg "chainConfig|chain.*configuration" -A 3Length of output: 66298
src/lib/services/wasm/contractState/index.ts (1)
3-3
: LGTM! Consistent with the architectural changes.The refactoring from
useLcdEndpoint
touseCelatoneApp
is clean and maintains type safety through proper destructuring.Let's verify the consistency of this refactoring pattern across the codebase:
Also applies to: 12-14
✅ Verification successful
Refactoring verification successful
The removal of
useLcdEndpoint
and adoption ofuseCelatoneApp
is complete and consistent across the entire codebase. The change insrc/lib/services/wasm/contractState/index.ts
follows the established pattern.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify that useLcdEndpoint has been consistently replaced with useCelatoneApp # across the codebase # Check for any remaining usages of useLcdEndpoint rg "useLcdEndpoint" # Verify the consistent usage pattern of chainConfig.lcd rg "chainConfig:\s*{\s*lcd:"Length of output: 172
Script:
#!/bin/bash # Check for any remaining usages of old hook rg "useLcdEndpoint" # Check for imports of old hook ast-grep --pattern 'import { $$$useLcdEndpoint$$$ } from "$_"' # Verify new pattern adoption rg "useCelatoneApp" # Check for consistent imports of new hook ast-grep --pattern 'import { $$$useCelatoneApp$$$ } from "lib/app-provider"'Length of output: 19641
src/lib/services/distribution/index.ts (1)
20-22
: LGTM! Consistent refactoring pattern.The replacement of
useLcdEndpoint
withuseCelatoneApp
is consistently applied across both functions, maintaining proper integration with governance configuration.Also applies to: 43-45
src/lib/hooks/useOpenTab.ts (1)
27-29
: LGTM! Clean integration with app configuration.The refactoring maintains proper memoization and dependency management while cleanly integrating with the application's configuration.
src/lib/services/evm/index.ts (2)
18-20
: LGTM! Consistent refactoring and improved naming.The changes maintain consistency with the architectural pattern while improving naming conventions (bech32_prefix → bech32Prefix).
Also applies to: 35-37, 52-54
60-60
: Verify the impact of the bech32Prefix renaming.The renaming from
bech32_prefix
tobech32Prefix
should be consistently applied across the codebase.Also applies to: 63-63
✅ Verification successful
The different naming conventions are intentionally used for different purposes
The codebase consistently uses:
bech32_prefix
(snake_case) in configuration and type definitionsbech32Prefix
(camelCase) in implementation codeThe conversion between these conventions is properly handled where needed, following TypeScript best practices.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify consistent renaming of bech32_prefix to bech32Prefix # Check for any remaining instances of the old naming rg "bech32_prefix" # Verify the usage of the new naming rg "bech32Prefix"Length of output: 8813
src/lib/services/staking/index.ts (2)
20-22
: LGTM! Consistent refactoring pattern.The refactoring to use
chainConfig.lcd
is consistent with the architectural changes. The query key updates correctly reflect the new endpoint source.Also applies to: 26-27
39-41
: Verify query key consistency across hooks.The pattern of updating query keys is consistent across all hooks. Let's verify that all instances of
lcdEndpoint
in query keys match their usage in the query functions.Also applies to: 45-46, 58-60, 64-65, 77-79, 83-84
✅ Verification successful
Query key consistency verification completed
All query keys in the staking service correctly match their usage in the query functions, with consistent parameter ordering and naming conventions.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify consistent usage of lcdEndpoint in query keys and functions rg -A 2 "CELATONE_QUERY_KEYS\.[A-Z_]+.*lcdEndpoint.*\]" src/lib/services/staking/Length of output: 1037
src/lib/services/account/index.ts (1)
32-34
: LGTM! Business logic preserved with improved configuration management.The refactoring maintains the tier-based endpoint selection while improving configuration management through
chainConfig
.src/lib/services/wasm/code/index.ts (2)
23-29
: LGTM! Query configuration preserved.The refactoring maintains the specific query configurations (
keepPreviousData
,retry: false
) while updating the endpoint source.
84-90
: Verify error handling consistency.Let's verify that error handling is consistent across all LCD query functions in the codebase.
✅ Verification successful
Error handling is consistent across LCD functions
The code follows the established error handling pattern used throughout the codebase:
- Network errors handled by axios
- Response validation through parseWithError utility
- Query management via useQuery with retry: 1
- Type safety enforced by zod schemas
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check for try-catch blocks in LCD query functions rg -A 5 "getLcd|fetchLcd" src/lib/services/ | grep -B 5 "try"Length of output: 61
Script:
#!/bin/bash # Find all LCD-related query functions echo "=== LCD Query Function Declarations ===" ast-grep --pattern 'const $_ = async ($$$) => { $$$ }' | rg -B2 -A5 'Lcd|lcd' echo -e "\n=== LCD Query Function Usage ===" rg -B2 -A5 'Lcd|lcd.*async' echo -e "\n=== Error Handling Patterns ===" rg -B2 -A5 'catch|throw.*Lcd|lcd'Length of output: 81316
Script:
#!/bin/bash # Find parseWithError implementation and usage echo "=== parseWithError Implementation ===" rg -B2 -A5 "export.*parseWithError" echo -e "\n=== parseWithError Usage with LCD ===" rg -B2 -A5 "parseWithError.*lcd"Length of output: 622
src/lib/services/nft/index.ts (2)
49-51
: LGTM! Consistent endpoint retrieval pattern.The changes consistently retrieve the LCD endpoint from
useCelatoneApp
, improving the maintainability of the codebase by centralizing configuration access.Also applies to: 106-108, 139-141, 158-160, 221-223, 320-322
155-155
: Good rename fromprefix
tobech32Prefix
.The variable renaming from
prefix
tobech32Prefix
improves code clarity by being more explicit about the variable's purpose.Also applies to: 169-169, 177-177
src/lib/services/move/module/index.ts (1)
60-62
: LGTM! Consistent endpoint retrieval pattern.The changes consistently retrieve the LCD endpoint from
useCelatoneApp
, following the same pattern across all hooks.Also applies to: 88-90, 124-126, 156-158, 195-197, 282-284, 301-303, 320-322, 345-347
src/lib/services/wasm/contract/index.ts (1)
246-248
: LGTM! Consistent endpoint retrieval pattern.The changes consistently retrieve the LCD endpoint from
useCelatoneApp
, improving configuration management.Also applies to: 282-284, 301-303, 320-322, 345-347
src/lib/services/move/resource/index.ts (1)
28-30
: LGTM! Consistent endpoint retrieval pattern.The change follows the established pattern of retrieving the LCD endpoint from
useCelatoneApp
.
Summary by CodeRabbit
Based on the comprehensive summary of changes, here are the concise release notes:
New Features
Improvements
Dependencies
@initia/react-wallet-widget
package.Breaking Changes
Chores