Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

test: extend solana unit tests #3158

Merged
merged 8 commits into from
Nov 15, 2024
Merged

test: extend solana unit tests #3158

merged 8 commits into from
Nov 15, 2024

Conversation

skosito
Copy link
Contributor

@skosito skosito commented Nov 14, 2024

Description

  • extend inbound and outbound tests for new instructions
  • fix terminology, tokenAccount was used instead of mintAccount
  • improve how accounts are resolved in inbound instructions

How Has This Been Tested?

  • Tested CCTX in localnet
  • Tested in development environment
  • Go unit tests
  • Go integration tests
  • Tested via GitHub Actions

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new struct for SPL withdrawal instructions, enhancing functionality with a decimal precision field.
    • Added tests for SPL withdrawal message hashing and instruction parsing, improving validation and error handling.
  • Improvements

    • Streamlined variable naming from tokenAccount to mintAccount across multiple components for clarity.
    • Enhanced deposit instruction handling with improved account resolution and error messaging.
  • Documentation

    • Added a detailed JSON file documenting an outbound transaction on the Solana blockchain.

@skosito skosito added the no-changelog Skip changelog CI check label Nov 14, 2024
@skosito skosito linked an issue Nov 14, 2024 that may be closed by this pull request
Copy link
Contributor

coderabbitai bot commented Nov 14, 2024

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request encompasses a series of changes primarily focused on renaming variables and parameters related to SPL token management within the Solana ecosystem. Key modifications include changing instances of tokenAccount to mintAccount across various methods and structures, enhancing consistency in terminology. Additionally, new functionalities and tests for SPL withdrawal instructions are introduced, along with updates to existing functions to improve error handling and account resolution. The overall structure and logic of the code remain intact, with a focus on maintaining clarity and accuracy in the representation of SPL token accounts.

Changes

File Path Change Summary
e2e/runner/setup_solana.go Renamed variable tokenAccount to mintAccount in the SetupSolana method.
e2e/runner/solana.go Renamed tokenAccount to mintAccount in ResolveSolanaATA, SPLDepositAndCall, DeploySPL, CreateDepositSPLInstruction, and CreateWhitelistSPLMintInstruction methods.
pkg/contracts/solana/gateway.go Renamed function ParseRentPayerPda to ParseRentPayerPDA.
pkg/contracts/solana/gateway_message.go Renamed tokenAccount field to mintAccount in MsgWithdrawSPL struct and updated related methods accordingly.
pkg/contracts/solana/gateway_message_test.go Added new test function Test_MsgWithdrawSPLHash to validate hash generation for SPL withdrawal messages.
pkg/contracts/solana/inbound.go Updated getSignerDeposit and getSignerAndSPLFromDepositSPLAccounts functions to use ResolveInstructionAccounts for better account handling.
pkg/contracts/solana/inbound_test.go Expanded Test_ParseInboundAsDeposit and Test_ParseInboundAsDepositSPL with additional test cases for error handling and validation.
pkg/contracts/solana/instruction.go Introduced WithdrawSPLInstructionParams struct and ParseInstructionWithdrawSPL function for SPL withdrawal instructions.
zetaclient/chains/solana/observer/outbound_test.go Added test function Test_ParseInstructionWithdrawSPL to validate parsing of SPL withdrawal instructions.
zetaclient/chains/solana/signer/withdraw_spl.go Renamed tokenAccount to mintAccount in createAndSignMsgWithdrawSPL and signWithdrawSPLTx methods.
zetaclient/testdata/solana/chain_901_outbound_tx_result_3NgoR4K9FJq7UunorPRGW9wpqMV8oNvZERejutd7bKmqh3CKEV5DMZndhZn7hQ1i4RhTyHXRWxtR5ZNVHmmjAUSF.json Added a new JSON file detailing a specific outbound transaction on the Solana blockchain.

Possibly related PRs

Suggested labels

SOLANA_TESTS, UPGRADE_TESTS

Suggested reviewers

  • fbac
  • kingpinXD
  • ws4charlie
  • brewmaster012
  • lumtis
  • swift1337

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

Documentation and Community

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

Copy link

!!!WARNING!!!
nosec detected in the following files: pkg/contracts/solana/gateway_message_test.go

