janzeer

package module
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 23 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

janzeer-sdk-go

Official Go SDK for the Janzeer blockchain — a stake-free, permissionless Layer-1 with instant finality. Wallet keys and signing, transaction builders, a REST client, JSON-RPC over HTTP and WebSocket subscriptions. Non-custodial by construction: keys never leave your process, the node only verifies.

license Go Reference

go get github.com/janzeerorg/janzeer-sdk-go/...@v0.1.3

The /... form fetches the sub-packages (client, rpc, vault) and their dependencies in one go. If you go get the root module alone, run go mod tidy after adding the imports — otherwise the first go run stops on a missing go.sum entry for the WebSocket library the client package uses.

Releases are Git tags (vX.Y.Z); the Go module proxy and pkg.go.dev index them directly. @master gives the development head.

60-second quickstart

package main

import (
	"context"
	"fmt"
	"log"

	janzeer "github.com/janzeerorg/janzeer-sdk-go"
	"github.com/janzeerorg/janzeer-sdk-go/client"
	"github.com/janzeerorg/janzeer-sdk-go/rpc"
)

func main() {
	ctx := context.Background()
	c := client.New("https://onion.janzeer.org") // REST  (/api/v1)
	r := rpc.New("https://onion.janzeer.org")    // JSON-RPC (/rpc)
	me, err := janzeer.AccountFromMnemonic("abandon abandon … about", "")
	if err != nil {
		log.Fatal(err)
	}

	nonce, _ := c.Nonce(ctx, me.Address())
	tx, err := janzeer.NewTransfer(janzeer.Transfer{
		Common: janzeer.Common{From: me.Address(), Nonce: nonce},
		To:     "0x598b1301acef3baba6ce25e38dd17b723f7b98b1", Amount: "1.25", Data: "hello",
	})
	if err != nil {
		log.Fatal(err)
	}
	signed, _ := me.SignTx(tx)
	if _, err := c.Submit(ctx, signed); err != nil { // HTTP 201, or a typed error
		log.Fatal(err)
	}
	final, err := rpc.WaitForFinality(ctx, r, signed.Hash) // one or two 15-second slots
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("final in block", *final.BlockHeight)
}

That is the whole integration: derive → nonce → build → sign → submit → wait. A committed block is final (2f+1 BFT commit), so there is no confirmation count.

What is in the box

Package Contents Guide
janzeer Account, mnemonics, addresses, amounts, the New… transaction builders, UnsignedTx / SignedTx, error types, result models wallet-and-keys, sending-transactions, errors
janzeer/client REST: balances, nonces, transactions, validators, Get / Post for the rest reading-chain-data
janzeer/rpc JSON-RPC over HTTP (Client, batches) and WebSocket (WS, newBlocks / addressActivity), WaitForFinality json-rpc-and-subscriptions
janzeer/vault Encrypt / Decrypt (PBKDF2 + AES-GCM, compatible with the other SDKs) vault

Money is never a float

Amounts are decimal strings ("1.25"). No function of this module takes or returns a float64: 0.1 is not representable in binary, and a payment must not depend on how a float prints. Responses decode coin amounts into janzeer.Amount, which keeps the exact digits the node wrote. ToScaled gives base units as a *big.Int.

Design

  • Every network call takes a context.Context. Clients have no global state and are safe for concurrent use.
  • Errors are typed values: errors.As(err, &nonce) for *janzeer.NonceMismatchError, *janzeer.TxRejectedError, *janzeer.APIError, *janzeer.RPCError, *janzeer.NetworkError… — see errors.
  • No cgo: CGO_ENABLED=0 go build works, so it cross-compiles to every platform Go supports.
  • Dependencies: decred/dcrd/dcrec/secp256k1 (pure Go, RFC-6979), golang.org/x/crypto (keccak-256, PBKDF2), golang.org/x/text (NFKD), coder/websocket.

Requirements

Go 1.26 or newer (the two latest Go releases are tested).

Compatibility

SDK Node REST envelope version Wire protocol Vectors
0.1.x 0.1.12 1.1.0 3.4.0 v2

The Spec… constants export these values; the e2e test checks them against the node on the first call.

Examples

Runnable programs in examples/: go run ./examples/quickstart and its siblings subscribe, watchblocks, token, validator, vault. They read the JANZEER_* environment variables described in CONTRIBUTING.

