hive-tx v7
GitHub npm

Use

Utilities

The utils object has stake and mana math, vote values, reputation, app authority, login signatures, social operations, comment options, account keys, profiles, permlinks, name validation, history filters, and witness properties.

The stake, mana, and vote helpers are async and fetch what they need: the account, global properties, reward fund, and price. That data is cached for 2 seconds and shared between concurrent calls, so several helpers in a row cost one request per kind of data. Results are JavaScript numbers, fine for display and estimates.

Voting power and mana

import { utils } from 'hive-tx'

await utils.getVotingMana('alice')      // { current, max, percentage, fullAt }
await utils.getDownvoteMana('alice')
await utils.getRCMana('alice')
await utils.getEffectiveVests('alice')  // own + received - delegated - this week's power down

Instead of a name, you can pass an account object you already have, from condenser_api.get_accounts or database_api.find_accounts (or from rc_api.find_rc_accounts for getRCMana). That skips the request.

Mana is computed for now; pass a time in milliseconds as the last argument to compute it for another moment. Mana refills from 0 to 100% in 5 days, and downvote mana is 25% of voting mana. fullAt is the Date the mana will be full.

Hive Power

await utils.vestsToHP('1000.000000 VESTS')  // HIVE
await utils.hpToVests(100)                  // VESTS
utils.parseAsset('1.000 HIVE')              // { amount: 1, symbol: 'HIVE' }

parseAsset also reads the { amount, precision, nai } format of database_api.

Prices and interest

await utils.hiveToHbd(10)          // HBD, at the witnesses' median price
await utils.hbdToHive('10.000 HBD')
await utils.getHpApr()             // yearly Hive Power interest, percent
await utils.getHbdApr()            // yearly interest on HBD in savings, percent

Account value

await utils.estimateAccountValue('alice')  // HBD

Counts liquid and savings HIVE and HBD, own Hive Power (including what is delegated out), and funds in open market orders, at the median price.

Vote value

await utils.getVoteValue('alice')         // HBD, 100% vote
await utils.getVoteValue('alice', 5000)   // 50% vote
await utils.getVoteRShares('alice')       // rshares
await utils.rsharesToHBD(rshares)         // HBD for any rshares

Weight runs from -10000 to 10000. Since HF28, a vote's strength depends only on stake and weight; current mana limits how many votes an account can cast, not how strong each one is. The value includes both author and curation rewards.

Reputation

utils.formatReputation('225722985673795')  // 73.18…

Converts raw reputation, as returned by condenser_api.get_account_reputations, to the familiar score. Use Math.floor for the whole number most frontends show.

createPermlink

utils.createPermlink('Hello World!')  // 'hello-world-3f9a1c0b7e2d'
utils.createPermlink()                // '3f9a1c0b7e2d', for replies

Makes a valid permlink from a title, with a random suffix so the same title can be used twice.

Social operations

These build the custom_json operations that Hivemind reads. Sign them with the posting key.

const tx = new Transaction()
await tx.addOperation(...utils.follow('alice', 'bob'))
// also: unfollow, mute, unmute (follower, following)
//       blacklist, unblacklist: block an account (posts marked "my blacklist")
//       followBlacklist, unfollowBlacklist, followMuted, unfollowMuted: use another account's lists
//       reblog(account, author, permlink)
//       subscribe, unsubscribe(account, 'hive-123456')
//       delegateRC(from, delegatees, maxRc): delegate RC; maxRc 0 removes the delegation

unfollow clears a follow or a mute; removing a blacklist entry needs unblacklist.

App authority

Lets an app sign for a user, as "Authorize app" flows do. Grant and revoke return an account_update2 operation; sign it with the user's active key.

await utils.hasAccountAuthority('alice', 'myapp')  // posting by default; 'active' as third argument

const tx = new Transaction()
await tx.addOperation(...(await utils.grantAccountAuthority('alice', 'myapp')))
// also: revokeAccountAuthority('alice', 'myapp')

An app counts only if its weight reaches the threshold, so it can sign alone. grantAccountAuthority gives it the threshold weight unless you pass one. revokeAccountAuthority throws if the authority could no longer sign afterwards.

Login signatures

To prove a user controls an account, have them sign a message with Hive Keychain's requestSignBuffer, Hivesigner, or signMessage, then check it on your server.

await utils.verifyMessage('alice', message, signature)            // posting key
await utils.verifyMessage('alice', message, signature, 'active')  // active key

const signature = utils.signMessage(message, PrivateKey.from('5J...posting-key'))
await utils.getKeyRole('alice', publicKey)  // 'owner' | 'active' | 'posting' | 'memo' | null

Keep the message on your server with a one-time value, and accept each signature once. The key must be able to sign alone for that authority. getKeyRole tells which role a key holds, for logins with a private key or a master password.

Image uploads

images.hive.blog takes an image signed with the uploader's posting key. signImage makes that signature.

import { readFile } from 'node:fs/promises'

const account = 'alice'
const postingKey = PrivateKey.from('5J...alice-posting-key')

const image = await readFile('photo.jpg')
const signature = utils.signImage(image, postingKey)

const form = new FormData()
form.append('file', new Blob([image]), 'photo.jpg')
const res = await fetch(`https://images.hive.blog/${account}/${signature}`, { method: 'POST', body: form })
if (!res.ok) throw new Error(await res.text())  // e.g. {"error":{"name":"invalid_signature"}}
const { url } = await res.json()  // put it in the post body as ![photo](url)

The account in the URL must be the one whose key signed: with another account's name the server answers invalid_signature. The key must be able to sign alone for that account's posting (or active) authority. images.hive.blog also rate-limits uploads and refuses accounts with low reputation (below 10 in its default config; new accounts start at 25).

Comment options

await tx.addOperation('comment', comment)
await tx.addOperation(...utils.commentOptions('alice', comment.permlink, {
  beneficiaries: [{ account: 'myapp', weight: 500 }],  // 5%
  percentHbd: 0                                        // 100% Hive Power
}))

Beneficiaries are sorted for you: at most 8, adding up to 10000 or less. maxAcceptedPayout: '0.000 HBD' declines the payout. Add the options in the same transaction as the comment: beneficiaries cannot be set once it has votes.

Profiles and accounts

await utils.getProfile('alice')        // { name, about, profile_image, ... }
await utils.accountExists('newuser')  // true or false

getProfile reads posting_json_metadata, then json_metadata. The values are whatever the user wrote, so check their types before you use them.

getRequiredRole

utils.getRequiredRole(['vote', vote])          // 'posting'
utils.getRequiredRole(['transfer', transfer])  // 'active'

Returns the key role the chain requires for an operation: 'posting', 'active', or 'owner'. It throws for witness_set_properties, which is signed with the witness signing key.

Account keys

const password = utils.createPassword()  // 'P5...', show it to the user once
const { privateKeys, owner, active, posting, memo_key } = utils.generateKeys('newuser', password)

await tx.addOperation('create_claimed_account', {
  creator: 'alice',
  new_account_name: 'newuser',
  owner,
  active,
  posting,
  memo_key,
  json_metadata: '',
  extensions: []
})

utils.isValidWif('5J...')         // true or false
utils.isValidPublicKey('STM...')  // checks prefix, checksum, and curve point

generateKeys derives keys the way Hive wallets do, so the user can log in with the password. privateKeys holds the owner, active, posting, and memo keys.

validateUsername

Returns null for a valid name, or a string that explains what is wrong.

const error = utils.validateUsername('alice')
if (error) console.log(error)

makeBitMaskFilter

Builds the operation filter for condenser_api.get_account_history.

const filter = utils.makeBitMaskFilter([
  utils.operations.transfer,
  utils.operations.vote,
  utils.operations.comment
])
const history = await callRPC('condenser_api.get_account_history', [
  'alice',
  -1,
  100,
  ...filter
])

utils.operations maps operation names to their numeric ids, for example vote is 0 and transfer is 2.

buildWitnessSetProperties

Builds a witness_set_properties operation, serializing each property to hex as the chain requires.

const operation = utils.buildWitnessSetProperties('mywitness', {
  key: 'STM...current-signing-key',
  account_creation_fee: '3.000 HIVE',
  maximum_block_size: 65536,
  url: 'https://example.com'
})
const tx = new Transaction()
await tx.addOperation(...operation)

key is required and must be the witness's current signing public key. Sign with the matching private key.