Skip to content

Refactor/kos-go#255

Merged
klever-patrick merged 6 commits into
developfrom
refactor/kos-go
May 12, 2026
Merged

Refactor/kos-go#255
klever-patrick merged 6 commits into
developfrom
refactor/kos-go

Conversation

@klever-patrick
Copy link
Copy Markdown
Contributor

@klever-patrick klever-patrick commented May 12, 2026

Summary by CodeRabbit

  • New Features

    • Introduced a unified Go API for wallet generation, mnemonic handling, transaction signing, and chain support across many blockchains.
    • Added BigNumber support with arithmetic, comparisons, and sign handling.
    • Added cryptographic utilities for key derivation, ECDSA signing, ECIES, and HMAC.
  • Bug Fixes

    • Improved hex decode error handling for prev-script inputs.
  • Tests

    • Added extensive tests covering wallet, signer, and BigNumber behaviors.

Review Change Stack

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 12, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: fc3567da-eb05-4f47-b74d-67e9e6ac86e0

📥 Commits

Reviewing files that changed from the base of the PR and between d2aa948 and 6667b07.

📒 Files selected for processing (5)
  • packages/kos-go/demo/main.go
  • packages/kos-go/number.go
  • packages/kos-go/signer.go
  • packages/kos-go/wallet.go
  • packages/kos-go/wallet_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/kos-go/wallet.go
  • packages/kos-go/number.go
  • packages/kos-go/signer.go

📝 Walkthrough

Walkthrough

Adds a new kosgo Go wrapper around kos_mobile: exported type aliases and constructors, a BigNumber wrapper with tests, signer wrappers and tests, wallet APIs (mnemonic/derivation/encryption, SignTransaction), extensive wallet tests, and an updated demo using kosgo APIs.

Changes

Go SDK Wrapper for kos-mobile

Layer / File(s) Summary
Type aliases and option constructors
packages/kos-go/models.go
Type aliases for transaction and wallet option types and constructor wrappers delegating to kos_mobile.
BigNumber implementation
packages/kos-go/number.go
BigNumber wrapper, sign constants, constructors, String(), arithmetic helpers with nil checks, comparisons, unary ops, and sign predicates.
BigNumber tests
packages/kos-go/number_test.go
Tests updated to call kosgo BigNumber APIs and assert results via String().
Signer wrappers and tests
packages/kos-go/signer.go, packages/kos-go/signer_test.go
Signer error aliases and wrapper functions for xpub derivation, Slip77, ECDSA/HMAC/ECIES, with tests calling local wrappers.
Wallet API and SignTransaction
packages/kos-go/wallet.go
Re-exports account/transaction/error types, mnemonic/path helpers, wallet generation, encryption/decryption wrappers, SignTransaction with option type-switching, SignMessage, and chain support queries.
Wallet tests (deterministic signing & utilities)
packages/kos-go/wallet_test.go
Comprehensive tests: mnemonic workflows, derivation (mnemonic & private key), encryption round-trips, deterministic signing across many networks/formats, message signing, and chain/path utilities.
Demo update
packages/kos-go/demo/main.go
Demo switched to use kosgo.NewWalletOptions(false), constructs BTC signing options with explicit PrevScripts/InputAmounts and calls kosgo.SignTransaction.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • mouravitor313
  • fsiggor

Poem

A rabbit wraps with care,
Types and functions, clean and fair,
BigNumber hops and signs take flight,
Wallets sing through day and night,
🐰✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 1.02% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Refactor/kos-go' is vague and generic—it uses a non-descriptive term that only indicates a refactoring activity without conveying meaningful information about the specific changes. Replace with a more descriptive title that clearly summarizes the main change, such as 'Add Go wrapper layer for kos-mobile types and functions' or 'Introduce kosgo package abstractions for signer and wallet operations'.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/kos-go

Warning

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

🔧 golangci-lint (2.12.2)

level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies"

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@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

🧹 Nitpick comments (2)
packages/kos-go/signer_test.go (1)

17-33: ⚡ Quick win