Conformance

This SDK reproduces, byte for byte, the public test vectors every Janzeer SDK is tested against (key derivation, addresses, every transaction preimage, hash and signature, the vault fixture) and passes the shared 14-step end-to-end flow: https://github.com/janzeerorg/janzeer-sdk-conformance. See docs/conformance.md.

Other SDKs

TypeScript · Dart / Flutter · Kotlin / JVM / Android · Python

Licence

Apache License 2.0 — see LICENSE. Security reports: see SECURITY.

Documentation

Overview

Package janzeer is the official Go SDK of the Janzeer blockchain: keys and addresses, exact amounts, transaction builders and signing. The network clients live in the sub-packages client (REST), rpc (JSON-RPC over HTTP and WebSocket) and vault (a secret at rest).

Non-custodial by construction: keys never leave your process; the node only verifies.

me, _ := janzeer.AccountFromMnemonic("abandon … about", "")
c := client.New("https://onion.janzeer.org")
nonce, _ := c.Nonce(ctx, me.Address())
tx, _ := janzeer.NewTransfer(janzeer.Transfer{From: me.Address(), To: "0x…", Amount: "1.25", Nonce: nonce})
signed, _ := me.SignTx(tx)
_, err := c.Submit(ctx, signed)

Index

Constants

View Source
const (
	// HDSalt is used BOTH as the PBKDF2 salt base (instead of BIP39's "mnemonic") AND as the root HMAC key.
	HDSalt = "@_Janzeer_Blockchain_@"
	// DefaultPath is the only derivation path wallets use; all three levels are non-hardened.
	DefaultPath = "m/0/0/0"
)
View Source
const (
	RPCParseError      = -32700
	RPCInvalidRequest  = -32600
	RPCMethodNotFound  = -32601
	RPCInvalidParams   = -32602
	RPCInternal        = -32603
	RPCNotFound        = -32000
	RPCRejected        = -32001
	RPCNotSynchronized = -32002
	RPCLimit           = -32003
	RPCRateLimited     = -32004
)

JSON-RPC error codes of the node.

View Source
const (
	// NetworkID is consensus.network-id, bound into every signed transaction (cross-network replay protection).
	NetworkID = "janzeer"
	// Decimals of the native coin: amounts are scaled x10^8 into an int64 on the wire.
	Decimals = 8
	// Ticker is the display ticker of the native coin.
	Ticker = "JNZ"
	// MinFee is the minimum fee of every transaction, in JNZ.
	MinFee = "0.01"
	// MinTransfer is the minimum transfer amount in JNZ unless the transfer carries a memo.
	MinTransfer = "0.1"
	// MaxMemoBytes is the maximum memo length in UTF-8 bytes.
	MaxMemoBytes = 256
	// ValidatorFee is the exact fee of a validator registration.
	ValidatorFee = "3"
	// ValidatorDeposit is the exact, NON-REFUNDABLE deposit of a validator registration.
	ValidatorDeposit = "2000"
	// TokenCreateFee is the exact fee of a token CREATE; every other token operation pays MinFee.
	TokenCreateFee = "5"
)

Chain constants. Every value mirrors the node and is pinned by the conformance vectors or the e2e flow.

View Source
const (
	SpecNode     = "0.1.12"
	SpecAPI      = "1.1.0"
	SpecProtocol = "3.4.0"
	SpecVectors  = 2
)

The node, API and wire-protocol versions this SDK release was built and tested against.

View Source
const (
	LimitPageSize          = 100
	LimitBlockRange        = 100
	LimitWaitForFinalityMs = 60_000
	LimitSubscriptions     = 16
	LimitWatchedAddresses  = 1000
	LimitRPCBatch          = 50
	LimitRPCBodyBytes      = 524_288
)

Server-side limits (informational; the node enforces them).

View Source
const NoDecimals = -1

NoDecimals asks FormatJNZ for whole coins only.

Variables

This section is empty.

Functions

func AddAmounts

func AddAmounts(a, b string) (string, error)

AddAmounts returns a + b exactly, as a canonical 8-decimal string.

func CompareAmounts

func CompareAmounts(a, b string) (int, error)

CompareAmounts compares two amounts exactly: -1, 0 or 1.

func DoubleSHA256

func DoubleSHA256(data []byte) []byte

DoubleSHA256 is the transaction hash function.

func FormatJNZ

func FormatJNZ(amount string, o FormatOptions) (string, error)

FormatJNZ renders an amount for people: FormatJNZ("1.50000000", FormatOptions{}) == "1.5 JNZ".

func FromScaled

func FromScaled(scaled *big.Int) string

FromScaled is the inverse of ToScaled: base units -> a decimal string with exactly 8 fractional digits.

func GenerateMnemonic

func GenerateMnemonic(strength int) (string, error)

GenerateMnemonic returns a fresh mnemonic from the OS random source: strength 128 (12 words) … 256 (24 words).

func HashPreimage

func HashPreimage(preimage []byte) string

HashPreimage is double-SHA256 as lowercase hex: what the node calls the transaction hash.

func HexToBytes

func HexToBytes(s string) ([]byte, error)

HexToBytes decodes hex with an optional 0x prefix, either case.

func IsRPCCode

func IsRPCCode(err error, code int) bool

IsRPCCode reports whether err is an *RPCError with the given code.

func IsValidAddress

func IsValidAddress(address string) bool

IsValidAddress checks shape and checksum the way the node does: all-lowercase, all-uppercase, or correct EIP-55.

func IsValidAmount

func IsValidAmount(s string) bool

IsValidAmount reports whether s is a plain decimal with at most 8 fractional digits (what the node accepts).

func IsValidPrivateKey

func IsValidPrivateKey(privateKeyHex string) bool

IsValidPrivateKey reports whether the hex string is a valid secp256k1 scalar (32 bytes, 0 < k < n).

func Keccak256

func Keccak256(data []byte) []byte

Keccak256 is the Ethereum variant of Keccak, NOT NIST SHA3-256 (the padding differs).

func MnemonicFromEntropy

func MnemonicFromEntropy(entropy []byte) (string, error)

MnemonicFromEntropy turns 16, 20, 24, 28 or 32 bytes of entropy into a mnemonic.

func MnemonicToEntropy

func MnemonicToEntropy(mnemonic string) ([]byte, error)

MnemonicToEntropy returns the entropy of a mnemonic, or an error for an unknown word, a bad length or a bad checksum.

func MnemonicToSeed

func MnemonicToSeed(mnemonic, passphrase string) []byte

MnemonicToSeed is PBKDF2-HMAC-SHA512, 2048 rounds, 64 bytes, salt HDSalt + passphrase (NFKD inputs).

func NormalizeAddress

func NormalizeAddress(address string) (string, error)

NormalizeAddress returns the canonical lowercase form, or an error for an invalid address.

func NormalizeAmount

func NormalizeAmount(s string) (string, error)

NormalizeAmount checks that s is a plain decimal (no exponent, no "+") and returns it trimmed.

func NormalizeMnemonic

func NormalizeMnemonic(mnemonic string) string

NormalizeMnemonic normalizes whitespace and case so equivalent phrases derive the same seed.

func ParseJNZ

func ParseJNZ(input string) (string, error)

ParseJNZ turns user input like "1,234.5 JNZ" into a canonical amount string ("1234.5").

func PrivateToPublic

func PrivateToPublic(privateKeyHex string) (string, error)

PrivateToPublic returns the compressed (33-byte) public key, hex.

func PublicKeyToAddress

func PublicKeyToAddress(compressedPublicKey []byte) (string, error)

PublicKeyToAddress is the CANONICAL address: "0x" + lowercase hex of the first 20 bytes of keccak256(compressed key).

func RESTErrorFrom

func RESTErrorFrom(status int, body []byte, retryAfter string) error

RESTErrorFrom maps a non-2xx REST response to the SDK error types. Rule: a body with "payload" -> use it (the envelope wraps errors too); otherwise the body itself (the rate limiter answers before the envelope layer).

func RPCErrorFrom

func RPCErrorFrom(code int, message string, data json.RawMessage, transport string) error

RPCErrorFrom maps a JSON-RPC error object to the SDK error types. transport is "rpc" or "ws".

func SignHash

func SignHash(hashHex, privateKeyHex string) (string, error)

SignHash signs a 32-byte digest (hex): RFC-6979 deterministic, low-S, DER, Base64. The digest is signed as-is.

func SubAmounts

func SubAmounts(a, b string) (string, error)

SubAmounts returns a - b exactly, as a canonical 8-decimal string.

func ToChecksumAddress

func ToChecksumAddress(address string) string

ToChecksumAddress is the EIP-55 mixed-case display form. Presentation only: never sign or store it.

func ToScaled

func ToScaled(amount string) (*big.Int, error)

ToScaled is the node's toScaledLong: BigDecimal(amount).setScale(8, HALF_UP) x 10^8 as an integer of base units. Pinned by the "scaled" table of the conformance vectors.

func ValidateMnemonic

func ValidateMnemonic(mnemonic string) bool

ValidateMnemonic checks word-list membership and the checksum. Client-side only: the node never sees a mnemonic.

func VerifyHash

func VerifyHash(hashHex, signatureBase64, publicKeyHex string) bool

VerifyHash verifies a Base64 DER signature over a digest (hex) with a compressed public key (hex). High-S is refused.

func Wordlist

func Wordlist() []string

Wordlist returns a copy of the 2048 English words.

Types

type APIError

type APIError struct {
	Status  int
	Message string
	Type    string
	Body    json.RawMessage
}

APIError: any other REST error ({status, message, type?} payload).

func (*APIError) Error

func (e *APIError) Error() string

type Account

type Account struct {
	// contains filtered or unexported fields
}

Account is a signing identity: private key -> public key -> address. The node never sees the private key. Printing an Account shows the address only.

func AccountFromMnemonic

func AccountFromMnemonic(mnemonic, passphrase string) (*Account, error)

AccountFromMnemonic derives the wallet account of a BIP39 mnemonic (Janzeer seed, path m/0/0/0).

func AccountFromPrivateKey

func AccountFromPrivateKey(privateKeyHex string) (*Account, error)

AccountFromPrivateKey imports a raw private key (hex, optional 0x).

func AccountFromSeed

func AccountFromSeed(seed []byte, path string) (*Account, error)

AccountFromSeed derives an account from a 64-byte seed and a non-hardened path.

func NewRandomAccount

func NewRandomAccount() (*Account, error)

NewRandomAccount creates a fresh random key (not mnemonic-backed; prefer GenerateMnemonic for user wallets).

func (*Account) Address

func (a *Account) Address() string

Address is the canonical lowercase address.

func (*Account) ChecksumAddress

func (a *Account) ChecksumAddress() string

ChecksumAddress is the EIP-55 display form of the address.

func (*Account) GoString

func (a *Account) GoString() string

GoString shows the address only, so %#v never prints the key.

func (*Account) PrivateKeyHex

func (a *Account) PrivateKeyHex() string

PrivateKeyHex returns the private key as hex. Handle with care: never log or send it.

func (*Account) PublicKeyHex

func (a *Account) PublicKeyHex() string

PublicKeyHex is the compressed secp256k1 public key, hex (66 chars).

func (*Account) Sign

func (a *Account) Sign(hashHex string) (string, error)

Sign returns the RFC-6979 low-S DER signature (Base64) over a 32-byte digest given as hex.

func (*Account) SignTx

func (a *Account) SignTx(tx *UnsignedTx) (*SignedTx, error)

SignTx hashes and signs a transaction. It fails if the transaction names another sender.

func (*Account) String

func (a *Account) String() string

String shows the address only.

func (*Account) Verify

func (a *Account) Verify(hashHex, signatureBase64 string) bool

Verify checks a signature made by this account.

type AccountView

type AccountView struct {
	Address           string `json:"address"`
	Balance           Amount `json:"balance"`
	CommittedBalance  Amount `json:"committedBalance"`
	NextNonce         int64  `json:"nextNonce"`
	CommittedNonce    int64  `json:"committedNonce"`
	PendingCount      int    `json:"pendingCount"`
	IsValidatorWallet bool   `json:"isValidatorWallet"`
}

AccountView is janzeer_getAccount.

type Amount

type Amount string

Amount is a decimal number exactly as the node wrote it ("1.25000000", "77499900.002"). The node serializes coin amounts as bare JSON numbers; decoding them into a float64 would round. Amount keeps the source text.

func (Amount) MarshalJSON

func (a Amount) MarshalJSON() ([]byte, error)

MarshalJSON writes the amount as a JSON string.

func (Amount) Scaled

func (a Amount) Scaled() (*big.Int, error)

Scaled returns the amount in base units (x10^8).

func (Amount) String

func (a Amount) String() string

String returns the decimal text.

func (*Amount) UnmarshalJSON

func (a *Amount) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts a JSON number or a JSON string and keeps its exact text (an exponent is expanded).

type BlockView

type BlockView struct {
	Type              string   `json:"type"`
	Height            int64    `json:"height"`
	Hash              string   `json:"hash"`
	PreviousHash      string   `json:"previousHash"`
	Timestamp         int64    `json:"timestamp"`
	Producer          string   `json:"producer"`
	Signature         string   `json:"signature"`
	EpochIndex        *int64   `json:"epochIndex"`
	TransactionsCount int      `json:"transactionsCount"`
	Validators        []string `json:"validators"`
	Transactions      []TxView `json:"transactions"`
}

BlockView is a block as the JSON-RPC methods and the newBlocks feed return it.

type Common

type Common struct {
	// From is the sender address (an EIP-55 address is normalized).
	From string
	// Nonce is the sender's next nonce (committed nonce + pending count).
	Nonce int64
	// Fee defaults to the type's required or minimum fee.
	Fee string
	// Timestamp in ms since epoch; defaults to now.
	Timestamp int64
	// NetworkID defaults to NetworkID ("janzeer"); pass the node's id when working on a private test network.
	NetworkID string
}

Common holds the fields every builder takes. Nonce comes from the node (client.Nonce).

type ExitValidator

type ExitValidator struct {
	Common
	ValidatorKey string
}

ExitValidator describes a validator exit.

type FeeEstimate

type FeeEstimate struct {
	Kind      string `json:"kind"`
	Fee       Amount `json:"fee"`
	Rule      string `json:"rule"`
	FeeMarket bool   `json:"feeMarket"`
}

FeeEstimate is janzeer_estimateFee.

type FinalityTimeoutError

type FinalityTimeoutError struct {
	Hash string
	Last *TxView
}

FinalityTimeoutError: the wait deadline passed; Last is the most recent view (possibly nil).

func (*FinalityTimeoutError) Error

func (e *FinalityTimeoutError) Error() string

type FormatOptions

type FormatOptions struct {
	// Decimals to keep (0 means the default 8; use NoDecimals for none). Digits beyond are truncated, never rounded.
	Decimals int
	// KeepZeros keeps trailing zeros instead of trimming them.
	KeepZeros bool
	// NoTicker omits the " JNZ" suffix.
	NoTicker bool
	// Group separates thousands with ",".
	Group bool
}

FormatOptions controls FormatJNZ. The zero value means: 8 decimals, trimmed, with the ticker, ungrouped.

type HDNode

type HDNode struct {
	Priv      []byte
	ChainCode []byte
}

HDNode is an extended private key: a 32-byte private key and a 32-byte chain code.

func DeriveChild

func DeriveChild(node HDNode, index uint32) (HDNode, error)

DeriveChild is the standard BIP32 non-hardened private derivation (index < 2^31).

func DerivePath

func DerivePath(seed []byte, path string) (HDNode, error)

DerivePath derives a path like "m/0/0/0" (non-hardened segments only).

func SeedToMasterKey

func SeedToMasterKey(seed []byte) HDNode

SeedToMasterKey is I = HMAC-SHA512(key = HDSalt, msg = seed): the left half is the key, the right the chain code.

type NetworkError

type NetworkError struct {
	Message string
	Err     error
}

NetworkError: the node could not be reached, the response was not JSON, or the socket died.

func (*NetworkError) Error

func (e *NetworkError) Error() string

func (*NetworkError) Unwrap

func (e *NetworkError) Unwrap() error

type NodeInfo

type NodeInfo struct {
	NodeKey         string `json:"nodeKey"`
	Host            string `json:"host"`
	Port            int    `json:"port"`
	NetworkID       string `json:"networkId"`
	GenesisHash     string `json:"genesisHash"`
	ChainSpecDigest string `json:"chainSpecDigest"`
	Version         string `json:"version"`
	APIVersion      string `json:"apiVersion"`
	ProtocolVersion string `json:"protocolVersion"`
	SyncStatus      string `json:"syncStatus"`
	Faucet          bool   `json:"faucet"`
}

NodeInfo is GET info.

type NonceMismatchError

type NonceMismatchError struct {
	TxRejectedError
	Address string
	// Expected and Got are valid when Known is true (the node's message carried them).
	Expected, Got int64
	Known         bool
}

NonceMismatchError: the nonce is not the sender's next nonce. Refresh it (client.Nonce) and rebuild.

func (*NonceMismatchError) Unwrap

func (e *NonceMismatchError) Unwrap() error

Unwrap lets errors.As(err, **TxRejectedError) match a nonce mismatch too.

type NotFoundError

type NotFoundError struct{ APIError }

NotFoundError: HTTP 404.

func (*NotFoundError) Unwrap

func (e *NotFoundError) Unwrap() error

type NotSynchronizedError

type NotSynchronizedError struct{ Message, Transport string }

NotSynchronizedError: the node is still syncing (REST 400 / RPC -32002). Retry shortly.

func (*NotSynchronizedError) Error

func (e *NotSynchronizedError) Error() string

type Page

type Page[T any] struct {
	Total      int64 `json:"total"`
	List       []T   `json:"list"`
	Page       int   `json:"page"`
	PageSize   int   `json:"pageSize"`
	TotalPages int   `json:"totalPages"`
}

Page is one page of a REST or RPC list.

type RPCError

type RPCError struct {
	Code    int
	Message string
	Data    json.RawMessage
}

RPCError: a JSON-RPC error that is not a transaction rejection. Compare Code with the RPC* constants.

func (*RPCError) Error

func (e *RPCError) Error() string

type RateLimitedError

type RateLimitedError struct {
	Message    string
	RetryAfter time.Duration
	Transport  string
}

RateLimitedError: HTTP 429 / RPC -32004.

func (*RateLimitedError) Error

func (e *RateLimitedError) Error() string

type Receipt

type Receipt struct {
	Successful bool            `json:"successful"`
	Results    json.RawMessage `json:"results"`
}

Receipt is the execution receipt of a committed transaction.

type RegisterValidator

type RegisterValidator struct {
	Common
	// ValidatorKey is the NODE's public key (GET info -> nodeKey), never the wallet's own key.
	ValidatorKey string
	// Amount must equal ValidatorDeposit; it defaults to it.
	Amount string
}

RegisterValidator describes a validator registration.

type SendResult

type SendResult struct {
	Hash   string `json:"hash"`
	Status string `json:"status"`
}

SendResult is the answer of the janzeer_send* methods.

type SignedTx

type SignedTx struct {
	Unsigned *UnsignedTx
	Hash     string
	// Signature is the Base64 DER ECDSA signature over Hash.
	Signature string
	// SenderPublicKey is the compressed secp256k1 public key, hex.
	SenderPublicKey string
}

SignedTx is a signed transaction ready for client.Submit or rpc.Send.

func (*SignedTx) Body

func (s *SignedTx) Body() map[string]any

Body is the JSON body the node's REST endpoints and janzeer_send* methods accept. Amounts are strings.

func (*SignedTx) RESTPath

func (s *SignedTx) RESTPath() string

RESTPath is the path (relative to the API base) that accepts this transaction.

func (*SignedTx) RPCMethod

func (s *SignedTx) RPCMethod() string

RPCMethod is the JSON-RPC method that accepts this transaction.

type Token

type Token struct {
	Common
	TokenID   string // every operation except create
	Symbol    string // create
	Name      string // create
	Decimals  int    // create, 0-18
	Cap       string // create (optional), set-cap
	Amount    string // create (optional initial mint), mint, burn, transfer
	Recipient string // mint (optional, defaults to the sender), transfer
}

Token describes a JZT-1 token operation. Token amounts (Cap, Amount) are integer base units as digit strings, never scaled; Decimals is display-only. Which fields are used depends on the operation.

type TokenOp

type TokenOp byte

TokenOp is a JZT-1 token operation code (the op byte).

const (
	TokenCreate TokenOp = iota
	TokenMint
	TokenBurn
	TokenSetCap
	TokenTransfer
)

Token operations.

func (TokenOp) String

func (o TokenOp) String() string

String is the operation name as the node reports it.

type Transaction

type Transaction struct {
	Hash             string  `json:"hash"`
	Timestamp        int64   `json:"timestamp"`
	Fee              Amount  `json:"fee"`
	Nonce            *int64  `json:"nonce"`
	SenderAddress    string  `json:"senderAddress"`
	SenderPublicKey  string  `json:"senderPublicKey"`
	SenderSignature  string  `json:"senderSignature"`
	BlockHash        *string `json:"blockHash"`
	Amount           *Amount `json:"amount"`
	RecipientAddress *string `json:"recipientAddress"`
	Data             *string `json:"data"`
	ValidatorKey     *string `json:"validatorKey"`
	TokenID          *string `json:"tokenId"`
	// Raw is the complete JSON object, for fields this struct does not name.
	Raw json.RawMessage `json:"-"`
}

Transaction is a transaction as the REST lists and lookups return it. Fields that a type does not have are nil.

func (*Transaction) Final

func (t *Transaction) Final() bool

Final reports whether the transaction is in a committed block.

func (*Transaction) UnmarshalJSON

func (t *Transaction) UnmarshalJSON(b []byte) error

UnmarshalJSON keeps the raw object next to the named fields.

type Transfer

type Transfer struct {
	Common
	To     string
	Amount string
	// Data is an optional memo, at most 256 UTF-8 bytes; with a memo the amount may be below MinTransfer (even "0").
	Data string
}

Transfer describes a native-coin transfer.

type TxRejectedError

type TxRejectedError struct {
	Message string
	// Type is the node's exception type (INCORRECT_SIGNATURE, INSUFFICIENT_BALANCE, …) or UNKNOWN.
	Type string
	// Transport is "rest", "rpc" or "ws".
	Transport  string
	HTTPStatus int
	RPCCode    int
}

TxRejectedError: the node refused a transaction at intake (validation or mempool rule).

func (*TxRejectedError) Error

func (e *TxRejectedError) Error() string

type TxType

type TxType string

TxType names a client-submittable transaction type.

const (
	TxTransfer          TxType = "transfer"
	TxToken             TxType = "token"
	TxRegisterValidator TxType = "registerValidator"
	TxExitValidator     TxType = "exitValidator"
)

Transaction types.

type TxView

type TxView struct {
	Hash string  `json:"hash"`
	Type *string `json:"type"`
	// Status is FINAL, PENDING or UNKNOWN.
	Status           string   `json:"status"`
	Timestamp        *int64   `json:"timestamp"`
	Fee              *Amount  `json:"fee"`
	Nonce            *int64   `json:"nonce"`
	SenderAddress    *string  `json:"senderAddress"`
	SenderPublicKey  *string  `json:"senderPublicKey"`
	SenderSignature  *string  `json:"senderSignature"`
	BlockHash        *string  `json:"blockHash"`
	BlockHeight      *int64   `json:"blockHeight"`
	Receipt          *Receipt `json:"receipt"`
	Amount           *Amount  `json:"amount"`
	RecipientAddress *string  `json:"recipientAddress"`
	Data             *string  `json:"data"`
	ValidatorKey     *string  `json:"validatorKey"`
	Op               *string  `json:"op"`
	TokenID          *string  `json:"tokenId"`
	Symbol           *string  `json:"symbol"`
	Name             *string  `json:"name"`
	Decimals         *int     `json:"decimals"`
	Cap              *Amount  `json:"cap"`
	TokenAmount      *Amount  `json:"tokenAmount"`
	Recipient        *string  `json:"recipient"`
	TimedOut         bool     `json:"timedOut"`
}

TxView is the unified view of any transaction (janzeer_getTransactionByHash, waitForFinality, subscriptions).

type UnsignedTx

type UnsignedTx struct {
	Type          TxType
	NetworkID     string
	Timestamp     int64 // ms since epoch
	Fee           string
	Nonce         int64
	SenderAddress string
	// Fields are the type-specific fields exactly as they go into the request body.
	Fields map[string]any
	// Payload is the type-specific part of the signed bytes.
	Payload []byte
}

UnsignedTx is a transaction that is fully specified but not yet signed. Sign it with Account.SignTx.

func NewExitValidator

func NewExitValidator(o ExitValidator) (*UnsignedTx, error)

NewExitValidator builds a graceful validator exit (removed at the next epoch; the deposit stays locked).

func NewRegisterValidator

func NewRegisterValidator(o RegisterValidator) (*UnsignedTx, error)

NewRegisterValidator builds a validator registration: the exact ValidatorFee and the NON-REFUNDABLE ValidatorDeposit.

func NewTokenBurn

func NewTokenBurn(o Token) (*UnsignedTx, error)

NewTokenBurn builds a BURN (issuer only).

func NewTokenCreate

func NewTokenCreate(o Token) (*UnsignedTx, error)

NewTokenCreate builds a token CREATE; the new token id is the transaction hash. The fee is exactly TokenCreateFee.

func NewTokenMint

func NewTokenMint(o Token) (*UnsignedTx, error)

NewTokenMint builds a MINT (issuer only); Recipient defaults to the sender.

func NewTokenSetCap

func NewTokenSetCap(o Token) (*UnsignedTx, error)

NewTokenSetCap builds a SETCAP (issuer only).

func NewTokenTransfer

func NewTokenTransfer(o Token) (*UnsignedTx, error)

NewTokenTransfer builds a token TRANSFER.

func NewTransfer

func NewTransfer(o Transfer) (*UnsignedTx, error)

NewTransfer builds a native-coin transfer. The fee defaults to MinFee.

func (*UnsignedTx) Hash

func (t *UnsignedTx) Hash() string

Hash is double-SHA256 of the preimage, lowercase hex: the transaction id.

func (*UnsignedTx) Preimage

func (t *UnsignedTx) Preimage() []byte

Preimage returns the exact bytes that are hashed and signed: networkId || timestamp(8) || scaled(fee)(8) || nonce(8) || senderAddress || payload.

func (*UnsignedTx) WithSignature

func (t *UnsignedTx) WithSignature(signatureBase64, senderPublicKeyHex string) *SignedTx

WithSignature attaches a signature made elsewhere (hardware wallet, KMS). Prefer Account.SignTx.

type ValidationError

type ValidationError struct {
	APIError
	Messages []string
}

ValidationError: request-body validation failed (HTTP 400 with a list of messages).

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

type Validator

type Validator struct {
	Address string `json:"address"`
	NodeKey string `json:"nodeKey"`
}

Validator is an entry of the REST validator lists.

type ValidatorInfo

type ValidatorInfo struct {
	Key           string  `json:"key"`
	WalletAddress *string `json:"walletAddress"`
	RegisteredAt  *int64  `json:"registeredAt"`
	Active        *bool   `json:"active"`
	Banned        *bool   `json:"banned"`
	Exited        *bool   `json:"exited"`
}

ValidatorInfo is an entry of the JSON-RPC validator methods.

Directories

Path Synopsis
Package client is the client of the node's REST API (/api/v1/).
Package client is the client of the node's REST API (/api/v1/).
examples
quickstart command
Send a transfer and wait until it is final.
Send a transfer and wait until it is final.
subscribe command
Watch an address over the WebSocket, send it a transfer, and print the notification.
Watch an address over the WebSocket, send it a transfer, and print the notification.
token command
Create a JZT-1 token, then move some units.
Create a JZT-1 token, then move some units.
validator command
Register (and later exit) a validator node.
Register (and later exit) a validator node.
vault command
Seal a recovery phrase under a password and open it again.
Seal a recovery phrase under a password and open it again.
watchblocks command
Watch newly finalized blocks over the WebSocket and print their height, hash and transaction count.
Watch newly finalized blocks over the WebSocket and print their height, hash and transaction count.
internal
vectors
Package vectors embeds the vendored conformance vectors (a copy of janzeer-sdk-conformance/vectors, checked by SHA256SUMS) for the tests of this module.
Package vectors embeds the vendored conformance vectors (a copy of janzeer-sdk-conformance/vectors, checked by SHA256SUMS) for the tests of this module.
Package rpc is the JSON-RPC 2.0 client of the node: over HTTP (Client, POST /rpc) and over WebSocket (WS, /rpc/ws) with live subscriptions.
Package rpc is the JSON-RPC 2.0 client of the node: over HTTP (Client, POST /rpc) and over WebSocket (WS, /rpc/ws) with live subscriptions.
Package vault seals a secret under a password: PBKDF2-HMAC-SHA256 (250,000 rounds) -> AES-256-GCM.
Package vault seals a secret under a password: PBKDF2-HMAC-SHA256 (250,000 rounds) -> AES-256-GCM.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL