hivego

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 18 Imported by: 0

README

hivego

A Go client library for the Hive blockchain.

Installation

go get github.com/cadawg/hivego

Quick Start

import "github.com/cadawg/hivego"

// Single node
client := hivego.NewClient("https://api.hive.blog")

// Multiple nodes — automatically fails over to the next on error
client := hivego.NewClient(
    "https://api.hive.blog",
    "https://rpc.ecency.com",
    "https://api.deathwing.me",
)

The client exposes two namespaces:

  • client.Broadcast — submit signed operations to the blockchain
  • client.Database — read data from the blockchain

Keys

All broadcast operations take a *KeyPair. Create one from a WIF string once and reuse it:

key, err := hivego.KeyPairFromWif("5J...")
if err != nil {
    log.Fatal(err)
}

You can also create one from raw bytes:

key, err := hivego.KeyPairFromBytes(privKeyBytes)

Broadcasting Operations

All broadcast methods return (*Transaction, string, error) — the signed transaction object, the transaction ID, and any error. If you only need the txid, use _ for the transaction:

_, txid, err := client.Broadcast.Vote(...)
Vote
_, txid, err := client.Broadcast.Vote("voter", "author", "permlink", 10000, key)

weight ranges from -10000 (100% downvote) to 10000 (100% upvote).

Transfer
amount, _ := hivego.ParseAsset("1.000 HIVE")
_, txid, err := client.Broadcast.Transfer("sender", "receiver", amount, "memo", key)
Custom JSON
// Active key action (required_auths)
_, txid, err := client.Broadcast.CustomJson([]string{"myaccount"}, []string{}, "app-id", `{"key":"value"}`, activeKey)

// Posting key action (required_posting_auths)
_, txid, err := client.Broadcast.CustomJson([]string{}, []string{"myaccount"}, "app-id", `{"key":"value"}`, postingKey)
Claim Rewards
hive,  _ := hivego.ParseAsset("0.000 HIVE")
hbd,   _ := hivego.ParseAsset("0.000 HBD")
vests, _ := hivego.ParseAsset("1234.567890 VESTS")
_, txid, err := client.Broadcast.ClaimRewards("myaccount", hive, hbd, vests, key)
Post / Comment
// Top-level post (parentAuthor = "")
_, txid, err := client.Broadcast.Comment(
    "", "hive-blog",       // parentAuthor, parentPermlink (category for top-level posts)
    "alice", "my-post",   // author, permlink
    "Hello World",        // title
    "This is my post.",   // body (markdown)
    `{"tags":["blog"]}`,  // json_metadata
    postingKey,
)

// Reply to a post
_, txid, err := client.Broadcast.Comment(
    "bob", "bobs-post",   // parentAuthor, parentPermlink
    "alice", "re-bobs-post",
    "", "Great post!",    // title is empty for replies
    "{}",
    postingKey,
)

// Delete a post (must have no replies, no payout, no net votes)
_, txid, err := client.Broadcast.DeleteComment("alice", "my-post", postingKey)
Post with Beneficiaries

comment_options must be in the same transaction as the comment it targets. Use BroadcastOps:

maxPayout, _ := hivego.ParseAsset("1000000.000 HBD") // no limit

ops := []hivego.HiveOperation{
    hivego.CommentOperation{
        Author: "alice", Permlink: "my-post",
        ParentPermlink: "hive-blog", Title: "Hello", Body: "...",
        JsonMetadata: `{"tags":["blog"]}`,
    },
    hivego.CommentOptionsOperation{
        Author: "alice", Permlink: "my-post",
        MaxAcceptedPayout:    maxPayout,
        PercentHbd:           10000, // 100% HBD rewards
        AllowVotes:           true,
        AllowCurationRewards: true,
        Beneficiaries: []hivego.Beneficiary{
            {Account: "appdev", Weight: 500}, // 5%
        },
    },
}

_, txid, err := client.BroadcastOps(ops, postingKey)
Hive Power
// Power up (HIVE → HP)
amount, _ := hivego.ParseAsset("100.000 HIVE")
_, txid, err := client.Broadcast.PowerUp("alice", "alice", amount, activeKey)

// Power down (HP → HIVE over 13 weeks)
vests, _ := hivego.ParseAsset("100000.000000 VESTS")
_, txid, err := client.Broadcast.PowerDown("alice", vests, activeKey)

// Cancel power-down
zero, _ := hivego.ParseAsset("0.000000 VESTS")
_, txid, err := client.Broadcast.PowerDown("alice", zero, activeKey)

// Delegate HP to another account
vests, _ := hivego.ParseAsset("50000.000000 VESTS")
_, txid, err := client.Broadcast.Delegate("alice", "bob", vests, activeKey)

// Remove delegation
zero, _ := hivego.ParseAsset("0.000000 VESTS")
_, txid, err := client.Broadcast.Delegate("alice", "bob", zero, activeKey)
Witnesses
// Vote for a witness
_, txid, err := client.Broadcast.VoteWitness("alice", "good-witness", true, activeKey)

// Remove witness vote
_, txid, err := client.Broadcast.VoteWitness("alice", "good-witness", false, activeKey)
Savings
// Move funds to savings (3-day withdrawal delay)
amount, _ := hivego.ParseAsset("100.000 HBD")
_, txid, err := client.Broadcast.TransferToSavings("alice", "alice", amount, "", activeKey)

// Initiate savings withdrawal (requestId must be unique per account)
_, txid, err := client.Broadcast.TransferFromSavings("alice", 1, "alice", amount, "", activeKey)

// Cancel a pending savings withdrawal
_, txid, err := client.Broadcast.CancelTransferFromSavings("alice", 1, activeKey)
Vesting Routes
// Route 50% of power-down to another account, auto-powering it up there
_, txid, err := client.Broadcast.SetWithdrawRoute("alice", "bob", 5000, true, activeKey)

// Remove a route (set percent to 0)
_, txid, err := client.Broadcast.SetWithdrawRoute("alice", "bob", 0, false, activeKey)
Recurrent Transfers
// Send 10 HIVE every 24 hours, 7 times
amount, _ := hivego.ParseAsset("10.000 HIVE")
_, txid, err := client.Broadcast.RecurrentTransfer("alice", "bob", amount, "weekly payment", 24, 7, activeKey)

// Cancel a recurrent transfer (set amount to 0)
zero, _ := hivego.ParseAsset("0.000 HIVE")
_, txid, err := client.Broadcast.RecurrentTransfer("alice", "bob", zero, "", 24, 2, activeKey)
Account Update
// Update profile and posting metadata
_, txid, err := client.Broadcast.UpdateAccount(
    "alice",
    `{"profile":{"name":"Alice","about":"Hive user"}}`,
    `{"tags":["hive","blog"]}`,
    postingKey,
)

For authority or memo key changes, construct AccountUpdate2Operation directly and use BroadcastOps. All authority fields and MemoKey are optional — set to nil to leave unchanged:

newKey, _ := hivego.KeyPairFromWif("5J...")

// Rotate the active key
_, txid, err := client.BroadcastOps([]hivego.HiveOperation{
    hivego.AccountUpdate2Operation{
        Account: "alice",
        Active: &hivego.Authority{
            WeightThreshold: 1,
            KeyAuths: []hivego.KeyAuth{
                {Key: newKey.PublicKey, Weight: 1},
            },
        },
    },
}, activeKey)

// Add a co-signer to the posting authority (2-of-2 multisig)
_, txid, err := client.BroadcastOps([]hivego.HiveOperation{
    hivego.AccountUpdate2Operation{
        Account: "alice",
        Posting: &hivego.Authority{
            WeightThreshold: 2,
            KeyAuths: []hivego.KeyAuth{
                {Key: alicePostingKey.PublicKey, Weight: 1},
                {Key: bobPostingKey.PublicKey, Weight: 1},
            },
        },
    },
}, activeKey)
Conversions
// Convert HBD to HIVE (3.5-day process, requestId must be unique per account)
hbd, _ := hivego.ParseAsset("100.000 HBD")
_, txid, err := client.Broadcast.Convert("alice", 1, hbd, activeKey)

// Convert HIVE to HBD instantly using collateral
hive, _ := hivego.ParseAsset("100.000 HIVE")
_, txid, err := client.Broadcast.CollateralizedConvert("alice", 1, hive, activeKey)
Limit Orders
// Place a limit order: sell 10 HIVE for at least 9 HBD, expires in 1 hour
sell, _ := hivego.ParseAsset("10.000 HIVE")
buy,  _ := hivego.ParseAsset("9.000 HBD")
_, txid, err := client.Broadcast.LimitOrderCreate("alice", 1, sell, buy, false, "2026-01-01T12:00:00", activeKey)

// Cancel an open order
_, txid, err := client.Broadcast.LimitOrderCancel("alice", 1, activeKey)
Witness Proxy
// Delegate all witness votes to a proxy
_, txid, err := client.Broadcast.SetWitnessProxy("alice", "my-proxy", activeKey)

// Remove proxy
_, txid, err := client.Broadcast.SetWitnessProxy("alice", "", activeKey)
DHF Proposals
// Create a funding proposal (dailyPay must be HBD)
dailyPay, _ := hivego.ParseAsset("100.000 HBD")
_, txid, err := client.Broadcast.CreateProposal(
    "alice", "alice",
    "2026-01-01T00:00:00", "2026-06-01T00:00:00",
    dailyPay,
    "My Proposal", "my-proposal-post",
    activeKey,
)

// Vote for proposals
_, txid, err := client.Broadcast.UpdateProposalVotes("alice", []int64{0, 1, 2}, true, activeKey)

// Remove votes
_, txid, err := client.Broadcast.UpdateProposalVotes("alice", []int64{0}, false, activeKey)

// Update a proposal (pass "" for endDate to leave it unchanged)
_, txid, err := client.Broadcast.UpdateProposal(0, "alice", dailyPay, "Updated Subject", "my-proposal-post", "", activeKey)

// Remove a proposal (creator only)
_, txid, err := client.Broadcast.RemoveProposal("alice", []int64{0}, activeKey)
Account Creation
// Claim an account creation token using RC (free, but costs RC)
zero, _ := hivego.ParseAsset("0.000 HIVE")
_, txid, err := client.Broadcast.ClaimAccount("alice", zero, activeKey)

// Claim using a HIVE fee instead
fee, _ := hivego.ParseAsset("3.000 HIVE")
_, txid, err := client.Broadcast.ClaimAccount("alice", fee, activeKey)

// Create a new account with a HIVE fee
fee, _ = hivego.ParseAsset("3.000 HIVE")
ownerKey, _ := hivego.KeyPairFromWif("5J...")
owner := hivego.Authority{WeightThreshold: 1, KeyAuths: []hivego.KeyAuth{{Key: ownerKey.PublicKey, Weight: 1}}}
_, txid, err = client.Broadcast.CreateAccount(fee, "alice", "newaccount", owner, owner, owner, ownerKey.PublicKey, "{}", activeKey)

// Create a new account from a claimed token (no fee)
_, txid, err = client.Broadcast.CreateClaimedAccount("alice", "newaccount", owner, owner, owner, ownerKey.PublicKey, "{}", activeKey)
Witness Management
// Register or update a witness
fee, _ := hivego.ParseAsset("0.000 HIVE")
props := hivego.ChainProperties{
    AccountCreationFee: func() hivego.Asset { a, _ := hivego.ParseAsset("3.000 HIVE"); return a }(),
    MaximumBlockSize:   131072,
    HbdInterestRate:    1000, // 10%
}
signingKey, _ := hivego.KeyPairFromWif("5J...")
_, txid, err := client.Broadcast.UpdateWitness("alice", "https://mywitness.com", signingKey.PublicKey, props, fee, activeKey)

// Disable a witness (set signing key to nil → 33 zero bytes)
_, txid, err = client.Broadcast.UpdateWitness("alice", "https://mywitness.com", nil, props, fee, activeKey)

// Modern witness_set_properties (preferred for active witnesses)
import "encoding/binary"
keyBuf := make([]byte, 2)
binary.LittleEndian.PutUint16(keyBuf, 1000) // hbd_interest_rate = 10%
_, txid, err = client.Broadcast.WitnessSetProperties("alice", map[string][]byte{
    "hbd_interest_rate": keyBuf,
    "key": signingKey.PublicKey.SerializeCompressed(),
}, activeKey)
Publish Price Feed
// Witnesses only: publish a HIVE/HBD price feed
base, _  := hivego.ParseAsset("1.000 HBD")
quote, _ := hivego.ParseAsset("3.500 HIVE")
_, txid, err := client.Broadcast.FeedPublish("mywitness", base, quote, witnessKey)
Account Recovery
// Step 1: recovery account submits the new owner authority
newOwner := hivego.Authority{WeightThreshold: 1, KeyAuths: []hivego.KeyAuth{{Key: newKey.PublicKey, Weight: 1}}}
_, txid, err := client.Broadcast.RequestAccountRecovery("recovery-account", "lost-account", newOwner, recoveryKey)

// Step 2: lost account owner completes recovery (sign with BOTH new and a recent old owner key)
recentOwner := hivego.Authority{WeightThreshold: 1, KeyAuths: []hivego.KeyAuth{{Key: oldKey.PublicKey, Weight: 1}}}
tx, err := client.BuildTransaction([]hivego.HiveOperation{
    hivego.RecoverAccountOperation{"lost-account", newOwner, recentOwner},
})
client.Sign(tx, newKey)
client.Sign(tx, oldKey)
client.BroadcastTx(tx)

// Change recovery account (takes 30 days to take effect)
_, txid, err = client.Broadcast.ChangeRecoveryAccount("alice", "new-recovery-acct", ownerKey)
Escrow
// Step 1: lock funds with an agent
hbd,  _ := hivego.ParseAsset("100.000 HBD")
zero, _ := hivego.ParseAsset("0.000 HIVE")
fee,  _ := hivego.ParseAsset("1.000 HBD")
_, txid, err := client.Broadcast.EscrowTransfer(
    "alice", "bob", "agent",
    1,                    // escrow ID
    hbd, zero, fee,
    "2026-04-01T00:00:00", // ratification deadline
    "2026-06-01T00:00:00", // escrow expiration
    `{}`,
    activeKey,
)

// Step 2a: to-party or agent approves
_, txid, err = client.Broadcast.EscrowApprove("alice", "bob", "agent", "bob", 1, true, bobKey)

// Step 2b: raise a dispute (hands release authority to the agent)
_, txid, err = client.Broadcast.EscrowDispute("alice", "bob", "agent", "bob", 1, bobKey)

// Step 3: release funds to bob
_, txid, err = client.Broadcast.EscrowRelease("alice", "bob", "agent", "agent", "bob", 1, hbd, zero, agentKey)
Custom

custom_operation broadcasts an integer-keyed operation with arbitrary string data, authorized by active keys.

_, txid, err := client.Broadcast.Custom([]string{"myaccount"}, 42, "my data", activeKey)
Custom Binary

custom_binary_operation broadcasts raw binary data with full authority control (owner, active, posting, and authority objects). The Id field is a short string (< 32 chars); Data is arbitrary bytes.

// Simple case — no authority restrictions
_, txid, err := client.Broadcast.CustomBinary(nil, nil, nil, nil, "myapp", []byte{0x01, 0x02}, activeKey)

// With active-key restriction
_, txid, err = client.Broadcast.CustomBinary(
    nil,                    // requiredOwnerAuths
    []string{"myaccount"}, // requiredActiveAuths
    nil,                    // requiredPostingAuths
    nil,                    // requiredAuths (Authority objects)
    "myapp", []byte{0xde, 0xad, 0xbe, 0xef},
    activeKey,
)
Decline Voting Rights

Declining voting rights is permanent and irreversible. There is no convenience method for this path — you must construct the operation directly to make the intent unambiguous:

// PERMANENT — the account can never vote again
_, txid, err := client.BroadcastOps([]hivego.HiveOperation{
    hivego.DeclineVotingRightsOperation{
        Account: "alice",
        Decline: true,
        IUnderstandThisIsIrreversible: true,
    },
}, ownerKey)

// Cancel a pending (not yet effective) decline request
_, txid, err = client.Broadcast.CancelDeclineVotingRights("alice", ownerKey)

Multi-Operation Transactions

To combine multiple operations in one transaction, use BroadcastOps directly:

key, _ := hivego.KeyPairFromWif("5J...")

ops := []hivego.HiveOperation{
    hivego.CommentOperation{
        Author: "alice", Permlink: "my-post",
        ParentPermlink: "hive-blog", Title: "Hello", Body: "...",
        JsonMetadata: `{"tags":["blog"]}`,
    },
    hivego.CommentOptionsOperation{
        Author: "alice", Permlink: "my-post",
        MaxAcceptedPayout:    maxPayout,
        PercentHbd:           10000,
        AllowVotes:           true,
        AllowCurationRewards: true,
    },
}

tx, txid, err := client.BroadcastOps(ops, key)
Advanced: Offline Signing and Multi-sig

For offline signing, multi-sig, or other workflows where you need control over each step, use BuildTransaction, Sign, and BroadcastTx separately:

tx, err := client.BuildTransaction(ops)
if err != nil { ... }

// sign with multiple keys for multi-sig operations
if err := client.Sign(tx, activeKey); err != nil { ... }
if err := client.Sign(tx, postingKey); err != nil { ... }

txid, _ := tx.GenerateTrxId()
if err := client.BroadcastTx(tx); err != nil { ... }
Implementing Your Own Operation Type

Implement HiveOperation to broadcast operations not yet built into the library:

type MyOperation struct {
    Account string `json:"account"`
}

func (o MyOperation) OpName() string               { return "my_operation_name" }
func (o MyOperation) SerializeOp() ([]byte, error) { /* binary serialization */ }

Reading Chain Data

Get a Block
block, err := client.Database.GetBlock(88000000)
fmt.Println(block.Timestamp, block.Witness)
// block.Transactions is []json.RawMessage — unmarshal individual transactions as needed
Stream Blocks
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

blocks, errc := client.Database.StreamBlocks(ctx, 88000000, 3*time.Second)
for block := range blocks {
    fmt.Println(block.BlockID, block.Timestamp)
}
if err := <-errc; err != nil {
    log.Fatal(err)
}
Get Accounts
accounts, err := client.Database.GetAccounts([]string{"alice", "bob"})
for _, acc := range accounts {
    fmt.Println(acc.Name, acc.Balance)
    bal, _ := hivego.ParseAsset(acc.Balance)
    fmt.Println(bal) // "1.500 HIVE"
}
Get a Transaction
raw, err := client.Database.GetTransaction("abc123...", true)
Raw Block Range (bulk processing)
// Returns raw bytes — fastest option for high-throughput block processing
rawBlocks, err := client.Database.GetBlockRangeFast(startBlock, count)

// Returns parsed json.RawMessage
blocks, err := client.Database.GetBlockRange(startBlock, count)

Warning: Do not run bulk block fetching against public API nodes at high rates. Run your own node for block processing workloads.

Asset Handling

Assets are parsed explicitly rather than accepted as raw strings. This is required because transactions are binary-serialized locally before signing, and the serialization needs the amount, precision, and symbol as separate fields.

a, err := hivego.ParseAsset("1.500 HIVE")
fmt.Println(a.Amount)    // 1500  (3 decimal places for HIVE/HBD, 6 for VESTS)
fmt.Println(a.Precision) // 3
fmt.Println(a.Symbol)    // "HIVE"
fmt.Println(a.String())  // "1.500 HIVE"

Error Handling

All errors are sentinel values so you can use errors.Is and errors.As:

key, err := hivego.KeyPairFromWif(wif)
if errors.Is(err, hivego.ErrInvalidFormat) {
    // bad WIF string
}
if errors.Is(err, hivego.ErrChecksumMismatch) {
    // WIF decoded but checksum failed
}

_, err = hivego.ParseAsset("bad input")
if errors.Is(err, hivego.ErrInvalidAsset) {
    // not a valid asset string
}

// RPC errors expose the node's error code and message
_, err = client.Database.GetBlock(0)
var rpcErr *hivego.RPCError
if errors.As(err, &rpcErr) {
    fmt.Println(rpcErr.Code, rpcErr.Message)
}

Available sentinels: ErrNilKey, ErrInvalidKeyLength, ErrInvalidPrefix, ErrInvalidPublicKey, ErrChecksumMismatch, ErrInvalidFormat, ErrInvalidAsset.

Public Key Utilities

// Encode/decode public keys
pubKeyStr := key.GetPublicKeyString()              // "STM7..."
pubKey, err := hivego.DecodePublicKey("STM7...")

// Graphene base58 encode/decode (for advanced use)
payload, version, err := hivego.GphBase58CheckDecode(wif)
encoded := hivego.GphBase58Encode(payload, version)

Message Signing

Many Hive services use signed messages for login/authentication (Keychain, HiveSigner, etc.). The digest is SHA256(message), and the signature is a 65-byte compact recoverable signature.

key, _ := hivego.KeyPairFromWif("5J...")

// Sign a message
sig, err := hivego.SignMessage([]byte("login-token"), key)

// Recover the public key from a signature
pubKey, err := hivego.RecoverMessageSigner([]byte("login-token"), sig)

// Verify by comparing against an account's posting keys
accounts, _ := client.Database.GetAccounts([]string{"alice"})
recoveredStr := hivego.GetPublicKeyStringWithPrefix(pubKey, client.PublicKeyPrefix)
for _, keyAuth := range accounts[0].Posting.KeyAuths {
    if keyAuth[0].(string) == recoveredStr {
        // valid
    }
}

Keychain and other services encode the signature as hex for transport:

import "encoding/hex"
hexSig := hex.EncodeToString(sig)
sigBytes, _ := hex.DecodeString(hexSig)

Testnet / Custom Chain

client := hivego.NewClient("https://testnet.openhive.network")
client.ChainID = "18dcf0a285365fc58b71f18b3d3fec954aa0c141c44e4e5cb4cf777b9eab274e"
client.PublicKeyPrefix = "TST"

// Decode testnet public keys
pubKey, err := hivego.DecodePublicKeyWithPrefix("TST7...", "TST")
str := hivego.GetPublicKeyStringWithPrefix(pubKey, "TST")

Dry-run / Inspecting Transactions

WithNoBroadcast enables dry-run mode: transactions are built and signed but not submitted. The returned *Transaction can be inspected, logged, or serialized:

client := hivego.NewClient("https://api.hive.blog").WithNoBroadcast()

tx, txid, err := client.Broadcast.Vote("voter", "author", "permlink", 10000, key)

// predicted transaction ID
fmt.Println(txid)

// signatures
fmt.Println(tx.Signatures)

// binary wire representation (what the node verifies the signature against)
b, err := tx.Serialize()
fmt.Printf("%x\n", b)

// JSON representation (what is sent to the node)
json.NewEncoder(os.Stdout).Encode(tx)

Client Options

All fields are public and can be set after construction:

client := hivego.NewClient("https://api.hive.blog")
client.MaxConn     = 4     // max concurrent HTTP connections per node (default 1)
client.MaxBatch    = 8     // max requests per batch RPC call (default 4)
client.NoBroadcast = true  // dry-run mode: sign but don't submit transactions

Comparison with Other Libraries

Concept hivego Beem (Python) dhive (TypeScript)
Client Client Hive Client
Multi-node failover NewClient("node1", "node2", ...) NodeList new Client(["node1", "node2"])
Keys KeyPairFromWif("5J...") WIF string PrivateKey.fromString("5J...")
Vote client.Broadcast.Vote(..., key) hive.commit.vote(...) client.broadcast.vote(...)
Custom JSON client.Broadcast.CustomJson(..., key) hive.commit.custom_json(...) client.broadcast.customJson(...)
Custom client.Broadcast.Custom(..., key) hive.commit.custom(...)
Custom Binary client.Broadcast.CustomBinary(..., key) hive.commit.custom_binary(...)
Read block client.Database.GetBlock(...) hive.get_block(...) client.database.getBlock(...)
Read account client.Database.GetAccounts(...) Account(name) client.database.getAccounts(...)
Multi-op tx BroadcastOps(ops, key) TransactionBuilder client.broadcast.sendOperations(...)
Custom ops implement HiveOperation extend Operation implement Operation
Block streaming client.Database.StreamBlocks(ctx, ...) blockchain.stream_from(...) loop over getBlock(...)

Testing

The library has 80%+ test coverage across unit and integration suites.

# Unit tests
go test ./...

# Integration tests (requires network)
go test -tags integration ./...

# Coverage report for both
bash scripts/coverage.sh

Documentation

Overview

Package hivego is a Go client library for the Hive blockchain (https://hive.io).

It provides:

  • Signing and broadcasting transactions (vote, transfer, custom_json, and 40+ other operations)
  • Reading chain data (blocks, accounts, dynamic global properties)
  • Binary serialization of Hive operations for local signing
  • Key management (WIF import, secp256k1 key pairs, public key encoding/decoding)

Quick start

client := hivego.NewClient("https://api.hive.blog")

key, err := hivego.KeyPairFromWif("5J...")

_, txid, err := client.Broadcast.Vote("voter", "author", "permlink", 10000, key)

block, err := client.Database.GetBlock(88000000)

Multiple nodes and failover

Pass multiple node addresses to NewClient. Requests are tried against each node in order and fall through to the next on error:

client := hivego.NewClient(
    "https://api.hive.blog",
    "https://rpc.ecency.com",
    "https://api.deathwing.me",
)

Broadcasting operations

All broadcast methods on BroadcastAPI return (*Transaction, string, error) — the signed transaction, the predicted transaction ID, and any error. Use _ to discard the transaction when you only need the txid:

_, txid, err := client.Broadcast.Transfer("alice", "bob", amount, "memo", key)

To combine multiple operations in one transaction, use Client.BroadcastOps directly:

ops := []hivego.HiveOperation{commentOp, commentOptionsOp}
_, txid, err := client.BroadcastOps(ops, postingKey)

Dry-run mode

Client.WithNoBroadcast enables dry-run mode: transactions are built and signed but not submitted to the network. Useful for testing, fee estimation, and offline signing:

client := hivego.NewClient("https://api.hive.blog").WithNoBroadcast()
tx, txid, err := client.Broadcast.Vote(...)
b, _ := tx.Serialize() // inspect the binary wire format

Assets

Use ParseAsset to create Asset values — the binary serializer requires the amount, precision, and symbol as separate fields, so raw strings are not accepted:

amount, err := hivego.ParseAsset("1.000 HIVE")

Testnet

client := hivego.NewClient("https://testnet.openhive.network")
client.ChainID = "18dcf0a285365fc58b71f18b3d3fec954aa0c141c44e4e5cb4cf777b9eab274e"
client.PublicKeyPrefix = "TST"

Error handling

All errors are sentinel values — use errors.Is for specific conditions and errors.As to extract structured RPC errors:

var rpcErr *hivego.RPCError
if errors.As(err, &rpcErr) {
    fmt.Println(rpcErr.Code, rpcErr.Message)
}

Index

Constants

View Source
const HiveMainnetChainID = "beeab0de00000000000000000000000000000000000000000000000000000000"

HiveMainnetChainID is the chain ID for Hive mainnet.

Variables

View Source
var (
	// ErrNilKey is returned when a nil *KeyPair is passed to Sign or a broadcast method.
	ErrNilKey = errors.New("key must not be nil")
	// ErrNilMemoKey is returned when a nil memo public key is passed to an operation that requires one.
	ErrNilMemoKey = errors.New("memo key must not be nil")
	// ErrInvalidKeyLength is returned by [KeyPairFromBytes] when the input is not exactly 32 bytes.
	ErrInvalidKeyLength = errors.New("private key must be 32 bytes")
	// ErrInvalidPrefix is returned by [DecodePublicKeyWithPrefix] when the key string does not start with the expected prefix.
	ErrInvalidPrefix = errors.New("invalid public key prefix")
	// ErrInvalidPublicKey is returned when the public key bytes cannot be parsed.
	ErrInvalidPublicKey = errors.New("invalid public key")
	// ErrChecksumMismatch is returned when a WIF or public key checksum does not match.
	ErrChecksumMismatch = errors.New("checksum mismatch")
	// ErrInvalidFormat is returned when a WIF string is too short or malformed.
	ErrInvalidFormat = errors.New("invalid format")
	// ErrInvalidAsset is returned by [ParseAsset] when the input string cannot be parsed.
	ErrInvalidAsset = errors.New("invalid asset")

	// ErrInvalidSignature is returned when a signature cannot be decoded or recovery fails.
	ErrInvalidSignature = errors.New("invalid signature")

	// ErrDeclineVotingRightsNotConfirmed is returned when [DeclineVotingRightsOperation].Decline
	// is true but IUnderstandThisIsIrreversible is not set. Declining voting rights permanently
	// removes the account's ability to vote and cannot be undone.
	ErrDeclineVotingRightsNotConfirmed = errors.New("set IUnderstandThisIsIrreversible: true to confirm — declining voting rights is permanent and cannot be undone")
)

Sentinel errors returned by hivego functions. Use errors.Is to check for a specific condition and errors.As to extract a structured RPCError.

View Source
var PublicKeyPrefix = "STM"

PublicKeyPrefix is the package-level default prefix for public key strings (e.g. "STM7..."). This is used by GetPublicKeyString and DecodePublicKey. Override per-client via Client.PublicKeyPrefix; set to "TST" for the Hive public testnet.

Functions

func DecodePublicKey

func DecodePublicKey(pubKey string) (*secp256k1.PublicKey, error)

DecodePublicKey decodes a Hive public key string (e.g. "STM7...") to a secp256k1 public key. Uses the package-level PublicKeyPrefix; for a different prefix use DecodePublicKeyWithPrefix.

func DecodePublicKeyWithPrefix

func DecodePublicKeyWithPrefix(pubKey, prefix string) (*secp256k1.PublicKey, error)

DecodePublicKeyWithPrefix decodes a Hive public key string with a specific prefix (e.g. "TST").

func GetPublicKeyString

func GetPublicKeyString(pubKey *secp256k1.PublicKey) string

GetPublicKeyString returns the Hive public key string for a secp256k1 public key. Uses the package-level PublicKeyPrefix.

func GetPublicKeyStringWithPrefix

func GetPublicKeyStringWithPrefix(pubKey *secp256k1.PublicKey, prefix string) string

GetPublicKeyStringWithPrefix returns the Hive public key string with a specific prefix.

func GphBase58CheckDecode

func GphBase58CheckDecode(input string) ([]byte, [1]byte, error)

GphBase58CheckDecode decodes a Graphene/Hive base58-encoded string with a double-SHA256 checksum. Returns the payload bytes, the version byte, and any error.

func GphBase58Encode

func GphBase58Encode(payload []byte, version [1]byte) string

GphBase58Encode encodes a payload with a version byte into a Graphene/Hive base58 string with a double-SHA256 checksum. This is the inverse of GphBase58CheckDecode.

func RecoverMessageSigner added in v0.1.5

func RecoverMessageSigner(message, sig []byte) (*secp256k1.PublicKey, error)

RecoverMessageSigner recovers the secp256k1 public key that produced sig over message. sig must be a 65-byte compact signature as returned by SignMessage or Hive Keychain. Returns ErrInvalidSignature if recovery fails.

func SignDigest

func SignDigest(digest []byte, key *KeyPair) []byte

SignDigest signs a digest with the given KeyPair using secp256k1 compact signing.

func SignMessage added in v0.1.5

func SignMessage(message []byte, key *KeyPair) ([]byte, error)

SignMessage signs an arbitrary message and returns a 65-byte compact signature. The digest is SHA256(message), matching the convention used by Hive Keychain and similar services for login-by-signature authentication.

Types

type AccountAuth

type AccountAuth struct {
	Account string
	Weight  uint16
}

AccountAuth is an account name paired with a weight for use in an Authority.

type AccountCreateOperation

type AccountCreateOperation struct {
	Fee            Asset                `json:"-"`
	Creator        string               `json:"-"`
	NewAccountName string               `json:"-"`
	Owner          Authority            `json:"-"`
	Active         Authority            `json:"-"`
	Posting        Authority            `json:"-"`
	MemoKey        *secp256k1.PublicKey `json:"-"`
	JsonMetadata   string               `json:"-"`
}

AccountCreateOperation creates a new account with a HIVE fee. All authority fields and MemoKey are required.

func (AccountCreateOperation) MarshalJSON

func (o AccountCreateOperation) MarshalJSON() ([]byte, error)

func (AccountCreateOperation) OpName

func (o AccountCreateOperation) OpName() string

func (AccountCreateOperation) SerializeOp

func (o AccountCreateOperation) SerializeOp() ([]byte, error)

type AccountData

type AccountData struct {
	ID                            uint32        `json:"id"`
	Name                          string        `json:"name"`
	Owner                         AuthorityData `json:"owner"`
	Active                        AuthorityData `json:"active"`
	Posting                       AuthorityData `json:"posting"`
	MemoKey                       string        `json:"memo_key"`
	JsonMetadata                  string        `json:"json_metadata"`
	PostingJsonMetadata           string        `json:"posting_json_metadata"`
	Proxy                         string        `json:"proxy"`
	LastOwnerUpdate               HiveTime      `json:"last_owner_update"`
	LastAccountUpdate             HiveTime      `json:"last_account_update"`
	Created                       HiveTime      `json:"created"`
	Mined                         bool          `json:"mined"`
	RecoveryAccount               string        `json:"recovery_account"`
	ResetAccount                  string        `json:"reset_account"`
	LastAccountRecovery           HiveTime      `json:"last_account_recovery"`
	PostCount                     uint32        `json:"post_count"`
	CanVote                       bool          `json:"can_vote"`
	VotingPower                   int16         `json:"voting_power"`
	LastVoteTime                  HiveTime      `json:"last_vote_time"`
	Balance                       string        `json:"balance"`
	SavingsBalance                string        `json:"savings_balance"`
	HbdBalance                    string        `json:"hbd_balance"`
	HbdSeconds                    string        `json:"hbd_seconds"`
	HbdSecondsLastUpdate          HiveTime      `json:"hbd_seconds_last_update"`
	HbdLastInterestPayment        HiveTime      `json:"hbd_last_interest_payment"`
	SavingsHbdBalance             string        `json:"savings_hbd_balance"`
	SavingsHbdSeconds             string        `json:"savings_hbd_seconds"`
	SavingsHbdLastUpdate          HiveTime      `json:"savings_hbd_last_update"`
	SavingsHbdLastInterestPayment HiveTime      `json:"savings_hbd_last_interest_payment"`
	SavingsWithdrawRequests       uint32        `json:"savings_withdraw_requests"`
	RewardHbdBalance              string        `json:"reward_hbd_balance"`
	RewardHiveBalance             string        `json:"reward_hive_balance"`
	RewardVestingBalance          string        `json:"reward_vesting_balance"`
	RewardVestingHive             string        `json:"reward_vesting_hive"`
	VestingShares                 string        `json:"vesting_shares"`
	DelegatedVestingShares        string        `json:"delegated_vesting_shares"`
	ReceivedVestingShares         string        `json:"received_vesting_shares"`
	VestingWithdrawRate           string        `json:"vesting_withdraw_rate"`
	NextVestingWithdrawal         HiveTime      `json:"next_vesting_withdrawal"`
	Withdrawn                     int64         `json:"withdrawn"`
	ToWithdraw                    int64         `json:"to_withdraw"`
	WithdrawRoutes                uint32        `json:"withdraw_routes"`
	CurationRewards               int64         `json:"curation_rewards"`
	PostingRewards                int64         `json:"posting_rewards"`
	ProxiedVsfVotes               []int64       `json:"proxied_vsf_votes"`
	WitnessesVotedFor             uint32        `json:"witnesses_voted_for"`
	WitnessVotes                  []string      `json:"witness_votes"`
	LastPost                      HiveTime      `json:"last_post"`
	LastRootPost                  HiveTime      `json:"last_root_post"`
	PostVotingPower               string        `json:"post_voting_power"`
	Reputation                    int64         `json:"reputation"`
	PendingClaimedAccounts        uint32        `json:"pending_claimed_accounts"`
	PendingTransfers              uint32        `json:"pending_transfers"`
	DelayedVotes                  []interface{} `json:"delayed_votes"`
	VotingManabar                 RC            `json:"voting_manabar"`
	DownvoteManabar               RC            `json:"downvote_manabar"`
	GovernanceVoteExpirationTs    HiveTime      `json:"governance_vote_expiration_ts"`
}

AccountData holds account information as returned by condenser_api.get_accounts. Balance fields (e.g. Balance, HbdBalance) are returned as strings like "1.000 HIVE"; use ParseAsset to convert them if needed. Note: NextVestingWithdrawal is "1969-12-31T23:59:59" when no power-down is active.

type AccountUpdate2Operation

type AccountUpdate2Operation struct {
	Account             string               `json:"-"`
	Owner               *Authority           `json:"-"`
	Active              *Authority           `json:"-"`
	Posting             *Authority           `json:"-"`
	MemoKey             *secp256k1.PublicKey `json:"-"`
	JsonMetadata        string               `json:"-"`
	PostingJsonMetadata string               `json:"-"`
}

AccountUpdate2Operation updates account metadata and/or authorities. All authority fields and MemoKey are optional — set to nil to leave unchanged.

func (AccountUpdate2Operation) MarshalJSON

func (o AccountUpdate2Operation) MarshalJSON() ([]byte, error)

MarshalJSON encodes AccountUpdate2Operation for the Hive node, rendering MemoKey as a public key string and omitting absent optional fields.

func (AccountUpdate2Operation) OpName

func (o AccountUpdate2Operation) OpName() string

func (AccountUpdate2Operation) SerializeOp

func (o AccountUpdate2Operation) SerializeOp() ([]byte, error)

type AccountUpdateOperation

type AccountUpdateOperation struct {
	Account      string               `json:"-"`
	Owner        *Authority           `json:"-"`
	Active       *Authority           `json:"-"`
	Posting      *Authority           `json:"-"`
	MemoKey      *secp256k1.PublicKey `json:"-"` // required
	JsonMetadata string               `json:"-"`
}

AccountUpdateOperation updates account authorities and memo key (legacy account_update operation). All authority fields are optional — set to nil to leave unchanged. MemoKey is required. For metadata-only updates (json_metadata, posting_json_metadata), prefer AccountUpdate2Operation.

func (AccountUpdateOperation) MarshalJSON

func (o AccountUpdateOperation) MarshalJSON() ([]byte, error)

func (AccountUpdateOperation) OpName

func (o AccountUpdateOperation) OpName() string

func (AccountUpdateOperation) SerializeOp

func (o AccountUpdateOperation) SerializeOp() ([]byte, error)

type AccountWitnessProxyOperation

type AccountWitnessProxyOperation struct {
	Account string `json:"account"`
	Proxy   string `json:"proxy"`
}

AccountWitnessProxyOperation delegates witness votes to a proxy account. Set Proxy to "" to remove an existing proxy.

func (AccountWitnessProxyOperation) OpName

func (AccountWitnessProxyOperation) SerializeOp

func (o AccountWitnessProxyOperation) SerializeOp() ([]byte, error)

type AccountWitnessVoteOperation

type AccountWitnessVoteOperation struct {
	Account string `json:"account"`
	Witness string `json:"witness"`
	Approve bool   `json:"approve"`
}

AccountWitnessVoteOperation votes for or removes a vote from a witness.

func (AccountWitnessVoteOperation) OpName

func (AccountWitnessVoteOperation) SerializeOp

func (o AccountWitnessVoteOperation) SerializeOp() ([]byte, error)

type Asset

type Asset struct {
	Amount    int64
	Precision uint8
	Symbol    string
}

Asset represents a Hive asset amount such as "1.000 HIVE" or "5.321 HBD". Use ParseAsset to create one from a string. The binary serializer requires all three fields, so constructing an Asset directly is only needed for zero values or test fixtures.

Precisions: HIVE and HBD use 3 decimal places; VESTS uses 6.

func ParseAsset

func ParseAsset(s string) (Asset, error)

ParseAsset parses a Hive asset string (e.g. "1.000 HIVE") into an Asset.

func (Asset) MarshalJSON added in v0.2.0

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

MarshalJSON encodes Asset as Hive's canonical string form (e.g. "1.000 HIVE").

func (Asset) String

func (a Asset) String() string

String formats the Asset back to its canonical string form (e.g. "1.000 HIVE").

func (*Asset) UnmarshalJSON added in v0.2.0

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

UnmarshalJSON decodes Asset from either canonical string form or legacy object form.

type Authority

type Authority struct {
	WeightThreshold uint32
	AccountAuths    []AccountAuth
	KeyAuths        []KeyAuth
}

Authority defines the signing requirements for an account action. Use in AccountUpdate2Operation to change owner, active, or posting authorities.

func (Authority) MarshalJSON

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

MarshalJSON encodes Authority in the format the Hive node expects: account_auths and key_auths as [name/key-string, weight] tuple arrays.

type AuthorityData

type AuthorityData struct {
	WeightThreshold uint32          `json:"weight_threshold"`
	AccountAuths    [][]interface{} `json:"account_auths"`
	KeyAuths        [][]interface{} `json:"key_auths"`
}

AuthorityData holds an authority structure as returned by the API (owner, active, or posting).

type Beneficiary

type Beneficiary struct {
	Account string `json:"account"`
	Weight  uint16 `json:"weight"`
}

Beneficiary is a share of a post's author reward routed to another account. Weight is in basis points out of 10000 (e.g. 500 = 5%). The sum of all beneficiary weights must not exceed 10000.

type Block

type Block struct {
	BlockID               string            `json:"block_id"`
	Previous              string            `json:"previous"`
	Timestamp             HiveTime          `json:"timestamp"`
	Witness               string            `json:"witness"`
	TransactionMerkleRoot string            `json:"transaction_merkle_root"`
	WitnessSignature      string            `json:"witness_signature"`
	Extensions            []interface{}     `json:"extensions"`
	Transactions          []json.RawMessage `json:"transactions"`
	TransactionIDs        []string          `json:"transaction_ids"`
}

Block represents a Hive block as returned by block_api.get_block. Transactions are raw JSON — unmarshal them individually based on the operation types you care about. TransactionIDs is populated when the block is fetched with transaction IDs included.

type BroadcastAPI

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

BroadcastAPI provides methods for submitting signed operations to the Hive blockchain. Access via client.Broadcast.

func (BroadcastAPI) CancelDeclineVotingRights

func (b BroadcastAPI) CancelDeclineVotingRights(account string, key *KeyPair) (*Transaction, string, error)

CancelDeclineVotingRights cancels a pending (not yet effective) decline-voting-rights request. To initiate a decline, construct DeclineVotingRightsOperation directly with Decline: true and IUnderstandThisIsIrreversible: true, then use BroadcastOps.

func (BroadcastAPI) CancelTransferFromSavings

func (b BroadcastAPI) CancelTransferFromSavings(from string, requestId uint32, key *KeyPair) (*Transaction, string, error)

CancelTransferFromSavings cancels a pending savings withdrawal. requestId must match the original request.

func (BroadcastAPI) ChangeRecoveryAccount

func (b BroadcastAPI) ChangeRecoveryAccount(accountToRecover, newRecoveryAccount string, key *KeyPair) (*Transaction, string, error)

ChangeRecoveryAccount changes the recovery account. Takes 30 days to take effect.

func (BroadcastAPI) ClaimAccount

func (b BroadcastAPI) ClaimAccount(creator string, fee Asset, key *KeyPair) (*Transaction, string, error)

ClaimAccount claims an account creation token. Use ParseAsset("0.000 HIVE") as fee to claim via RC.

func (BroadcastAPI) ClaimRewards

func (b BroadcastAPI) ClaimRewards(account string, hive, hbd, vests Asset, key *KeyPair) (*Transaction, string, error)

ClaimRewards claims pending reward balances (HIVE, HBD, VESTS) into the account.

func (BroadcastAPI) CollateralizedConvert

func (b BroadcastAPI) CollateralizedConvert(owner string, requestId uint32, amount Asset, key *KeyPair) (*Transaction, string, error)

CollateralizedConvert converts HIVE to HBD instantly using collateral. requestId must be unique per account.

func (BroadcastAPI) Comment

func (b BroadcastAPI) Comment(parentAuthor, parentPermlink, author, permlink, title, body, jsonMetadata string, key *KeyPair) (*Transaction, string, error)

Comment publishes a post or reply. For a top-level post, set parentAuthor to "" and parentPermlink to the category tag.

func (BroadcastAPI) Convert

func (b BroadcastAPI) Convert(owner string, requestId uint32, amount Asset, key *KeyPair) (*Transaction, string, error)

Convert converts HBD to HIVE via the 3.5-day conversion process. requestId must be unique per account.

func (BroadcastAPI) CreateAccount

func (b BroadcastAPI) CreateAccount(fee Asset, creator, newAccountName string, owner, active, posting Authority, memoKey *secp256k1.PublicKey, jsonMetadata string, key *KeyPair) (*Transaction, string, error)

CreateAccount creates a new account with a HIVE fee.

func (BroadcastAPI) CreateClaimedAccount

func (b BroadcastAPI) CreateClaimedAccount(creator, newAccountName string, owner, active, posting Authority, memoKey *secp256k1.PublicKey, jsonMetadata string, key *KeyPair) (*Transaction, string, error)

CreateClaimedAccount creates a new account from a previously claimed token (no fee).

func (BroadcastAPI) CreateProposal

func (b BroadcastAPI) CreateProposal(creator, receiver, startDate, endDate string, dailyPay Asset, subject, permlink string, key *KeyPair) (*Transaction, string, error)

CreateProposal submits a DHF funding proposal. startDate/endDate in "2006-01-02T15:04:05" format, dailyPay must be HBD.

func (BroadcastAPI) Custom

func (b BroadcastAPI) Custom(requiredAuths []string, id uint16, data string, key *KeyPair) (*Transaction, string, error)

Custom broadcasts a custom operation.

func (BroadcastAPI) CustomBinary

func (b BroadcastAPI) CustomBinary(requiredOwnerAuths, requiredActiveAuths, requiredPostingAuths []string, requiredAuths []Authority, id string, data []byte, key *KeyPair) (*Transaction, string, error)

CustomBinary broadcasts arbitrary binary data.

func (BroadcastAPI) CustomJson

func (b BroadcastAPI) CustomJson(reqAuth, reqPostAuth []string, id, cj string, key *KeyPair) (*Transaction, string, error)

CustomJson broadcasts a custom_json operation. Use reqAuth for active-key actions and reqPostAuth for posting-key actions.

func (BroadcastAPI) Delegate

func (b BroadcastAPI) Delegate(delegator, delegatee string, vestingShares Asset, key *KeyPair) (*Transaction, string, error)

Delegate delegates vestingShares of HP from delegator to delegatee. Use ParseAsset("0.000000 VESTS") to remove an existing delegation.

func (BroadcastAPI) DeleteComment

func (b BroadcastAPI) DeleteComment(author, permlink string, key *KeyPair) (*Transaction, string, error)

DeleteComment deletes a post or comment.

func (BroadcastAPI) EscrowApprove

func (b BroadcastAPI) EscrowApprove(from, to, agent, who string, escrowId uint32, approve bool, key *KeyPair) (*Transaction, string, error)

EscrowApprove approves or rejects an escrow. who must be the to-party or agent.

func (BroadcastAPI) EscrowDispute

func (b BroadcastAPI) EscrowDispute(from, to, agent, who string, escrowId uint32, key *KeyPair) (*Transaction, string, error)

EscrowDispute raises a dispute on an escrow, handing release authority to the agent.

func (BroadcastAPI) EscrowRelease

func (b BroadcastAPI) EscrowRelease(from, to, agent, who, receiver string, escrowId uint32, hbdAmount, hiveAmount Asset, key *KeyPair) (*Transaction, string, error)

EscrowRelease releases escrowed funds to receiver.

func (BroadcastAPI) EscrowTransfer

func (b BroadcastAPI) EscrowTransfer(from, to, agent string, escrowId uint32, hbdAmount, hiveAmount, fee Asset, ratificationDeadline, escrowExpiration, jsonMeta string, key *KeyPair) (*Transaction, string, error)

EscrowTransfer locks funds in escrow with an agent. ratificationDeadline and escrowExpiration in "2006-01-02T15:04:05" format.

func (BroadcastAPI) FeedPublish

func (b BroadcastAPI) FeedPublish(publisher string, base, quote Asset, key *KeyPair) (*Transaction, string, error)

FeedPublish publishes a HIVE/HBD price feed. base should be HBD, quote should be HIVE. Only witnesses with an active signing key should call this.

func (BroadcastAPI) LimitOrderCancel

func (b BroadcastAPI) LimitOrderCancel(owner string, orderId uint32, key *KeyPair) (*Transaction, string, error)

LimitOrderCancel cancels an open limit order by ID.

func (BroadcastAPI) LimitOrderCreate

func (b BroadcastAPI) LimitOrderCreate(owner string, orderId uint32, amountToSell, minToReceive Asset, fillOrKill bool, expiration string, key *KeyPair) (*Transaction, string, error)

LimitOrderCreate places a limit order on the internal DEX. expiration must be in "2006-01-02T15:04:05" format.

func (BroadcastAPI) PowerDown

func (b BroadcastAPI) PowerDown(account string, vestingShares Asset, key *KeyPair) (*Transaction, string, error)

PowerDown initiates a 13-week power-down of vestingShares. Use ParseAsset("0.000000 VESTS") to cancel.

func (BroadcastAPI) PowerUp

func (b BroadcastAPI) PowerUp(from, to string, amount Asset, key *KeyPair) (*Transaction, string, error)

PowerUp converts HIVE to Hive Power. Set to "" to power up to the same account as from.

func (BroadcastAPI) RecoverAccount

func (b BroadcastAPI) RecoverAccount(accountToRecover string, newOwnerAuthority, recentOwnerAuthority Authority, key *KeyPair) (*Transaction, string, error)

RecoverAccount completes account recovery. Must be signed with both the new and a recent old owner key.

func (BroadcastAPI) RecurrentTransfer

func (b BroadcastAPI) RecurrentTransfer(from, to string, amount Asset, memo string, recurrence, executions uint16, key *KeyPair) (*Transaction, string, error)

RecurrentTransfer schedules a recurring transfer of HIVE or HBD. recurrence is the number of hours between each execution; executions is the total number of transfers (minimum 2). To cancel, set amount to zero and executions to 2.

func (BroadcastAPI) RemoveProposal

func (b BroadcastAPI) RemoveProposal(owner string, proposalIds []int64, key *KeyPair) (*Transaction, string, error)

RemoveProposal removes proposals by ID. Only the proposal creator can remove.

func (BroadcastAPI) RequestAccountRecovery

func (b BroadcastAPI) RequestAccountRecovery(recoveryAccount, accountToRecover string, newOwnerAuthority Authority, key *KeyPair) (*Transaction, string, error)

RequestAccountRecovery initiates recovery. Must be submitted by the recovery account.

func (BroadcastAPI) SetWithdrawRoute

func (b BroadcastAPI) SetWithdrawRoute(from, to string, percent uint16, autoVest bool, key *KeyPair) (*Transaction, string, error)

SetWithdrawRoute routes percent of power-down payouts to toAccount. percent is in basis points (10000 = 100%). Set to 0 to remove the route.

func (BroadcastAPI) SetWitnessProxy

func (b BroadcastAPI) SetWitnessProxy(account, proxy string, key *KeyPair) (*Transaction, string, error)

SetWitnessProxy delegates witness votes to proxy. Set proxy to "" to remove.

func (BroadcastAPI) Transfer

func (b BroadcastAPI) Transfer(from, to string, amount Asset, memo string, key *KeyPair) (*Transaction, string, error)

Transfer sends HIVE or HBD from one account to another. amount should be created with ParseAsset, e.g. ParseAsset("1.000 HIVE").

func (BroadcastAPI) TransferFromSavings

func (b BroadcastAPI) TransferFromSavings(from string, requestId uint32, to string, amount Asset, memo string, key *KeyPair) (*Transaction, string, error)

TransferFromSavings initiates a savings withdrawal. requestId must be unique per account.

func (BroadcastAPI) TransferToSavings

func (b BroadcastAPI) TransferToSavings(from, to string, amount Asset, memo string, key *KeyPair) (*Transaction, string, error)

TransferToSavings moves HIVE or HBD into the savings balance (3-day withdrawal delay).

func (BroadcastAPI) UpdateAccount

func (b BroadcastAPI) UpdateAccount(account, jsonMetadata, postingJsonMetadata string, key *KeyPair) (*Transaction, string, error)

UpdateAccount updates the json_metadata and/or posting_json_metadata for an account. For authority or memo key changes, construct AccountUpdate2Operation directly and use BroadcastOps.

func (BroadcastAPI) UpdateProposal

func (b BroadcastAPI) UpdateProposal(proposalId int64, creator string, dailyPay Asset, subject, permlink, endDate string, key *KeyPair) (*Transaction, string, error)

UpdateProposal updates an existing proposal. endDate is optional — pass "" to leave unchanged.

func (BroadcastAPI) UpdateProposalVotes

func (b BroadcastAPI) UpdateProposalVotes(voter string, proposalIds []int64, approve bool, key *KeyPair) (*Transaction, string, error)

UpdateProposalVotes approves or removes votes for the given proposal IDs.

func (BroadcastAPI) UpdateWitness

func (b BroadcastAPI) UpdateWitness(owner, url string, signingKey *secp256k1.PublicKey, props ChainProperties, fee Asset, key *KeyPair) (*Transaction, string, error)

UpdateWitness updates a witness registration (witness_update).

func (BroadcastAPI) Vote

func (b BroadcastAPI) Vote(voter, author, permlink string, weight int, key *KeyPair) (*Transaction, string, error)

Vote submits a vote on a post or comment. weight ranges from -10000 (100% downvote) to 10000 (100% upvote).

func (BroadcastAPI) VoteWitness

func (b BroadcastAPI) VoteWitness(account, witness string, approve bool, key *KeyPair) (*Transaction, string, error)

VoteWitness approves or removes a vote for a witness.

func (BroadcastAPI) WitnessSetProperties

func (b BroadcastAPI) WitnessSetProperties(owner string, props map[string][]byte, key *KeyPair) (*Transaction, string, error)

WitnessSetProperties updates witness properties using the modern key-value format.

type CancelTransferFromSavingsOperation

type CancelTransferFromSavingsOperation struct {
	From      string `json:"from"`
	RequestId uint32 `json:"request_id"`
}

CancelTransferFromSavingsOperation cancels a pending savings withdrawal by request ID.

func (CancelTransferFromSavingsOperation) OpName

func (CancelTransferFromSavingsOperation) SerializeOp

func (o CancelTransferFromSavingsOperation) SerializeOp() ([]byte, error)

type ChainProperties

type ChainProperties struct {
	AccountCreationFee Asset  `json:"account_creation_fee"`
	MaximumBlockSize   uint32 `json:"maximum_block_size"`
	HbdInterestRate    uint16 `json:"hbd_interest_rate"`
}

ChainProperties represents witness-reported blockchain configuration for witness_update.

type ChangeRecoveryAccountOperation

type ChangeRecoveryAccountOperation struct {
	AccountToRecover   string `json:"account_to_recover"`
	NewRecoveryAccount string `json:"new_recovery_account"`
}

ChangeRecoveryAccountOperation changes the designated recovery account. Takes 30 days to take effect.

func (ChangeRecoveryAccountOperation) OpName

func (ChangeRecoveryAccountOperation) SerializeOp

func (o ChangeRecoveryAccountOperation) SerializeOp() ([]byte, error)

type ClaimAccountOperation

type ClaimAccountOperation struct {
	Creator string `json:"creator"`
	Fee     Asset  `json:"fee"`
}

ClaimAccountOperation claims an account creation token using RC or a HIVE fee. Set Fee to ParseAsset("0.000 HIVE") to use RC instead of a HIVE fee.

func (ClaimAccountOperation) OpName

func (o ClaimAccountOperation) OpName() string

func (ClaimAccountOperation) SerializeOp

func (o ClaimAccountOperation) SerializeOp() ([]byte, error)

type ClaimRewardBalanceOperation

type ClaimRewardBalanceOperation struct {
	Account     string `json:"account"`
	RewardHive  Asset  `json:"reward_hive"`
	RewardHbd   Asset  `json:"reward_hbd"`
	RewardVests Asset  `json:"reward_vests"`
}

ClaimRewardBalanceOperation claims pending reward balances into the account.

func (ClaimRewardBalanceOperation) OpName

func (ClaimRewardBalanceOperation) SerializeOp

func (o ClaimRewardBalanceOperation) SerializeOp() ([]byte, error)

type Client

type Client struct {
	// Broadcast provides methods for submitting operations to the blockchain.
	Broadcast BroadcastAPI
	// Database provides methods for reading data from the blockchain.
	Database DatabaseAPI

	// MaxConn is the maximum number of concurrent HTTP connections per node (default 1).
	MaxConn int
	// MaxBatch is the maximum number of requests per JSON-RPC batch call (default 4).
	MaxBatch int
	// NoBroadcast enables dry-run mode: transactions are built and signed but not submitted.
	// Prefer using [Client.WithNoBroadcast] to set this.
	NoBroadcast bool
	// ChainID is the hex-encoded chain ID used when signing transactions.
	// Defaults to [HiveMainnetChainID]. Override for testnet or custom chains.
	ChainID string
	// PublicKeyPrefix is the prefix used when encoding/decoding public key strings.
	// Defaults to "STM". Set to "TST" for the Hive public testnet.
	PublicKeyPrefix string
	// contains filtered or unexported fields
}

Client is the Hive blockchain RPC client. Create one with NewClient.

The two namespaces cover all common use cases:

client.Broadcast  — sign and submit operations (vote, transfer, custom_json, …)
client.Database   — read blocks, accounts, and chain state

func NewClient

func NewClient(nodes ...string) *Client

NewClient creates a Client that connects to one or more Hive API node addresses. Requests are tried against each node in order, falling through to the next on error, providing automatic failover.

client := hivego.NewClient("https://api.hive.blog", "https://api.deathwing.me")

func (*Client) BroadcastOps

func (h *Client) BroadcastOps(ops []HiveOperation, key *KeyPair) (*Transaction, string, error)

BroadcastOps builds a transaction from ops, signs it with key, and submits it to the network. It is a convenience wrapper around BuildTransaction, Sign, and BroadcastTx. Returns the signed transaction, the transaction ID, and any error. If NoBroadcast is set, the transaction is built and signed but not submitted.

func (*Client) BroadcastTx

func (h *Client) BroadcastTx(tx *Transaction) error

BroadcastTx submits a pre-built, pre-signed Transaction to the network. Most callers should use Client.BroadcastOps instead, which handles the full build → sign → broadcast flow. Use BroadcastTx directly when you need fine-grained control, such as multi-sig (multiple Sign calls before broadcasting).

func (*Client) BuildTransaction

func (h *Client) BuildTransaction(ops []HiveOperation) (*Transaction, error)

BuildTransaction fetches the current chain state and returns an unsigned Transaction populated with the correct reference block and expiration.

func (*Client) Sign

func (h *Client) Sign(tx *Transaction, key *KeyPair) error

Sign signs the transaction with the given KeyPair and appends the signature. The client's ChainID is used (Hive mainnet by default; override with client.ChainID). Does not broadcast — call BroadcastTx when ready.

func (*Client) WithNoBroadcast

func (h *Client) WithNoBroadcast() *Client

WithNoBroadcast sets the client to dry-run mode: transactions are built and signed but not submitted to the network. The signed Transaction is still returned so it can be inspected, serialized, or logged.

type CollateralizedConvertOperation

type CollateralizedConvertOperation struct {
	Owner     string `json:"owner"`
	RequestId uint32 `json:"request_id"`
	Amount    Asset  `json:"amount"`
}

CollateralizedConvertOperation converts HIVE to HBD instantly using collateral. RequestId must be unique per account.

func (CollateralizedConvertOperation) OpName

func (CollateralizedConvertOperation) SerializeOp

func (o CollateralizedConvertOperation) SerializeOp() ([]byte, error)

type CommentOperation

type CommentOperation struct {
	ParentAuthor   string `json:"parent_author"`
	ParentPermlink string `json:"parent_permlink"`
	Author         string `json:"author"`
	Permlink       string `json:"permlink"`
	Title          string `json:"title"`
	Body           string `json:"body"`
	JsonMetadata   string `json:"json_metadata"`
}

CommentOperation creates or edits a post or comment. For a top-level post, set ParentAuthor to "" and ParentPermlink to the category tag. For a reply, set ParentAuthor and ParentPermlink to the parent post's values.

func (CommentOperation) OpName

func (o CommentOperation) OpName() string

func (CommentOperation) SerializeOp

func (o CommentOperation) SerializeOp() ([]byte, error)

type CommentOptionsOperation

type CommentOptionsOperation struct {
	Author               string        `json:"author"`
	Permlink             string        `json:"permlink"`
	MaxAcceptedPayout    Asset         `json:"max_accepted_payout"`
	PercentHbd           uint16        `json:"percent_hbd"`
	AllowVotes           bool          `json:"allow_votes"`
	AllowCurationRewards bool          `json:"allow_curation_rewards"`
	Beneficiaries        []Beneficiary `json:"-"`
}

CommentOptionsOperation sets payout and beneficiary options on a post. It must be submitted in the same transaction as the CommentOperation it targets. Use client.BuildTransaction to combine them.

MaxAcceptedPayout: ParseAsset("1000000.000 HBD") for no limit, or ParseAsset("0.000 HBD") to decline. PercentHbd: portion of author reward paid as HBD, in basis points (10000 = 100%).

func (CommentOptionsOperation) MarshalJSON added in v0.1.6

func (o CommentOptionsOperation) MarshalJSON() ([]byte, error)

MarshalJSON encodes comment_options in condenser-compatible form. Beneficiaries are represented as an extensions static_variant: [[0,{"beneficiaries":[...]}]].

func (CommentOptionsOperation) OpName

func (o CommentOptionsOperation) OpName() string

func (CommentOptionsOperation) SerializeOp

func (o CommentOptionsOperation) SerializeOp() ([]byte, error)

type ConvertOperation

type ConvertOperation struct {
	Owner     string `json:"owner"`
	RequestId uint32 `json:"request_id"`
	Amount    Asset  `json:"amount"`
}

ConvertOperation converts HBD to HIVE via the 3.5-day conversion process. RequestId must be unique per account.

func (ConvertOperation) OpName

func (o ConvertOperation) OpName() string

func (ConvertOperation) SerializeOp

func (o ConvertOperation) SerializeOp() ([]byte, error)

type CreateClaimedAccountOperation

type CreateClaimedAccountOperation struct {
	Creator        string               `json:"-"`
	NewAccountName string               `json:"-"`
	Owner          Authority            `json:"-"`
	Active         Authority            `json:"-"`
	Posting        Authority            `json:"-"`
	MemoKey        *secp256k1.PublicKey `json:"-"`
	JsonMetadata   string               `json:"-"`
}

CreateClaimedAccountOperation creates a new account from a previously claimed token (no fee). All authority fields and MemoKey are required.

func (CreateClaimedAccountOperation) MarshalJSON

func (o CreateClaimedAccountOperation) MarshalJSON() ([]byte, error)

func (CreateClaimedAccountOperation) OpName

func (CreateClaimedAccountOperation) SerializeOp

func (o CreateClaimedAccountOperation) SerializeOp() ([]byte, error)

type CreateProposalOperation

type CreateProposalOperation struct {
	Creator   string `json:"creator"`
	Receiver  string `json:"receiver"`
	StartDate string `json:"start_date"`
	EndDate   string `json:"end_date"`
	DailyPay  Asset  `json:"daily_pay"`
	Subject   string `json:"subject"`
	Permlink  string `json:"permlink"`
}

CreateProposalOperation submits a funding proposal to the Decentralised Hive Fund. StartDate and EndDate must be in "2006-01-02T15:04:05" format. DailyPay must be HBD.

func (CreateProposalOperation) OpName

func (o CreateProposalOperation) OpName() string

func (CreateProposalOperation) SerializeOp

func (o CreateProposalOperation) SerializeOp() ([]byte, error)

type CustomBinaryOperation

type CustomBinaryOperation struct {
	RequiredOwnerAuths   []string    `json:"-"`
	RequiredActiveAuths  []string    `json:"-"`
	RequiredPostingAuths []string    `json:"-"`
	RequiredAuths        []Authority `json:"-"`
	Id                   string      `json:"-"`
	Data                 []byte      `json:"-"`
}

CustomBinaryOperation broadcasts arbitrary binary data with optional authority requirements. Id must be less than 32 characters. Data is arbitrary binary.

Note: beem's implementation of this operation is incomplete (it uses uint16 for id and omits all auth fields). The wire format here follows the Hive C++ protocol spec.

func (CustomBinaryOperation) MarshalJSON

func (o CustomBinaryOperation) MarshalJSON() ([]byte, error)

func (CustomBinaryOperation) OpName

func (o CustomBinaryOperation) OpName() string

func (CustomBinaryOperation) SerializeOp

func (o CustomBinaryOperation) SerializeOp() ([]byte, error)

type CustomJsonOperation

type CustomJsonOperation struct {
	RequiredAuths        []string `json:"required_auths"`
	RequiredPostingAuths []string `json:"required_posting_auths"`
	Id                   string   `json:"id"`
	Json                 string   `json:"json"`
}

CustomJsonOperation broadcasts a custom_json operation. Use RequiredAuths for active-key actions and RequiredPostingAuths for posting-key actions.

func (CustomJsonOperation) OpName

func (o CustomJsonOperation) OpName() string

func (CustomJsonOperation) SerializeOp

func (o CustomJsonOperation) SerializeOp() ([]byte, error)

type CustomOperation

type CustomOperation struct {
	RequiredAuths []string `json:"required_auths"`
	Id            uint16   `json:"id"`
	Data          string   `json:"data"`
}

CustomOperation broadcasts a custom operation with an integer id and arbitrary string data. RequiredAuths must contain accounts with active key authority.

func (CustomOperation) OpName

func (o CustomOperation) OpName() string

func (CustomOperation) SerializeOp

func (o CustomOperation) SerializeOp() ([]byte, error)

type DatabaseAPI

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

DatabaseAPI provides methods for reading data from the Hive blockchain. Access via client.Database.

func (DatabaseAPI) GetAccounts

func (d DatabaseAPI) GetAccounts(names []string) ([]AccountData, error)

GetAccounts returns account data for the given account names. Non-existent accounts are silently omitted from the result — the returned slice may be shorter than the input. Balance fields on AccountData are strings (e.g. "1.000 HIVE"); use ParseAsset to convert them for arithmetic or serialization.

func (DatabaseAPI) GetBlock

func (d DatabaseAPI) GetBlock(blockNum int) (*Block, error)

GetBlock fetches a single block by block number and returns it as a typed Block. Returns nil (with no error) if the block does not yet exist on the chain.

func (DatabaseAPI) GetBlockRange

func (d DatabaseAPI) GetBlockRange(startBlock int, count int) ([]json.RawMessage, error)

GetBlockRange fetches count blocks starting at startBlock and returns each as a json.RawMessage. Requests are batched internally in groups of 500. For a single typed block use DatabaseAPI.GetBlock; for continuous streaming use DatabaseAPI.StreamBlocks. For maximum throughput use DatabaseAPI.GetBlockRangeFast.

Note: do not run bulk block fetching against public API nodes at high request rates. Use a dedicated node for block processing workloads.

func (DatabaseAPI) GetBlockRangeFast

func (d DatabaseAPI) GetBlockRangeFast(startBlock int, count int) ([][]byte, error)

GetBlockRangeFast fetches count blocks starting at startBlock and returns each as raw bytes. Requests are batched internally in groups of 500. This is the fastest option for high-throughput block processing — skip JSON parsing entirely and handle the bytes directly.

func (DatabaseAPI) GetDynamicGlobalProperties

func (d DatabaseAPI) GetDynamicGlobalProperties() ([]byte, error)

GetDynamicGlobalProperties returns the current dynamic global properties as raw JSON. The result includes the head block number, head block ID, current supply, and other chain-wide state. Unmarshal into a struct of your choosing for specific fields.

func (DatabaseAPI) GetTransaction

func (d DatabaseAPI) GetTransaction(txId string, includeReversible bool) ([]byte, error)

GetTransaction fetches a transaction by ID, returning raw JSON.

func (DatabaseAPI) StreamBlocks

func (d DatabaseAPI) StreamBlocks(ctx context.Context, startBlock int, pollInterval time.Duration) (<-chan Block, <-chan error)

StreamBlocks streams blocks sequentially starting at startBlock. Blocks are delivered on the returned channel. When caught up to the head block, StreamBlocks polls at the given interval until the next block is produced. Cancel ctx to stop the stream; both returned channels are closed on exit. Any terminal error is sent on the error channel before it closes.

Example:

blocks, errc := client.Database.StreamBlocks(ctx, 88000000, 3*time.Second)
for block := range blocks {
    fmt.Println(block.BlockID, block.Timestamp)
}
if err := <-errc; err != nil {
    log.Fatal(err)
}

type DeclineVotingRightsOperation

type DeclineVotingRightsOperation struct {
	Account string `json:"account"`
	Decline bool   `json:"decline"`
	// IUnderstandThisIsIrreversible must be true when Decline is true.
	// Declining voting rights permanently removes the account's ability to vote and cannot be undone.
	IUnderstandThisIsIrreversible bool `json:"-"`
}

DeclineVotingRightsOperation permanently removes an account's ability to vote. THIS CANNOT BE UNDONE. You must set IUnderstandThisIsIrreversible to true when Decline is true. Set Decline to false to cancel a pending (not yet effective) decline request.

func (DeclineVotingRightsOperation) OpName

func (DeclineVotingRightsOperation) SerializeOp

func (o DeclineVotingRightsOperation) SerializeOp() ([]byte, error)

type DelegateVestingSharesOperation

type DelegateVestingSharesOperation struct {
	Delegator     string `json:"delegator"`
	Delegatee     string `json:"delegatee"`
	VestingShares Asset  `json:"vesting_shares"`
}

DelegateVestingSharesOperation delegates HP to another account. Set VestingShares to ParseAsset("0.000000 VESTS") to remove an existing delegation.

func (DelegateVestingSharesOperation) OpName

func (DelegateVestingSharesOperation) SerializeOp

func (o DelegateVestingSharesOperation) SerializeOp() ([]byte, error)

type DeleteCommentOperation

type DeleteCommentOperation struct {
	Author   string `json:"author"`
	Permlink string `json:"permlink"`
}

DeleteCommentOperation deletes a post or comment. The post must have no replies, no pending payout, and no net votes.

func (DeleteCommentOperation) OpName

func (o DeleteCommentOperation) OpName() string

func (DeleteCommentOperation) SerializeOp

func (o DeleteCommentOperation) SerializeOp() ([]byte, error)

type EscrowApproveOperation

type EscrowApproveOperation struct {
	From     string `json:"from"`
	To       string `json:"to"`
	Agent    string `json:"agent"`
	Who      string `json:"who"`
	EscrowId uint32 `json:"escrow_id"`
	Approve  bool   `json:"approve"`
}

EscrowApproveOperation approves or rejects an escrow by the to-party or agent.

func (EscrowApproveOperation) OpName

func (o EscrowApproveOperation) OpName() string

func (EscrowApproveOperation) SerializeOp

func (o EscrowApproveOperation) SerializeOp() ([]byte, error)

type EscrowDisputeOperation

type EscrowDisputeOperation struct {
	From     string `json:"from"`
	To       string `json:"to"`
	Agent    string `json:"agent"`
	Who      string `json:"who"`
	EscrowId uint32 `json:"escrow_id"`
}

EscrowDisputeOperation raises a dispute, transferring release authority to the agent.

func (EscrowDisputeOperation) OpName

func (o EscrowDisputeOperation) OpName() string

func (EscrowDisputeOperation) SerializeOp

func (o EscrowDisputeOperation) SerializeOp() ([]byte, error)

type EscrowReleaseOperation

type EscrowReleaseOperation struct {
	From       string `json:"from"`
	To         string `json:"to"`
	Agent      string `json:"agent"`
	Who        string `json:"who"`
	Receiver   string `json:"receiver"`
	EscrowId   uint32 `json:"escrow_id"`
	HbdAmount  Asset  `json:"hbd_amount"`
	HiveAmount Asset  `json:"hive_amount"`
}

EscrowReleaseOperation releases escrowed funds to the receiver.

func (EscrowReleaseOperation) OpName

func (o EscrowReleaseOperation) OpName() string

func (EscrowReleaseOperation) SerializeOp

func (o EscrowReleaseOperation) SerializeOp() ([]byte, error)

type EscrowTransferOperation

type EscrowTransferOperation struct {
	From                 string `json:"from"`
	To                   string `json:"to"`
	Agent                string `json:"agent"`
	EscrowId             uint32 `json:"escrow_id"`
	HbdAmount            Asset  `json:"hbd_amount"`
	HiveAmount           Asset  `json:"hive_amount"`
	Fee                  Asset  `json:"fee"`
	RatificationDeadline string `json:"ratification_deadline"`
	EscrowExpiration     string `json:"escrow_expiration"`
	JsonMeta             string `json:"json_meta"`
}

EscrowTransferOperation locks funds with a third-party agent until conditions are met. RatificationDeadline and EscrowExpiration must be in "2006-01-02T15:04:05" format.

func (EscrowTransferOperation) OpName

func (o EscrowTransferOperation) OpName() string

func (EscrowTransferOperation) SerializeOp

func (o EscrowTransferOperation) SerializeOp() ([]byte, error)

type FeedPublishOperation

type FeedPublishOperation struct {
	Publisher    string `json:"publisher"`
	ExchangeRate Price  `json:"exchange_rate"`
}

FeedPublishOperation publishes a HIVE/HBD price feed for consensus. Witnesses only. ExchangeRate.Base should be HBD and ExchangeRate.Quote should be HIVE, representing the price of 1 HBD in HIVE (e.g. base="1.000 HBD", quote="3.500 HIVE" means 1 HBD = 3.5 HIVE).

func (FeedPublishOperation) OpName

func (o FeedPublishOperation) OpName() string

func (FeedPublishOperation) SerializeOp

func (o FeedPublishOperation) SerializeOp() ([]byte, error)

type HiveOperation

type HiveOperation interface {
	SerializeOp() ([]byte, error)
	OpName() string
}

HiveOperation is the interface implemented by all Hive blockchain operations. Implement this interface to broadcast operations not built into the library.

SerializeOp returns the binary representation used for local signing. OpName returns the Hive operation type name (e.g. "vote", "custom_json").

type HiveRpcNode deprecated

type HiveRpcNode = Client

HiveRpcNode is an alias for Client for backward compatibility.

Deprecated: Use Client directly.

type HiveTime

type HiveTime time.Time

HiveTime is a time.Time that marshals/unmarshals Hive's timestamp format ("2006-01-02T15:04:05"). Hive timestamps carry no timezone suffix and are always UTC, making them incompatible with Go's default RFC3339 JSON handling. Use HiveTime.Time to get the underlying time.Time.

func (HiveTime) MarshalJSON

func (ht HiveTime) MarshalJSON() ([]byte, error)

func (HiveTime) Time

func (ht HiveTime) Time() time.Time

Time returns the underlying time.Time value.

func (*HiveTime) UnmarshalJSON

func (ht *HiveTime) UnmarshalJSON(b []byte) error

type KeyAuth

type KeyAuth struct {
	Key    *secp256k1.PublicKey
	Weight uint16
}

KeyAuth is a public key paired with a weight for use in an Authority.

type KeyPair

type KeyPair struct {
	PrivateKey *secp256k1.PrivateKey
	PublicKey  *secp256k1.PublicKey
}

KeyPair holds a secp256k1 private/public key pair derived from a Hive WIF private key. Create one with KeyPairFromWif or KeyPairFromBytes and pass it to broadcast methods.

func KeyPairFromBytes

func KeyPairFromBytes(privKeyBytes []byte) (*KeyPair, error)

KeyPairFromBytes creates a KeyPair from a raw 32-byte private key.

func KeyPairFromWif

func KeyPairFromWif(wif string) (*KeyPair, error)

KeyPairFromWif creates a KeyPair from a WIF-encoded private key string.

func (*KeyPair) GetPublicKeyString

func (kp *KeyPair) GetPublicKeyString() string

GetPublicKeyString returns the Hive public key string using this KeyPair's public key. Uses the package-level PublicKeyPrefix.

type LimitOrderCancelOperation

type LimitOrderCancelOperation struct {
	Owner   string `json:"owner"`
	OrderId uint32 `json:"orderid"`
}

LimitOrderCancelOperation cancels an open limit order by ID.

func (LimitOrderCancelOperation) OpName

func (o LimitOrderCancelOperation) OpName() string

func (LimitOrderCancelOperation) SerializeOp

func (o LimitOrderCancelOperation) SerializeOp() ([]byte, error)

type LimitOrderCreateOperation

type LimitOrderCreateOperation struct {
	Owner        string `json:"owner"`
	OrderId      uint32 `json:"orderid"`
	AmountToSell Asset  `json:"amount_to_sell"`
	MinToReceive Asset  `json:"min_to_receive"`
	FillOrKill   bool   `json:"fill_or_kill"`
	Expiration   string `json:"expiration"`
}

LimitOrderCreateOperation places a limit order on the internal DEX. Expiration must be in "2006-01-02T15:04:05" format. Set FillOrKill to true to cancel the order if it cannot be immediately filled.

func (LimitOrderCreateOperation) OpName

func (o LimitOrderCreateOperation) OpName() string

func (LimitOrderCreateOperation) SerializeOp

func (o LimitOrderCreateOperation) SerializeOp() ([]byte, error)

type Price

type Price struct {
	Base  Asset `json:"base"`
	Quote Asset `json:"quote"`
}

Price represents an exchange rate between two assets (e.g. for witness feed publishing).

type RC

type RC struct {
	CurrentMana    int64 `json:"current_mana"`
	LastUpdateTime int64 `json:"last_update_time"`
}

RC holds a resource-credit manabar as returned by the API (e.g. VotingManabar, DownvoteManabar). CurrentMana is in raw units (not percentage); divide by the account's VestingShares to get the effective percentage. LastUpdateTime is a Unix timestamp.

type RPCError

type RPCError struct {
	Code    int
	Message string
}

RPCError is returned when the Hive node responds with a JSON-RPC error. Use errors.As to extract the Code and Message:

var rpcErr *hivego.RPCError
if errors.As(err, &rpcErr) {
    fmt.Println(rpcErr.Code, rpcErr.Message)
}

func (*RPCError) Error

func (e *RPCError) Error() string

type RecoverAccountOperation

type RecoverAccountOperation struct {
	AccountToRecover     string    `json:"account_to_recover"`
	NewOwnerAuthority    Authority `json:"new_owner_authority"`
	RecentOwnerAuthority Authority `json:"recent_owner_authority"`
}

RecoverAccountOperation completes account recovery using both the new and a recent old owner authority.

func (RecoverAccountOperation) OpName

func (o RecoverAccountOperation) OpName() string

func (RecoverAccountOperation) SerializeOp

func (o RecoverAccountOperation) SerializeOp() ([]byte, error)

type RecurrentTransferOperation

type RecurrentTransferOperation struct {
	From       string `json:"from"`
	To         string `json:"to"`
	Amount     Asset  `json:"amount"`
	Memo       string `json:"memo"`
	Recurrence uint16 `json:"recurrence"`
	Executions uint16 `json:"executions"`
}

RecurrentTransferOperation schedules a recurring transfer of HIVE or HBD. Recurrence is the number of hours between each transfer. Executions is the number of times to execute (minimum 2). To cancel a recurrent transfer, set Amount to ParseAsset("0.000 HIVE") (or HBD) and Executions to 2.

func (RecurrentTransferOperation) OpName

func (RecurrentTransferOperation) SerializeOp

func (o RecurrentTransferOperation) SerializeOp() ([]byte, error)

type RemoveProposalOperation

type RemoveProposalOperation struct {
	ProposalOwner string  `json:"proposal_owner"`
	ProposalIds   []int64 `json:"proposal_ids"`
}

RemoveProposalOperation removes one or more proposals. Only the proposal creator can remove.

func (RemoveProposalOperation) OpName

func (o RemoveProposalOperation) OpName() string

func (RemoveProposalOperation) SerializeOp

func (o RemoveProposalOperation) SerializeOp() ([]byte, error)

type RequestAccountRecoveryOperation

type RequestAccountRecoveryOperation struct {
	RecoveryAccount   string    `json:"recovery_account"`
	AccountToRecover  string    `json:"account_to_recover"`
	NewOwnerAuthority Authority `json:"new_owner_authority"`
}

RequestAccountRecoveryOperation initiates account recovery. Submitted by the recovery account.

func (RequestAccountRecoveryOperation) OpName

func (RequestAccountRecoveryOperation) SerializeOp

func (o RequestAccountRecoveryOperation) SerializeOp() ([]byte, error)

type SetWithdrawVestingRouteOperation

type SetWithdrawVestingRouteOperation struct {
	FromAccount string `json:"from_account"`
	ToAccount   string `json:"to_account"`
	Percent     uint16 `json:"percent"`
	AutoVest    bool   `json:"auto_vest"`
}

SetWithdrawVestingRouteOperation routes a percentage of power-down payouts to another account. Percent is in basis points (10000 = 100%). Set to 0 to remove a route. AutoVest controls whether the routed amount is automatically powered up in the destination account.

func (SetWithdrawVestingRouteOperation) OpName

func (SetWithdrawVestingRouteOperation) SerializeOp

func (o SetWithdrawVestingRouteOperation) SerializeOp() ([]byte, error)

type Transaction

type Transaction struct {
	RefBlockNum    uint16 `json:"ref_block_num"`
	RefBlockPrefix uint32 `json:"ref_block_prefix"`
	// Expiration is a Hive timestamp string ("2006-01-02T15:04:05"). Set automatically
	// by [Client.BuildTransaction] to 30 seconds after the current head block time.
	Expiration   string           `json:"expiration"`
	Operations   []HiveOperation  `json:"-"`
	OperationsJs [][2]interface{} `json:"operations"`
	Extensions   []string         `json:"extensions"`
	Signatures   []string         `json:"signatures"`
}

Transaction is a Hive blockchain transaction, ready for signing and broadcasting. Use Client.BuildTransaction to create one from a set of operations, or construct it directly for offline or multi-sig workflows.

Operations holds the typed operations for signing and serialization. OperationsJs is populated by the broadcast path and holds the JSON representation that is sent to the node; it is built automatically and should not be set manually.

func (*Transaction) GenerateTrxId

func (t *Transaction) GenerateTrxId() (string, error)

GenerateTrxId computes the transaction ID (first 20 bytes of SHA256 of the serialized tx).

func (*Transaction) Serialize

func (t *Transaction) Serialize() ([]byte, error)

Serialize returns the binary representation of the transaction as it is signed. This is the canonical wire format: the same bytes that are hashed and signed, and that the node independently re-serializes to verify signatures.

type TransferFromSavingsOperation

type TransferFromSavingsOperation struct {
	From      string `json:"from"`
	RequestId uint32 `json:"request_id"`
	To        string `json:"to"`
	Amount    Asset  `json:"amount"`
	Memo      string `json:"memo"`
}

TransferFromSavingsOperation initiates a withdrawal from savings. RequestId must be unique per account — use an incrementing counter.

func (TransferFromSavingsOperation) OpName

func (TransferFromSavingsOperation) SerializeOp

func (o TransferFromSavingsOperation) SerializeOp() ([]byte, error)

type TransferOperation

type TransferOperation struct {
	From   string `json:"from"`
	To     string `json:"to"`
	Amount Asset  `json:"amount"`
	Memo   string `json:"memo"`
}

TransferOperation transfers HIVE or HBD between accounts.

func (TransferOperation) OpName

func (o TransferOperation) OpName() string

func (TransferOperation) SerializeOp

func (o TransferOperation) SerializeOp() ([]byte, error)

type TransferToSavingsOperation

type TransferToSavingsOperation struct {
	From   string `json:"from"`
	To     string `json:"to"`
	Amount Asset  `json:"amount"`
	Memo   string `json:"memo"`
}

TransferToSavingsOperation moves HIVE or HBD into the savings balance. Savings have a 3-day withdrawal delay.

func (TransferToSavingsOperation) OpName

func (TransferToSavingsOperation) SerializeOp

func (o TransferToSavingsOperation) SerializeOp() ([]byte, error)

type TransferToVestingOperation

type TransferToVestingOperation struct {
	From   string `json:"from"`
	To     string `json:"to"`
	Amount Asset  `json:"amount"`
}

TransferToVestingOperation converts HIVE to Hive Power (HP). Set To to "" to power up to the same account as From.

func (TransferToVestingOperation) OpName

func (TransferToVestingOperation) SerializeOp

func (o TransferToVestingOperation) SerializeOp() ([]byte, error)

type UpdateProposalOperation

type UpdateProposalOperation struct {
	ProposalId int64  `json:"proposal_id"`
	Creator    string `json:"creator"`
	DailyPay   Asset  `json:"daily_pay"`
	Subject    string `json:"subject"`
	Permlink   string `json:"permlink"`
	EndDate    string `json:"end_date,omitempty"`
}

UpdateProposalOperation updates an existing proposal's pay, subject, permlink, or end date. DailyPay can only be lowered, not increased — the chain rejects any value above the current pay. EndDate is optional — set to "" to leave unchanged. Must be in "2006-01-02T15:04:05" format if provided.

func (UpdateProposalOperation) OpName

func (o UpdateProposalOperation) OpName() string

func (UpdateProposalOperation) SerializeOp

func (o UpdateProposalOperation) SerializeOp() ([]byte, error)

type UpdateProposalVotesOperation

type UpdateProposalVotesOperation struct {
	Voter       string  `json:"voter"`
	ProposalIds []int64 `json:"proposal_ids"`
	Approve     bool    `json:"approve"`
}

UpdateProposalVotesOperation approves or removes votes for one or more proposals.

func (UpdateProposalVotesOperation) OpName

func (UpdateProposalVotesOperation) SerializeOp

func (o UpdateProposalVotesOperation) SerializeOp() ([]byte, error)

type VoteOperation

type VoteOperation struct {
	Voter    string `json:"voter"`
	Author   string `json:"author"`
	Permlink string `json:"permlink"`
	Weight   int16  `json:"weight"`
}

VoteOperation votes on a post or comment. Weight ranges from -10000 (100% downvote) to 10000 (100% upvote).

func (VoteOperation) OpName

func (o VoteOperation) OpName() string

func (VoteOperation) SerializeOp

func (o VoteOperation) SerializeOp() ([]byte, error)

type WithdrawVestingOperation

type WithdrawVestingOperation struct {
	Account       string `json:"account"`
	VestingShares Asset  `json:"vesting_shares"`
}

WithdrawVestingOperation initiates a power-down, converting HP back to HIVE over 13 weeks. Set VestingShares to ParseAsset("0.000000 VESTS") to cancel an in-progress power-down.

func (WithdrawVestingOperation) OpName

func (o WithdrawVestingOperation) OpName() string

func (WithdrawVestingOperation) SerializeOp

func (o WithdrawVestingOperation) SerializeOp() ([]byte, error)

type WitnessSetPropertiesOperation

type WitnessSetPropertiesOperation struct {
	Owner string            `json:"owner"`
	Props map[string][]byte `json:"-"` // serialized as [["key", "hexvalue"], ...]
}

WitnessSetPropertiesOperation updates witness properties using the modern key-value format. Props values are raw binary — use encoding/binary to build property values. Keys must be one of: "key", "new_signing_key", "account_creation_fee", "maximum_block_size", "hbd_interest_rate", "hbd_exchange_rate", "url", "account_subsidy_budget", "account_subsidy_decay".

func (WitnessSetPropertiesOperation) MarshalJSON

func (o WitnessSetPropertiesOperation) MarshalJSON() ([]byte, error)

func (WitnessSetPropertiesOperation) OpName

func (WitnessSetPropertiesOperation) SerializeOp

func (o WitnessSetPropertiesOperation) SerializeOp() ([]byte, error)

type WitnessUpdateOperation

type WitnessUpdateOperation struct {
	Owner           string               `json:"-"`
	Url             string               `json:"-"`
	BlockSigningKey *secp256k1.PublicKey `json:"-"`
	Props           ChainProperties      `json:"-"`
	Fee             Asset                `json:"-"`
}

WitnessUpdateOperation updates a witness's URL, signing key, chain properties, and fee. Set BlockSigningKey to nil to write 33 zero bytes, which disables the witness.

func (WitnessUpdateOperation) MarshalJSON

func (o WitnessUpdateOperation) MarshalJSON() ([]byte, error)

func (WitnessUpdateOperation) OpName

func (o WitnessUpdateOperation) OpName() string

func (WitnessUpdateOperation) SerializeOp

func (o WitnessUpdateOperation) SerializeOp() ([]byte, error)

Jump to

Keyboard shortcuts

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