Prefer fail-fast error assertions in these tests.

For Line 17 and Line 29 flows, use require.NoError so the test stops immediately when setup fails.

Proposed patch
 import (
 	"fmt"
 	"testing"
 
 	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
 )
@@
 	xpub, err := GenerateXpub(MNEMONIC, passphrase, isMainnet, index)
-
-	assert.Nil(t, err, "Failed to generate xpub")
+	require.NoError(t, err, "Failed to generate xpub")
 	assert.Equal(t, 78, len(xpub), "Expected xpub length to be 78")
@@
 	derivedXpub, err := DeriveXpub(MNEMONIC, passphrase, isMainnet, index, derivationPath)
-
-	assert.Nil(t, err, "Failed to derive xpub")
+	require.NoError(t, err, "Failed to derive xpub")
 	fmt.Printf("%v\n", []byte(derivedXpub))
 	assert.Equal(t, 78, len(derivedXpub), "Expected derived xpub length to be 78")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/kos-go/signer_test.go` around lines 17 - 33, Replace the non-failing
assertions in the tests with fail-fast error checks: change the calls that
assert nil errors for GenerateXpub and DeriveXpub to use require.NoError (from
testify/require) so the test aborts immediately on setup failures; update
imports to include require where needed and keep the subsequent length
assertions the same (references: GenerateXpub test and TestDeriveXpub using
DeriveXpub).
packages/kos-go/number_test.go (1)

165-205: ⚡ Quick win

Add explicit error-path tests for Div and nil operands.

Current tests validate many success paths, but they don’t assert wrapper behavior for divide-by-zero and nil inputs. Adding those cases will harden the API contract and catch panic regressions early.

Suggested additions
+func TestBigNumberErrorPaths(t *testing.T) {
+	a, err := NewBigNumber("10")
+	assert.Nil(t, err)
+	zero, err := NewBigNumber("0")
+	assert.Nil(t, err)
+
+	_, err = Div(a, zero)
+	assert.Error(t, err, "division by zero should return error")
+
+	_, err = Add(nil, a)
+	assert.Error(t, err, "nil lhs should return error")
+}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/kos-go/number_test.go` around lines 165 - 205, The tests cover
successful Div paths but miss error cases for divide-by-zero and nil operands;
update TestBigNumberDivide (or add a new TestBigNumberDivideErrors) to assert
Div returns an error (and not panic) when the divisor is zero (use
NewBigNumber("0") and expect a non-nil error) and when either argument is nil
(call Div(nil, b) and Div(a, nil) and assert errors), and ensure you check error
types/messages consistently with Div's implementation to lock the API contract.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/kos-go/demo/main.go`:
- Around line 27-36: The demo currently ignores hex.DecodeString errors for
prevScript and proceeds after kosgo.SignTransaction failures; update main.go to
check and handle both errors immediately: validate the error returned by
hex.DecodeString("76a9...") (the prevScript variable) and log/exit if non-nil,
and when kosgo.SignTransaction(account, rawTx, options) returns an err, print
the error and terminate (or return) instead of continuing; locate usages of
prevScript and the call to kosgo.SignTransaction to add these early-failure
checks so the demo fails fast on decode or signing errors.

In `@packages/kos-go/number.go`:
- Around line 33-131: Guard all exported BigNumber APIs against nil
receiver/operands: check for nil *BigNumber and nil .inner before using .inner.
For methods like String (receiver b *BigNumber) return a safe zero value (e.g.,
"" or "nil") when b or b.inner is nil; for constructors/ops that return
(*BigNumber, error) such as Add, Sub, Mul, Div, Pow, Abs, Increment, Decrement
return (nil, fmt.Errorf("nil BigNumber operand")) when any input is nil; for
boolean predicates like IsEqual, IsGt, IsGte, IsLt, IsLte, IsZero, IsPositive,
IsNegative return false if any operand is nil. Apply these nil checks at the top
of each function (e.g., in Add, Sub, Mul, Div, Pow, Abs, Increment, Decrement,
String, IsEqual, IsGt, IsGte, IsLt, IsLte, IsZero, IsPositive, IsNegative) so no
.inner is accessed when operands are nil.

In `@packages/kos-go/signer.go`:
- Line 7: Add a correctly spelled public alias LdErrorInstanceError that points
to the same underlying type as the existing misspelled alias LdErrorIntanceError
so consumers can use the correct name while keeping the old alias for
compatibility; specifically, in signer.go add a new type alias declaration `type
LdErrorInstanceError = kos_mobile.LdErrorIntanceError` alongside the existing
`LdErrorIntanceError` declaration and leave the original alias untouched.

In `@packages/kos-go/wallet_test.go`:
- Line 239: The test currently ignores hex.DecodeString errors (e.g., the
prevScript assignment and other fixtures around the file) which can hide
malformed fixtures; update each hex.DecodeString call used in tests to capture
the returned error and call t.Fatalf with a clear message on decode failure
(e.g., replace `prevScript, _ := hex.DecodeString(...)` with capturing `err` and
doing `if err != nil { t.Fatalf("failed to decode prevScript fixture: %v", err)
}`), apply the same pattern for the other decode sites referenced (lines around
the other fixtures), ensuring you use the appropriate test variable (`t`) and
descriptive messages for each fixture name to fail fast.

In `@packages/kos-go/wallet.go`:
- Around line 62-70: The type switch in SignTransaction that assigns actualOpts
by dereferencing options (cases for *TransactionChainOptionsBtc,
*TransactionChainOptionsSubstrate, *TransactionChainOptionsEvm,
*TransactionChainOptionsCosmos) can panic when a typed-nil pointer is passed;
update each pointer case to check that v != nil before dereferencing and handle
the nil case (return an error or set a sensible default) instead of blindly
doing actualOpts = *v so dereferences are safe; keep references to the options
variable, the actualOpts target, and the specific types
(TransactionChainOptionsBtc, TransactionChainOptionsSubstrate,
TransactionChainOptionsEvm, TransactionChainOptionsCosmos) to locate and fix the
code.

---

Nitpick comments:
In `@packages/kos-go/number_test.go`:
- Around line 165-205: The tests cover successful Div paths but miss error cases
for divide-by-zero and nil operands; update TestBigNumberDivide (or add a new
TestBigNumberDivideErrors) to assert Div returns an error (and not panic) when
the divisor is zero (use NewBigNumber("0") and expect a non-nil error) and when
either argument is nil (call Div(nil, b) and Div(a, nil) and assert errors), and
ensure you check error types/messages consistently with Div's implementation to
lock the API contract.

In `@packages/kos-go/signer_test.go`:
- Around line 17-33: Replace the non-failing assertions in the tests with
fail-fast error checks: change the calls that assert nil errors for GenerateXpub
and DeriveXpub to use require.NoError (from testify/require) so the test aborts
immediately on setup failures; update imports to include require where needed
and keep the subsequent length assertions the same (references: GenerateXpub
test and TestDeriveXpub using DeriveXpub).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 452d8878-3b51-4373-a7a3-c4e195fb97ab

📥 Commits

Reviewing files that changed from the base of the PR and between 06507fc and d2aa948.

📒 Files selected for processing (8)
  • packages/kos-go/demo/main.go
  • packages/kos-go/models.go
  • packages/kos-go/number.go
  • packages/kos-go/number_test.go
  • packages/kos-go/signer.go
  • packages/kos-go/signer_test.go
  • packages/kos-go/wallet.go
  • packages/kos-go/wallet_test.go

Comment thread packages/kos-go/demo/main.go Outdated
Comment thread packages/kos-go/number.go
Comment thread packages/kos-go/signer.go Outdated
Comment thread packages/kos-go/wallet_test.go Outdated
Comment thread packages/kos-go/wallet.go
@klever-patrick klever-patrick merged commit f1a6b24 into develop May 12, 2026
5 checks passed
@klever-patrick klever-patrick deleted the refactor/kos-go branch May 12, 2026 16:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants