Open
Conversation
Add proposal withdraw
Uint265 hexstring
Update goeth
[KLDC-41] Divergent TRX rewards values
* Add new method for call approve function in contract * Fixed TRC20Approve Bug
* replace deprecate protobuf package * . * improve tx parser * contract tests/examples * Account sign and verify message
* add staking 2.0 operations * update staking 2.0 * adjust model * update staking v2.0 operations * skip tests only for testnet nile
* upgrade deprecated packages * golang packages * btcd * goethereum
Co-authored-by: gribanoid <gricrypto007@gmail.com>
* feat(cmd): add tronctl upgrade command for self-updating Add a new `tronctl upgrade` command that downloads and installs the latest release by delegating to the project's install.sh script. Supports --check (dry run) and --version flags. Detects Homebrew and go install builds, redirecting users to the appropriate upgrade method. Closes #244 * fix(cmd): address PR review feedback on upgrade command - Kill curl process on sh.Start() failure to prevent process leak - Use http.Client with 30s timeout instead of default client - Clarify go-install detection logic with inline comment - Remove redundant nil check on HTTP response
* feat(client): add pending pool methods Expose GetTransactionFromPending, GetTransactionListFromPending, and GetPendingSize gRPC wrappers with context-aware variants. Add convenience helpers IsTransactionPending and GetPendingTransactionsByAddress for common use cases. Closes #239 * fix(client): use sentinel error for pending tx not-found Introduce ErrPendingTxNotFound and propagate real RPC errors in IsTransactionPending and GetPendingTransactionsByAddress instead of silently swallowing them.
…252) * feat(address): add BytesToAddress and EthAddressToAddress utilities Add conversion functions for raw bytes and Ethereum-format addresses to TRON addresses, closing a gap in the address package API. Closes #245 * fix(address): clarify copy semantics in BytesToAddress doc and tests Update doc comment to state that input bytes are always copied (no aliasing). Replace weak copy-semantics test with one that mutates the original input and verifies isolation for the default branch.
…#254) * feat(client): add callValue support to TriggerConstantContract for payable function simulation (#241) Add variadic ConstantCallOption to TriggerConstantContract and TriggerConstantContractWithData (plus their Ctx variants) so callers can set CallValue and TokenValue when simulating payable functions. Closes #241 * fix(client): surface WithTokenValue parse errors and guard nil options Address PR review feedback: - WithTokenValue now returns (ConstantCallOption, error) so invalid token IDs are surfaced immediately instead of silently ignored - applyConstantCallOptions skips nil options to prevent panics - Add TestWithTokenValue_InvalidTokenID for the error path
* feat(client): add WithEstimate() option to TRC20 methods for energy estimation Add TRC20Option variadic parameter to TRC20Send, TRC20Approve, and TRC20TransferFrom (and their Ctx variants). When WithEstimate() is passed, the methods use TriggerConstantContract for a dry-run simulation instead of building a real transaction, enabling idiomatic energy cost estimation. Closes #242 * fix(client): address PR review — nil guard and test hardening Add nil check in applyTRC20Options to prevent panics from nil option entries. Add explicit TriggerContractFunc fail-fast to estimateMock so tests catch routing bugs immediately.
…e JSON params (#258) * feat(abi): infer parameter types from method signature for plain-value JSON params Add LoadFromJSONWithMethod that accepts plain value arrays (e.g., ["TJD...", "1000000"]) in addition to the existing typed-object format, inferring types from the method signature automatically. Closes #257 * fix(abi): validate empty array arity and preserve numeric precision - Validate empty [] against method arity instead of silently returning nil - Use json.Decoder with UseNumber() to preserve large integer precision - Add edge case tests for raw numbers, large integers, and empty array with non-zero-arg methods
… pattern (#260) * feat: transaction builder + contract call builder with multi-terminal pattern Add new builder packages for constructing, signing, and broadcasting TRON transactions with a fluent API: - pkg/signer: Signer interface with PrivateKey, Keystore, and Ledger implementations for decoupled transaction signing - pkg/txbuilder: Native transaction builder (Transfer, FreezeV2, DelegateResource, VoteWitness, etc.) with Build/Send/SendAndConfirm terminals and fluent .Vote()/.Lock() methods - pkg/contract: Smart contract call builder with Call/EstimateEnergy/ Build/Send/SendAndConfirm terminals, deferred error pattern via SetError/Err for fluent chain safety - pkg/standards/trc20: Typed TRC20 wrapper with Info/BalanceOf/Transfer/ Approve/TransferFrom — rich return types with formatted balances - pkg/txresult: Shared Receipt type used by both builder packages - pkg/tron: SDK convenience entry point with compile-time interface checks Design: same builder, multiple terminal operations. Set up the client once, then chain method calls to build transactions: tx := txbuilder.New(conn) tx.Transfer(from, to, amount).Send(ctx, signer) tx.VoteWitness(from).Vote("TW1", 100).Vote("TW2", 200).Send(ctx, signer) All existing pkg/client methods remain unchanged — fully backwards compatible. Closes #243 * fix: address CodeRabbit review findings - Add EstimateEnergyWithDataCtx to GrpcClient and contract.Client interface, enabling energy estimation with pre-packed ABI data - Require From address for EstimateEnergy (mirrors Build behavior) - Return partial Receipt with TxID on post-sign broadcast failures so callers can re-query the transaction status - Validate secp256k1 curve in NewPrivateKeySigner; reject other curves - Return defensive copy from privateKeySigner.Address() - Make padUint256 return error for nil, negative, or >256-bit values - Only retry "not found" errors in SendAndConfirm confirmation loop; surface permanent errors immediately - Skip nil options in applyOptions to prevent panics - Rename TransferFrom parameter from "owner" to "caller" for clarity - Remove stale demoRecord reference that broke CI build * fix(txbuilder): return partial Receipt on broadcast failure Move receipt creation before BroadcastCtx so callers get the TxID even when broadcast fails — the transaction may have been received by the node despite the error. Also propagate partial receipt from SendAndConfirm on Send failure. Mirrors the same fix already applied to contract/builder.go. * fix(txbuilder): return partial Receipt on context cancellation SendAndConfirm now returns the receipt (with TxID) instead of nil when the context is cancelled during confirmation polling, matching all other error paths in both txbuilder and contract packages. * fix(txbuilder): add nil guard for malformed transaction responses Prevent panic if buildFn returns a TransactionExtention with nil Transaction or RawData by checking before accessing those fields. * fix(txbuilder): add nil guards for BroadcastCtx and GetTransactionInfoByIDCtx responses Prevent panics if either gRPC call returns (nil, nil) by checking result and info for nil before accessing their fields.
* docs: add and improve Go doc comments across all pkg/ packages Add missing doc comments and improve existing low-quality ones across the entire public API surface. Fix typos (calulcated, deafault, privete, Ythe AML) and replace placeholder "..." comments with proper descriptions. * docs: address PR review feedback - Fix misleading IsValidPassphrase doc to reflect placeholder status - Use errors.New instead of fmt.Errorf for static ErrInvalidMnemonic - Improve DecodeCheck doc with return value description - Zero private key bytes after serialization in EncodeHex
…c complexity (#270) * fix: correct misspellings, gofmt simplification, and reduce cyclomatic complexity (#269) Fix misspellings across CLI subcommands and pkg packages, remove empty var() block for gofmt -s compliance, and extract monolithic *Sub() functions into individual command constructors following Cobra best practices to reduce cyclomatic complexity. * fix: address PR review feedback from CodeRabbit - Fix --estiamte flag typo to --estimate (contract.go) - Use comma-ok idiom for proposal collision detection (proposal.go) - Clarify brokerage range error message (sr.go) - Remove dead assignment result["amount"] = addr.String() (account.go) - Add missing --feeLimit flag to trc20 send command (trc20.go) * fix: address round 2 PR review feedback - Use signerAddress instead of unset addr in withdraw result (account.go) - Use comma-ok idiom for vote collision detection (account.go) - Add description to --details flag (account.go) - Fix copy-paste error: "Approve" → "Create" in proposalCreateCmd (proposal.go) * fix: address round 3 PR review feedback - Move vote collision check after address normalization to detect duplicates regardless of input format (account.go) - Improve flag descriptions for --useFixedLength and --hashMessage on both sign and verify commands (account.go)
…276) Patches critical authorization bypass vulnerability via missing leading slash in :path. Also bumps transitive deps: golang.org/x/crypto, golang.org/x/net, golang.org/x/term, golang.org/x/text.
* feat(mnemonic): add configurable entropy size to Generate (#268) Accept an optional entropy size in bits via variadic int parameter. Valid values: 128, 160, 192, 224, 256 (producing 12-24 word mnemonics). Default remains 256 (24 words) for backward compatibility. * test: use require.Error to prevent nil dereference in invalid entropy test
* test: improve code coverage to 82.6% and add Codecov integration Add meaningful unit tests across 8 packages, bringing overall coverage from ~65% to 82.6%. All new tests exercise real logic (crypto, encoding, validation, file I/O) — no mock-echo patterns. New test coverage: - client/transaction: 63% → 84% (SHA256 hashing, keystore signing, broadcast flow, DryRun branching, confirmation, error cascade) - keystore: 71% → 82% (pkcs7Unpad, AES-CBC/CTR round-trips, RecoverPubkey sign-then-verify, getKDFKey error paths, wallet Contains/Status/SignTx with signature recovery) - trc20: 54% → 97% (ABI encoding/decoding, padUint256 round-trips, formatBalance math, address validation, call data verification) - store: 74% → 94% (SetKeystoreFactory, CloseAll, UnlockedKeystore with real encrypted keys, AddressFromAccountName, FromAddress) - signer: 42% → 56% (real keystore signing, lock/unlock, determinism, multi-sig, defensive copy, curve rejection, BTCEC/ECDSA parity) - account: 77% → 79% (path traversal validation, writeToFile, generateName, export round-trips) - mnemonic: 71% → 71% (BIP39 word list validation, uniqueness) Standardize all test assertions to testify assert/require — removed all raw t.Fatal/t.Fatalf/t.Error/t.Errorf calls across the entire test suite for consistent style. Add Codecov integration: - .codecov.yml with 80% project target, excluding cmd/examples/proto - Codecov badge in README.md * fix: address CodeRabbit review feedback - Add runtime.GOOS guard for Unix-only test path (internal_test.go) - Verify signature covers final raw data with PermissionId via Ecrecover (controller_test.go) - Assert tx ID in both txConfirmation mock handlers (controller_test.go) - Make TestDecodeStringTruncatedABI deterministic with require.Error (token_test.go) - Add bounds check panic to abiEncodeString test helper (token_test.go) - Replace time.Sleep with runtime.Gosched for goroutine settling (local_test.go)
…ireUnfreeze (#279) * feat(txbuilder): add fluent WithMemo/WithPermissionID and WithdrawExpireUnfreeze Add fluent methods for cross-cutting transaction concerns so developers can chain them naturally with any builder method: b.Transfer(from, to, amount).WithMemo("payment").WithPermissionID(2).Send(ctx, s) b.DelegateResource(from, to, res, amt).Lock(86400).WithMemo("x").Send(ctx, s) b.VoteWitness(from).Vote(sr, 100).WithPermissionID(2).Send(ctx, s) - Add WithMemo/WithPermissionID on Tx, DelegateTx, and VoteTx - Each specialized type returns its own concrete type for full chain safety - Functional options still work at builder and per-call level - Fluent methods override options when both are used - Add WithdrawExpireUnfreeze builder method with full fluent support - Add WithdrawExpireUnfreezeCtx to Client interface * test(txbuilder): verify fluent and option APIs produce identical transactions Add equivalence tests that build the same transaction via both APIs and assert the serialized RawData is byte-identical. Covers Transfer, DelegateResource (with Lock), and VoteWitness. * fix(txbuilder): recompute Txid after applying permissionID or memo Build mutates RawData (adding permissionID/memo) after the node returns the TransactionExtention, making the original Txid stale. Now sha256(RawData) is recomputed so ext.Txid always matches the final serialized transaction.
…lue, WithTokenValue (#280) * feat(contract): add fluent WithPermissionID, WithFeeLimit, WithCallValue, WithTokenValue Add fluent methods to ContractCall for all cross-cutting configuration options, matching the pattern established in txbuilder: contract.New(c, addr).From(from).Method(sig). WithFeeLimit(100_000_000). WithPermissionID(2). WithCallValue(1_000_000). Send(ctx, signer) Also works with TRC20 via the existing contract.Option passthrough: token.Transfer(from, to, amount). WithFeeLimit(100_000_000). WithPermissionID(2). Send(ctx, signer) Both functional options (.Apply()) and fluent methods produce identical serialized transactions (verified by equivalence test). * refactor(contract): delegate fluent setters to Option helpers, consolidate test fixtures - Fluent methods now delegate to Apply(WithX()) to prevent drift between option and fluent code paths - Clarify WithTokenValue doc: only affects Build/Send/EstimateEnergy, not read-only Call - Consolidate newDummyTxExt and newTestTxExt into a single newTestTxExt helper
…simulation (#281) * fix(contract): forward token value in Call() for TRC10 constant call simulation Call() only forwarded callValue to constant contract calls but silently ignored tokenID/tokenAmount. This meant WithTokenValue had no effect on read-only simulations of TRC10-aware contracts. Now Call() forwards both callValue and tokenValue as ConstantCallOptions, matching the behavior of Build/EstimateEnergy. * docs(contract): update WithTokenValue doc to reflect Call() forwarding
) Add opt-in MetadataCache that caches immutable token metadata (name, symbol, decimals) after the first successful RPC fetch. Subsequent calls serve from memory, eliminating redundant network round-trips. - LRU eviction with configurable max size (container/list + sync.Mutex) - Per-field bitmask population (partial cache works — e.g. only decimals) - Thread-safe for concurrent goroutines - Shared across Token instances via WithCache option - BalanceOf/Info automatically use cached decimals/symbol - Zero external dependencies - Backward compatible: New(client, addr) works unchanged
…284) Add .Sign() terminal to txbuilder.Tx and contract.ContractCall that builds and signs without broadcasting — useful for deferred broadcast or transaction inspection. Add WithdrawExpireUnfreezeContract decode support to DecodeContractData, completing coverage for all native contract types used by the MCP policy engine. Closes #283
…, and testing (#285) * refactor: major SDK improvement — correctness, architecture, security, and testing BREAKING CHANGES: - address.BigToAddress now returns (Address, error) instead of Address - address.HexToAddress now returns (Address, error) instead of Address - address.Bytes() returns a copy to prevent external mutation - address.IsValid() validates Base58Check checksum - account functions (ExportPrivateKey, CreateNewLocalAccount, ImportFromPrivateKey, ImportKeyStore, ExportKeystore) now accept Store as first parameter - account.IsValidPassphrase enforces minimum 8 characters - keys.FromMnemonicSeedAndPassphrase moved to mnemonic.FromSeedAndPassphrase (old function kept as deprecated wrapper) - ledger: Device interface replaces singleton + log.Fatalln pattern - txbuilder.Tx is single-use (second Build/Send returns ErrAlreadyBuilt) - contract.SetError accumulates errors via errors.Join - pkg/errors dependency removed — all wrapping uses stdlib %w New packages: - pkg/txcore: shared Send/SendAndConfirm/TransactionID/Receipt for builders - pkg/standards/trc20enc: canonical TRC20 ABI encoding (cycle-free) - pkg/mnemonic: FromSeedAndPassphrase (single mnemonic entry point) New features: - 11 service interfaces on GrpcClient (AccountService, ContractService, etc.) - Functional options: NewGrpcClientWithOptions(addr, WithTimeout, WithAPIKey) - CLI: account freezeV2 / unfreezeV2 commands - CLI: .env auto-loading, TRONCTL_NODE/TRONCTL_KS_DIR/TRONCTL_TLS/TRONCTL_SIGNER env vars - pkg/store: Store struct with explicit config dir - pkg/common: DebugConfig struct - keys.ZeroPrivateKey for key material cleanup - Typed sentinel errors across all packages - CLI Runtime struct with focused setup methods Security: - Keystore: key zeroization on Lock, TimedUnlock, Export, Update - ExportPrivateKey returns key as string instead of printing to stdout - writeToFile: tightened permissions to 0700/0600, removed os.Chdir - Path traversal validation in ImportFromPrivateKey - Ledger: panics converted to error returns Testing: - Benchmarks for address encoding, base58, ABI parsing - Fuzz tests for address, ABI, base58, hexutils - Race condition tests for keystore and store - Keystore security tests (zeroization, concurrent sign, idempotent close) - scripts/integration-test.sh: 36-test round-trip on local node - scripts/local-node.sh: Docker-based local TRON node management Bug fixes: - Float precision: math.Round for TRX-to-SUN conversion - for-range: iterate values not indices in generateName (Go 1.22+) - Ledger HID framer: panics converted to errors - Fixed typo: "Blokchain" → "Blockchain" * fix: address CodeRabbit review feedback - Fix typo "one address" → "TRON address" in custom-flags.go - Run go mod tidy - FuzzABIGetParser: use real ERC-20 ABI instead of empty - Add bad-checksum Base58 seed to fuzz corpus - Must-style init for defaultFromAddress (panic on invalid hex) - Clear debug env vars before DebugFromEnv test assertions - Collect goroutine errors in keystore race tests - Add BitLen overflow guard in DecodeString - Call Forget(ks) after Close in DescribeLocalAccounts and FromAddress - Assert first Build succeeds in single-use test - Fix shell redirect order: >/dev/null 2>&1 - Resolve DATA_DIR from script location in local-node.sh - Boost test coverage to 83.8% (keys, signer, account, keystore) * fix: address second round of CodeRabbit review feedback - Use require.Error before .Error() dereference in account_test.go - Rename TestPrivateKeySigner_Sign_NilTransaction → EmptyTransaction - Compare raw data against independent copy in sign preservation test - AddressFromAccountName: call Forget after Close - DefaultLocation: acquire mutex before reading configDir - UnlockedKeystore: call Forget on error-close paths * fix: eliminate data race in Store.configDir access Extract getConfigDir() that reads s.configDir under s.mu, and configRootFromDir() as a pure function. All public methods now access configDir through the lock-protected path. * fix: address remaining CodeRabbit review feedback - Add keys.ZeroECDSAKey() for secure ECDSA key zeroing via D.Bits() - Fix account_cache.go: log hexErr instead of nil err - Fix local_race_test.go: path.Join → filepath.Join, /tmp → t.TempDir() - Fix misleading "keystore not found" → "no accounts found in keystore" * fix: protect all package-level reads of DefaultConfigDirName with mutex Add getDefaultConfigDir() snapshot helper under keystoreMu. configRoot() now delegates to configRootFromDir(getDefaultConfigDir()). DefaultStoreInstance() simplified to NewStore(configRoot()). SetDefaultLocation() snapshots dir path under lock before filesystem ops.
* fix: handle homedir errors and remove go-homedir dependency Replace github.com/mitchellh/go-homedir with stdlib os.UserHomeDir(). Both call sites now handle errors instead of silently swallowing them: - pkg/store/local.go: warns and falls back to "." if HOME unset - pkg/keys/keys.go: warns and returns "" to skip dir creation Closes #286 * fix: propagate homedir errors instead of fallback - checkAndMakeKeyDirIfNeeded returns (string, error); callers abort on failure - configRootFromDir returns (string, error); mustConfigRoot panics on failure - No more silent fallback to "." or "" on UserHomeDir error * fix: move mustConfigRoot outside mutex to prevent deadlock on panic
* feat: TRC20 contract integration test and CLI improvements - Add --params flag to contract deploy for constructor arguments - Fix TRC20ContractBalance: strip 0x41 prefix in ABI encoding (Hex()[2:]→Hex()[4:]) - Remove signer requirement from contract constant (read-only calls) - Trim whitespace from --abiFile/--bcFile content (trailing newline fix) - Error when --params provided but ABI has no constructor - Add pre-compiled TestToken TRC20 contract (testdata/contracts/) - Extend integration test: deploy, constant calls, balance, transfer, approve * style: align var block formatting
- Update direct deps: btcec v2.3.6, go-ethereum v1.17.1, cobra v1.10.2, crypto v0.49.0, term v0.41.0, zap v1.27.1 - Add Dec.Display() for trailing-zero-free numeric formatting - Add auto-decode for contract constant results (uint256, string, bool, address) - Replace trc20enc init() hex decoding with pre-computed byte literals - Return explicit error for ledger message signing (was silent no-op) - Remove dead commented-out signature validation code
* docs: add MCP server section to README and update demo GIF - Add MCP Server section with zero-install Claude Desktop config - Add AI-Ready bullet to Features list - Link to gotron-mcp repo and mcp.gotron.sh hosted endpoint - Update demo GIF with new sections (contract read, address conversion, SR detail) and fixed banner alignment * docs: clarify MCP config examples and hosted mode capabilities - Add Claude Code CLI example alongside Desktop JSON config - Note that Desktop remote servers use Settings > Connectors - Clarify hosted mode: read-only queries + unsigned tx builders - Link to gotron-mcp repo for local mode with signing support * docs: remove claude_desktop_config.json snippet for remote MCP Remote MCP servers should be added via Settings > Connectors in Claude Desktop, not via the config file. Keep only the UI instruction.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.