Be very careful about using #nosec in code. It can be a quick way to suppress security warnings and move forward with development, it should be employed with caution. Suppressing warnings with #nosec can hide potentially serious vulnerabilities. Only use #nosec when you're absolutely certain that the security issue is either a false positive or has been mitigated in another way.

Only suppress a single rule (or a specific set of rules) within a section of code, while continuing to scan for other problems. To do this, you can list the rule(s) to be suppressed within the #nosec annotation, e.g: /* #nosec G401 */ or //#nosec G201 G202 G203
Broad #nosec annotations should be avoided, as they can hide other vulnerabilities. The CI will block you from merging this PR until you remove #nosec annotations that do not target specific rules.

Pay extra attention to the way #nosec is being used in the files listed above.

@github-actions github-actions bot added the nosec label Nov 14, 2024
Copy link

codecov bot commented Nov 14, 2024

Codecov Report

Attention: Patch coverage is 51.42857% with 17 lines in your changes missing coverage. Please review.

Project coverage is 62.84%. Comparing base (46f3d44) to head (7fb1268).
Report is 2 commits behind head on develop.

Files with missing lines Patch % Lines
zetaclient/chains/solana/signer/withdraw_spl.go 0.00% 9 Missing ⚠️
pkg/contracts/solana/inbound.go 72.72% 4 Missing and 2 partials ⚠️
pkg/contracts/solana/gateway_message.go 50.00% 2 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop    #3158      +/-   ##
===========================================
+ Coverage    62.67%   62.84%   +0.16%     
===========================================
  Files          424      424              
  Lines        30128    30140      +12     
===========================================
+ Hits         18884    18942      +58     
+ Misses       10402    10360      -42     
+ Partials       842      838       -4     
Files with missing lines Coverage Δ
pkg/contracts/solana/gateway.go 0.00% <ø> (ø)
pkg/contracts/solana/instruction.go 18.57% <ø> (ø)
pkg/contracts/solana/gateway_message.go 49.67% <50.00%> (+19.35%) ⬆️
pkg/contracts/solana/inbound.go 84.81% <72.72%> (+26.60%) ⬆️
zetaclient/chains/solana/signer/withdraw_spl.go 0.00% <0.00%> (ø)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (14)
pkg/contracts/solana/gateway_message_test.go (2)

51-60: Consider enhancing test coverage with table-driven tests.

While the test setup is well-structured, consider implementing table-driven tests to cover multiple scenarios and edge cases. This would make it easier to add new test cases and improve maintainability.

Example refactor:

 func Test_MsgWithdrawSPLHash(t *testing.T) {
-	t.Run("should pass for archived inbound, receipt and cctx", func(t *testing.T) {
+	tests := []struct {
+		name        string
+		chainID     uint64
+		nonce       uint64
+		amount      uint64
+		mintAccount solana.PublicKey
+		to          solana.PublicKey
+		wantHash    string
+	}{
+		{
+			name:        "should pass for archived inbound",
+			chainID:     uint64(chains.SolanaLocalnet.ChainId),
+			nonce:       0,
+			amount:      1336000,
+			mintAccount: solana.MustPublicKeyFromBase58("AS48jKNQsDGkEdDvfwu1QpqjtqbCadrAq9nGXjFmdX3Z"),
+			to:          solana.MustPublicKeyFromBase58("37yGiHAnLvWZUNVwu9esp74YQFqxU1qHCbABkDvRddUQ"),
+			wantHash:    "87fa5c0ed757c6e1ea9d8976537eaf7868bc1f1bbf55ab198a01645d664fe0ae",
+		},
+		// Add more test cases here
+	}

67-67: Document or parameterize the hardcoded decimals value.

The decimals value of 8 is hardcoded in the NewMsgWithdrawSPL call. Consider documenting why this specific value is used or making it configurable through test parameters.

-		hash := contracts.NewMsgWithdrawSPL(chainID, nonce, amount, 8, mintAccount, to, toAta).Hash()
+		const tokenDecimals = 8 // Standard decimals for SPL token X
+		hash := contracts.NewMsgWithdrawSPL(chainID, nonce, amount, tokenDecimals, mintAccount, to, toAta).Hash()
pkg/contracts/solana/inbound.go (2)

105-106: Consider extracting magic number into a named constant

The account count validation uses a magic number through accountsNumDeposit. Consider defining this as a documented constant at package level for better maintainability and self-documentation.

const (
    MaxSignaturesPerTicker = 100
+   // AccountsNumDeposit is the number of accounts required for a deposit instruction
+   // [signer, pda, system_program]
+   AccountsNumDeposit = 3
)

129-133: Consider extracting magic number into a named constant

Similar to the previous suggestion, consider defining accountsNumberDepositSPL as a documented constant at package level.

const (
    MaxSignaturesPerTicker = 100
+   // AccountsNumberDepositSPL is the number of accounts required for a deposit SPL instruction
+   // [signer, pda, whitelist_entry, mint_account, token_program, from, to]
+   AccountsNumberDepositSPL = 7
)
pkg/contracts/solana/inbound_test.go (1)

71-124: LGTM: Comprehensive error case coverage with room for improvement

The new test cases effectively cover important validation scenarios:

  1. Discriminator validation
  2. Account count validation
  3. Signer requirement validation

Consider enhancing the error validation by checking specific error messages:

 deposit, err := ParseInboundAsDeposit(tx, 0, txResult.Slot)
 require.Error(t, err)
+require.Contains(t, err.Error(), "expected 3 accounts")
 require.Nil(t, deposit)

This would ensure that the correct validation is failing for the expected reason.

pkg/contracts/solana/instruction.go (3)

131-131: Add compile-time interface compliance check

Add a compile-time check to ensure WithdrawSPLInstructionParams implements the OutboundInstruction interface.

Add this line before the struct definition:

+var _ OutboundInstruction = (*WithdrawSPLInstructionParams)(nil)

Line range hint 192-194: Improve error message specificity

The error message should specifically mention that this is for SPL withdrawal instructions.

-		return nil, fmt.Errorf("not a withdraw instruction: %v", inst.Discriminator)
+		return nil, fmt.Errorf("not a withdraw SPL instruction: %v", inst.Discriminator)

131-131: Enhance documentation for the Decimals field

The current comment could be more descriptive about the purpose and usage of the Decimals field.

-	// Decimals is decimals for spl token
+	// Decimals represents the number of decimal places used by the SPL token.
+	// For example, if Decimals is 6, then an amount of 1000000 represents 1 token.
e2e/runner/solana.go (4)

Line range hint 166-177: Enhance error handling in ATA resolution

While the function correctly handles ATA creation, consider improving error handling for production readiness.

 func (r *E2ERunner) ResolveSolanaATA(
     payer solana.PrivateKey,
     owner solana.PublicKey,
     mintAccount solana.PublicKey,
 ) solana.PublicKey {
     pdaAta, _, err := solana.FindAssociatedTokenAddress(owner, mintAccount)
     require.NoError(r, err)
 
-    info, _ := r.SolanaClient.GetAccountInfo(r.Ctx, pdaAta)
+    info, err := r.SolanaClient.GetAccountInfo(r.Ctx, pdaAta)
+    require.NoError(r, err)
+
     if info != nil {
         return pdaAta
     }

205-207: Extract whitelist seed construction to a constant

Consider extracting the whitelist seed construction to improve maintainability and reusability.

+const WhitelistSeedPrefix = "whitelist"

 func (r *E2ERunner) SPLDepositAndCall(...) solana.Signature {
-    seed := [][]byte{[]byte("whitelist"), mintAccount.Bytes()}
+    seed := [][]byte{[]byte(WhitelistSeedPrefix), mintAccount.Bytes()}
     whitelistEntryPDA, _, err := solana.FindProgramAddress(seed, r.GatewayProgram)

265-266: Extract magic number for initial mint amount

Consider extracting the hardcoded mint amount to a named constant for better maintainability.

+const InitialMintAmount = 1_000_000_000

-    mintToInstruction := token.NewMintToInstruction(uint64(1_000_000_000), mintAccount.PublicKey(), ata, privateKey.PublicKey(), []solana.PublicKey{}).
+    mintToInstruction := token.NewMintToInstruction(uint64(InitialMintAmount), mintAccount.PublicKey(), ata, privateKey.PublicKey(), []solana.PublicKey{}).

Line range hint 279-288: Extract whitelist verification logic

Consider extracting the whitelist verification logic into a separate function for better code organization.

+func (r *E2ERunner) isTokenWhitelisted(mintAccount solana.PublicKey) (bool, solana.PublicKey, error) {
+    seed := [][]byte{[]byte("whitelist"), mintAccount.Bytes()}
+    whitelistEntryPDA, _, err := solana.FindProgramAddress(seed, r.GatewayProgram)
+    if err != nil {
+        return false, solana.PublicKey{}, err
+    }
+
+    whitelistEntryInfo, err := r.SolanaClient.GetAccountInfo(r.Ctx, whitelistEntryPDA)
+    return whitelistEntryInfo != nil, whitelistEntryPDA, err
+}

 func (r *E2ERunner) DeploySPL(privateKey *solana.PrivateKey, whitelist bool) *solana.Wallet {
     // ... existing code ...
     
     if whitelist {
-        seed := [][]byte{[]byte("whitelist"), mintAccount.PublicKey().Bytes()}
-        whitelistEntryPDA, _, err := solana.FindProgramAddress(seed, r.GatewayProgram)
-        require.NoError(r, err)
-
-        whitelistEntryInfo, err := r.SolanaClient.GetAccountInfo(r.Ctx, whitelistEntryPDA)
+        isWhitelisted, whitelistEntryPDA, err := r.isTokenWhitelisted(mintAccount.PublicKey())
         require.Error(r, err)
 
-        if whitelistEntryInfo != nil {
+        if isWhitelisted {
             return mintAccount
         }
zetaclient/chains/solana/observer/outbound_test.go (2)

364-390: Consider adding edge case tests.

While the happy path test is comprehensive, consider adding test cases for:

  • Zero token amount
  • Maximum possible decimals (9 for SPL tokens)
  • Maximum possible nonce value

364-424: Consider refactoring to table-driven tests.

The test could be more maintainable using table-driven tests, consistent with Go's testing best practices. This would make it easier to add new test cases and reduce code duplication.

Example refactor:

 func Test_ParseInstructionWithdrawSPL(t *testing.T) {
-	// the test chain and transaction hash
-	chain := chains.SolanaDevnet
-	txHash := withdrawSPLTxTest
-	txAmount := uint64(1000000)
+	tests := []struct {
+		name          string
+		txHash        string
+		modifyInst    func(*solana.CompiledInstruction)
+		expectedErr   string
+		expectedInst  *contracts.InstructionWithdrawSPL
+	}{
+		{
+			name:   "successful parsing",
+			txHash: withdrawSPLTxTest,
+			expectedInst: &contracts.InstructionWithdrawSPL{
+				TokenAmount: 1000000,
+				Decimals:    6,
+				Nonce:       3,
+			},
+		},
+		{
+			name:   "invalid instruction data",
+			txHash: withdrawSPLTxTest,
+			modifyInst: func(inst *solana.CompiledInstruction) {
+				inst.Data = []byte("invalid instruction data")
+			},
+			expectedErr: "error deserializing instruction",
+		},
+		// Add more test cases here
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			txResult := testutils.LoadSolanaOutboundTxResult(t, TestDataDir, chains.SolanaDevnet.ChainId, tt.txHash)
+			tx, err := txResult.Transaction.GetTransaction()
+			require.NoError(t, err)
+
+			instruction := tx.Message.Instructions[0]
+			if tt.modifyInst != nil {
+				tt.modifyInst(&instruction)
+			}
+
+			inst, err := contracts.ParseInstructionWithdrawSPL(instruction)
+			if tt.expectedErr != "" {
+				require.ErrorContains(t, err, tt.expectedErr)
+				require.Nil(t, inst)
+				return
+			}
+
+			require.NoError(t, err)
+			require.Equal(t, tt.expectedInst.TokenAmount, inst.TokenAmount)
+			require.Equal(t, tt.expectedInst.Decimals, inst.Decimals)
+			require.Equal(t, tt.expectedInst.Nonce, inst.GatewayNonce())
+		})
+	}
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d6ed9aa and 8173fc4.

📒 Files selected for processing (11)
  • e2e/runner/setup_solana.go (1 hunks)
  • e2e/runner/solana.go (7 hunks)
  • pkg/contracts/solana/gateway.go (1 hunks)
  • pkg/contracts/solana/gateway_message.go (4 hunks)
  • pkg/contracts/solana/gateway_message_test.go (1 hunks)
  • pkg/contracts/solana/inbound.go (1 hunks)
  • pkg/contracts/solana/inbound_test.go (3 hunks)
  • pkg/contracts/solana/instruction.go (1 hunks)
  • zetaclient/chains/solana/observer/outbound_test.go (2 hunks)
  • zetaclient/chains/solana/signer/withdraw_spl.go (3 hunks)
  • zetaclient/testdata/solana/chain_901_outbound_tx_result_3NgoR4K9FJq7UunorPRGW9wpqMV8oNvZERejutd7bKmqh3CKEV5DMZndhZn7hQ1i4RhTyHXRWxtR5ZNVHmmjAUSF.json (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • e2e/runner/setup_solana.go
  • pkg/contracts/solana/gateway.go
  • zetaclient/testdata/solana/chain_901_outbound_tx_result_3NgoR4K9FJq7UunorPRGW9wpqMV8oNvZERejutd7bKmqh3CKEV5DMZndhZn7hQ1i4RhTyHXRWxtR5ZNVHmmjAUSF.json
🧰 Additional context used
📓 Path-based instructions (8)
e2e/runner/solana.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

pkg/contracts/solana/gateway_message.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

pkg/contracts/solana/gateway_message_test.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

pkg/contracts/solana/inbound.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

pkg/contracts/solana/inbound_test.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

pkg/contracts/solana/instruction.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

zetaclient/chains/solana/observer/outbound_test.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

zetaclient/chains/solana/signer/withdraw_spl.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

🪛 GitHub Check: codecov/patch
pkg/contracts/solana/gateway_message.go

[warning] 179-180: pkg/contracts/solana/gateway_message.go#L179-L180
Added lines #L179 - L180 were not covered by tests

pkg/contracts/solana/inbound.go

[warning] 101-102: pkg/contracts/solana/inbound.go#L101-L102
Added lines #L101 - L102 were not covered by tests


[warning] 125-126: pkg/contracts/solana/inbound.go#L125-L126
Added lines #L125 - L126 were not covered by tests

zetaclient/chains/solana/signer/withdraw_spl.go

[warning] 43-43: zetaclient/chains/solana/signer/withdraw_spl.go#L43
Added line #L43 was not covered by tests


[warning] 49-49: zetaclient/chains/solana/signer/withdraw_spl.go#L49
Added line #L49 was not covered by tests


[warning] 51-51: zetaclient/chains/solana/signer/withdraw_spl.go#L51
Added line #L51 was not covered by tests


[warning] 55-55: zetaclient/chains/solana/signer/withdraw_spl.go#L55
Added line #L55 was not covered by tests


[warning] 88-88: zetaclient/chains/solana/signer/withdraw_spl.go#L88
Added line #L88 was not covered by tests


[warning] 90-90: zetaclient/chains/solana/signer/withdraw_spl.go#L90
Added line #L90 was not covered by tests


[warning] 93-93: zetaclient/chains/solana/signer/withdraw_spl.go#L93
Added line #L93 was not covered by tests


[warning] 95-95: zetaclient/chains/solana/signer/withdraw_spl.go#L95
Added line #L95 was not covered by tests


[warning] 105-105: zetaclient/chains/solana/signer/withdraw_spl.go#L105
Added line #L105 was not covered by tests

🔇 Additional comments (11)
pkg/contracts/solana/inbound.go (1)

97-145: Overall improvements to account resolution look good

The changes to both functions improve the robustness of account resolution and validation:

  1. Using ResolveInstructionAccounts instead of direct access
  2. Clear validation of account counts
  3. Explicit signer checks
  4. Well-documented account ordering

The code is now more maintainable and secure.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 101-102: pkg/contracts/solana/inbound.go#L101-L102
Added lines #L101 - L102 were not covered by tests


[warning] 125-126: pkg/contracts/solana/inbound.go#L125-L126
Added lines #L125 - L126 were not covered by tests

zetaclient/chains/solana/signer/withdraw_spl.go (3)

42-55: LGTM: Improved terminology accuracy

The renaming from tokenAccount to mintAccount better aligns with Solana's terminology, where mint accounts represent the token definition. This change enhances code clarity and domain accuracy.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 43-43: zetaclient/chains/solana/signer/withdraw_spl.go#L43
Added line #L43 was not covered by tests


[warning] 49-49: zetaclient/chains/solana/signer/withdraw_spl.go#L49
Added line #L49 was not covered by tests


[warning] 51-51: zetaclient/chains/solana/signer/withdraw_spl.go#L51
Added line #L51 was not covered by tests


[warning] 55-55: zetaclient/chains/solana/signer/withdraw_spl.go#L55
Added line #L55 was not covered by tests


105-105: LGTM: Correct account metadata setup

The mint account is correctly included in the instruction's account metadata list with appropriate permissions.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 105-105: zetaclient/chains/solana/signer/withdraw_spl.go#L105
Added line #L105 was not covered by tests


Line range hint 128-132: Consider implementing dynamic compute budget

The TODO comment indicates a potential optimization for handling transaction fees. While the current fixed fee approach works, implementing dynamic compute budgets could improve transaction reliability during network congestion.

Let's check if this issue is being tracked:

✅ Verification successful

Dynamic compute budget optimization is actively tracked

The concern is valid and already being tracked in issue #2599 "Explorer Solana priority fee and compute budget for outbound." The TODO comment accurately reflects the current fixed fee of 5K lamports and the need for optimization through priority fees and compute budgets.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify if the compute budget issue is being tracked
gh issue view 2599 --json title,state,labels

Length of output: 354


Script:

#!/bin/bash
# Check the content of the file for the TODO comment and its context
rg -A 5 "TODO" zetaclient/chains/solana/signer/withdraw_spl.go

Length of output: 395

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 43-43: zetaclient/chains/solana/signer/withdraw_spl.go#L43
Added line #L43 was not covered by tests


[warning] 49-49: zetaclient/chains/solana/signer/withdraw_spl.go#L49
Added line #L49 was not covered by tests


[warning] 51-51: zetaclient/chains/solana/signer/withdraw_spl.go#L51
Added line #L51 was not covered by tests


[warning] 55-55: zetaclient/chains/solana/signer/withdraw_spl.go#L55
Added line #L55 was not covered by tests

pkg/contracts/solana/inbound_test.go (2)

11-13: LGTM: Imports are well-organized and necessary

The added imports for Solana and Borsh libraries are required for the new test cases and follow good organization practices.


Line range hint 19-33: Verify test data availability

The tests load transaction data from JSON files, but these files are not visible in the review.

✅ Verification successful

The previous attempt showed that the specific JSON files weren't found. Let's search more broadly to understand what test data files exist and how they are referenced in the tests.


Test data files are present and correctly referenced

The test data files mentioned in the code are present in the repository:

  • pkg/contracts/solana/testdata/MS3MPLN7hkbyCZFwKqXcg8fmEvQMD74fN6Ps2LSWXJoRxPW5ehaxBorK9q1JFVbqnAvu9jXm6ertj7kT7HpYw1j.json
  • pkg/contracts/solana/testdata/aY8yLDze6nHSRi7L5REozKAZY1aAyPJ6TfibiqQL5JGwgSBkYux5z5JfXs5ed8LZqpXUy4VijoU3x15mBd66ZGE.json

The files are also correctly referenced in the test code at pkg/contracts/solana/inbound_test.go using the LoadObjectFromJSONFile function.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if test data files exist
ls testdata/MS3MPLN7hkbyCZFwKqXcg8fmEvQMD74fN6Ps2LSWXJoRxPW5ehaxBorK9q1JFVbqnAvu9jXm6ertj7kT7HpYw1j.json \
   testdata/aY8yLDze6nHSRi7L5REozKAZY1aAyPJ6TfibiqQL5JGwgSBkYux5z5JfXs5ed8LZqpXUy4VijoU3x15mBd66ZGE.json

# Check JSON validity
for f in testdata/*.json; do
  if [ -f "$f" ]; then
    jq '.' "$f" >/dev/null
  fi
done

Length of output: 564


Script:

#!/bin/bash
# Let's check if there are any JSON files in the testdata directory or its subdirectories
fd -e json -t f

# Also check if there are any references to JSON test files in the test code
rg -g "*.go" "testdata.*\.json" -A 2 -B 2

Length of output: 17846

pkg/contracts/solana/gateway_message.go (4)

122-123: LGTM: Improved terminology accuracy

The rename from tokenAccount to mintAccount better reflects the field's purpose in representing the SPL token's mint address.


142-142: LGTM: Constructor changes align with field renaming

The parameter and field assignment changes maintain consistency with the struct field renaming.

Also applies to: 150-150


179-180: Add test coverage for the MintAccount getter

While the getter implementation is correct, it lacks test coverage according to the code coverage report. Since this PR focuses on extending Solana unit tests, we should ensure this new method is tested.

#!/bin/bash
# Check if there are any existing tests for MintAccount getter
rg -l "func.*Test.*MintAccount" .

Would you like me to help generate a test case for this getter method?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 179-180: pkg/contracts/solana/gateway_message.go#L179-L180
Added lines #L179 - L180 were not covered by tests


203-203: Verify hash compatibility with existing data

The hash calculation now uses mintAccount instead of tokenAccount. While this change is consistent with the renaming, please verify that this doesn't affect compatibility with any existing stored hashes in the system.

✅ Verification successful

Change is safe - test vectors validate hash calculation

The hash calculation change from tokenAccount to mintAccount is validated by existing test vectors in Test_MsgWithdrawSPLHash. The test explicitly verifies the hash using the mintAccount parameter against a known hash value, confirming that this is the intended behavior rather than a breaking change.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for stored hashes or hash comparisons in tests
rg -A 2 "withdraw_spl_token.*[Hh]ash"

Length of output: 35


Script:

#!/bin/bash
# Search for tests involving hash verification or comparison
rg -A 5 "Hash\(\)" pkg/contracts/solana/

Length of output: 4760


Script:

#!/bin/bash
# Search for any stored or hardcoded hashes in tests
rg -A 2 "hash.*:.*[\"'].*[\"']" pkg/contracts/solana/

Length of output: 1033


Script:

#!/bin/bash
# Look for test files containing both hash and mint/token account references
rg -l "(Hash|hash).*mint.*account|mint.*account.*(Hash|hash)" pkg/contracts/solana/

Length of output: 85


Script:

#!/bin/bash
# Check if there are any test vectors or fixtures containing hashes
fd -e json -e yaml -x grep -l "hash" {}

Length of output: 6857


Script:

#!/bin/bash
# Search for any hash-related test assertions
rg -A 2 "assert.*[Hh]ash" pkg/contracts/solana/

Length of output: 49


Script:

#!/bin/bash
# Search for test vectors specifically for MsgWithdrawSPL
rg -A 10 "Test_MsgWithdrawSPLHash" pkg/contracts/solana/gateway_message_test.go

Length of output: 619


Script:

#!/bin/bash
# Look for any stored hash test vectors
rg -A 5 "wantHashBytes.*:=" pkg/contracts/solana/gateway_message_test.go

Length of output: 839

zetaclient/chains/solana/observer/outbound_test.go (1)

41-43: LGTM: Well-documented test constant.

The constant follows the established pattern and includes a descriptive comment.

pkg/contracts/solana/gateway_message_test.go Outdated Show resolved Hide resolved
pkg/contracts/solana/inbound.go Show resolved Hide resolved
pkg/contracts/solana/inbound.go Show resolved Hide resolved
pkg/contracts/solana/inbound_test.go Outdated Show resolved Hide resolved
pkg/contracts/solana/gateway_message_test.go Outdated Show resolved Hide resolved
pkg/contracts/solana/gateway_message_test.go Outdated Show resolved Hide resolved
pkg/contracts/solana/gateway_message_test.go Show resolved Hide resolved
pkg/contracts/solana/inbound.go Outdated Show resolved Hide resolved
pkg/contracts/solana/inbound_test.go Show resolved Hide resolved
@skosito skosito requested a review from lumtis November 14, 2024 20:34
Copy link
Contributor

@ws4charlie ws4charlie left a comment

Choose a reason for hiding this comment

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

looks good. nit comment

@skosito skosito added this pull request to the merge queue Nov 15, 2024
Merged via the queue into develop with commit 3c22fbb Nov 15, 2024
40 of 41 checks passed
@skosito skosito deleted the improve-solana-unit-tests branch November 15, 2024 09:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-changelog Skip changelog CI check nosec
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Extend unit tests for solana integration features
3 participants