Commit a0e9e6e7 authored by Mahdi Yari's avatar Mahdi Yari

Merge branch 'rebrand-hf24' into 'master'

Rebrand hf24

Closes #11

See merge request !7
parents 77d4a3ee 9120061f
......@@ -8,5 +8,6 @@
"address_prefix": "STM",
"chain_id": "beeab0de00000000000000000000000000000000000000000000000000000000",
"alternative_api_endpoints": ["https://api.hive.blog", "https://anyx.io"],
"failover_threshold": 3
"failover_threshold": 3,
"rebranded_api": false
}
......@@ -44,9 +44,12 @@ as
```js
hive.api.setOptions({ url: 'https://anyx.io' });
hive.config.set('address_prefix','STM');
hive.config.set('chain_id','0000000000000000000000000000000000000000000000000000000000000000');
hive.config.set('chain_id','beeab0de00000000000000000000000000000000000000000000000000000000');
hive.config.set('alternative_api_endpoints', ['https://api.hive.blog', 'https://anyx.io']);
```
### rebranded_api
Set `rebranded_api` to `true` for connecting to eclipse (hf24) RPC nodes.
### set
```
hive.config.set('address_prefix','STM');
......@@ -975,8 +978,10 @@ const props = {
"account_subsidy_budget": 10000, // optional
"account_subsidy_decay": 330782, // optional
"maximum_block_size": 65536, // optional
"sbd_interest_rate": "0.000 HIVE", // optional
"sbd_exchange_rate": {"base": "0.250 HBD", "quote": "1.000 HIVE"}, // optional
// "sbd_interest_rate": "0.000 HIVE", // for old api nodes - optional
"hbd_interest_rate": "0.000 HIVE", // optional
// "sbd_exchange_rate": {"base": "0.250 HBD", "quote": "1.000 HIVE"}, // for old api nodes - optional
"hbd_exchange_rate": {"base": "0.250 HBD", "quote": "1.000 HIVE"}, // optional
"url": "https://testurl", // optional
"new_signing_key": "Public Signing Key" // optional
}
......@@ -988,3 +993,13 @@ hive.broadcast.witnessSetProperties('Private Signing Key', owner, witnessOps.pro
});
```
### Auto Detect API Version
Get API version and update `rebranded_api` in config.
Note: this will update the config too based on the result.
```
var apiVersion = await hive.utils.autoDetectApiVersion();
console.log(apiVersion);
// => { rebranded_api: true }
```
{
"name": "@hiveio/hive-js",
"version": "0.8.1",
"version": "0.8.2",
"description": "Hive.js the JavaScript API for Hive blockchain",
"main": "lib/index.js",
"scripts": {
......
......@@ -20,7 +20,7 @@ import {
sign as signRequest
} from '@steemit/rpc-auth';
class Steem extends EventEmitter {
class Hive extends EventEmitter {
constructor(options = {}) {
super(options);
this._setTransport(options);
......@@ -408,6 +408,6 @@ class Steem extends EventEmitter {
}
// Export singleton instance
const steem = new Steem(config);
exports = module.exports = steem;
exports.Steem = Steem;
const hive = new Hive(config);
exports = module.exports = hive;
exports.Hive = Hive;
......@@ -14,6 +14,16 @@ var Auth = {};
var transaction = operations.transaction;
var signed_transaction = operations.signed_transaction;
// this function can be removed after hf24
const updateOperations = () => {
delete require.cache[require.resolve('./serializer/src/operations')];
operations = require('./serializer/src/operations');
transaction = operations.transaction;
signed_transaction = operations.signed_transaction;
}
updateOperations()
Auth.updateOperations = updateOperations
Auth.verify = function (name, password, auths) {
var hasKey = false;
var roles = [];
......@@ -49,7 +59,7 @@ Auth.generateKeys = function (name, password, roles) {
/**
@arg {string} name - blockchain account name
@arg {string} password - very strong password typically no shorter than a private key
@arg {array} roles - defaults to standard Steem blockchain-level roles
@arg {array} roles - defaults to standard Hive blockchain-level roles
*/
Auth.getPrivateKeys = function (name, password, roles = ['owner', 'active', 'posting', 'memo']) {
var privKeys = {};
......
......@@ -33,6 +33,10 @@ static_variant [
import types from "./types"
import SerializerImpl from "./serializer"
import config from "../../../config"
const hiveVar = () => config.get("rebranded_api") ? "hive" : "steem"
const hbdVar = () => config.get("rebranded_api") ? "hbd" : "sbd"
const {
//id_type,
......@@ -88,7 +92,7 @@ const allowed_vote_assets = new Serializer(1, {
const smt_generation_unit = new Serializer(
"smt_generation_unit", {
steem_unit: map((string), (uint16)),
[hiveVar() + "_unit"]: map((string), (uint16)),
token_unit: map((string), (uint16))
});
......@@ -332,7 +336,7 @@ let chain_properties = new Serializer(
"chain_properties", {
account_creation_fee: asset,
maximum_block_size: uint32,
sbd_interest_rate: uint16
[hbdVar() + "_interest_rate"]: uint16
}
);
......@@ -407,7 +411,7 @@ let comment_options = new Serializer(
author: string,
permlink: string,
max_accepted_payout: asset,
percent_steem_dollars: uint16,
["percent_" + hiveVar() ? "hbd" : "steem_dollars"]: uint16,
allow_votes: bool,
allow_curation_rewards: bool,
extensions: set(static_variant([
......@@ -488,8 +492,8 @@ let escrow_transfer = new Serializer(
"escrow_transfer", {
from: string,
to: string,
sbd_amount: asset,
steem_amount: asset,
[hbdVar() + "_amount"]: asset,
[hiveVar() + "_amount"]: asset,
escrow_id: uint32,
agent: string,
fee: asset,
......@@ -517,8 +521,8 @@ let escrow_release = new Serializer(
who: string,
receiver: string,
escrow_id: uint32,
sbd_amount: asset,
steem_amount: asset
[hbdVar() + "_amount"]: asset,
[hiveVar() + "_amount"]: asset
}
);
......@@ -629,8 +633,8 @@ let set_reset_account = new Serializer(
let claim_reward_balance = new Serializer(
"claim_reward_balance", {
account: string,
reward_steem: asset,
reward_sbd: asset,
["reward_" + hiveVar()]: asset,
["reward_" + hbdVar()]: asset,
reward_vests: asset
}
);
......@@ -745,7 +749,7 @@ let smt_setup = new Serializer(
contribution_begin_time: time_point_sec,
contribution_end_time: time_point_sec,
launch_time: time_point_sec,
steem_units_min: int64,
[hiveVar() + "_units_min"]: int64,
min_unit_ratio: uint32,
max_unit_ratio: uint32,
extensions: set(future_extensions)
......@@ -777,7 +781,7 @@ let smt_setup_ico_tier = new Serializer(
"smt_setup_ico_tier", {
control_account: string,
symbol: asset_symbol,
steem_units_cap: int64,
[hiveVar() + "_units_cap"]: int64,
generation_policy: static_variant([
smt_capped_generation_policy
]),
......@@ -834,8 +838,8 @@ let author_reward = new Serializer(
"author_reward", {
author: string,
permlink: string,
sbd_payout: asset,
steem_payout: asset,
[hbdVar() + "_payout"]: asset,
[hiveVar() + "_payout"]: asset,
vesting_payout: asset
}
);
......
......@@ -10,7 +10,7 @@ const chain_types = require('./ChainTypes')
import { PublicKey, Address, ecc_config } from "../../ecc"
import { fromImpliedDecimal } from "./number_utils"
import Config from "../../../config.js"
import config from "../../../config.js"
const Types = {}
module.exports = Types
......@@ -108,7 +108,7 @@ Types.asset = {
let b_copy = b.copy(b.offset, b.offset + 7)
symbol = new Buffer(b_copy.toBinary(), "binary").toString().replace(/\x00/g, "")
b.skip(7)
// "1.000 STEEM" always written with full precision
// "1.000 HIVE" always written with full precision
amount_string = fromImpliedDecimal(amount, precision)
}
......@@ -132,11 +132,11 @@ Types.asset = {
{
case "@@000000021":
precision = 3
symbol = Config.get( "address_prefix" ) == "STM" ? "STEEM" : "TESTS"
symbol = config.get( "address_prefix" ) == "STM" ? "STEEM" : "TESTS"
break
case "@@000000013":
precision = 3
symbol = Config.get( "address_prefix" ) == "STM" ? "SBD" : "TBD"
symbol = config.get( "address_prefix" ) == "STM" ? "SBD" : "TBD"
break
case "@@000000037":
precision = 6
......@@ -196,7 +196,7 @@ Types.asset = {
return object
},
toObject(object, debug = {}){
if (debug.use_default && object === undefined) { return "0.000 STEEM"; }
if (debug.use_default && object === undefined) { return "0.000 HIVE"; }
return object
}
}
......@@ -252,11 +252,11 @@ Types.asset_symbol = {
{
case "@@000000021":
precision = 3
symbol = Config.get( "address_prefix" ) == "STM" ? "STEEM" : "TESTS"
symbol = config.get( "address_prefix" ) == "STM" ? "STEEM" : "TESTS"
break
case "@@000000013":
precision = 3
symbol = Config.get( "address_prefix" ) == "STM" ? "SBD" : "TBD"
symbol = config.get( "address_prefix" ) == "STM" ? "SBD" : "TBD"
break
case "@@000000037":
precision = 6
......
import api from '../api';
exports = module.exports = steemBroadcast => {
steemBroadcast.addAccountAuth = ({ signingKey, username, authorizedUsername, role = 'posting', weight }, cb) => {
exports = module.exports = hiveBroadcast => {
hiveBroadcast.addAccountAuth = ({ signingKey, username, authorizedUsername, role = 'posting', weight }, cb) => {
api.getAccounts([username], (err, [userAccount]) => {
if (err) { return cb(new Error(err), null); }
if (!userAccount) { return cb(new Error('Invalid account name'), null); }
......@@ -23,7 +23,7 @@ exports = module.exports = steemBroadcast => {
const posting = role === 'posting' ? updatedAuthority : undefined;
/** Add authority on user account */
steemBroadcast.accountUpdate(
hiveBroadcast.accountUpdate(
signingKey,
userAccount.name,
owner,
......@@ -36,7 +36,7 @@ exports = module.exports = steemBroadcast => {
});
};
steemBroadcast.removeAccountAuth = ({ signingKey, username, authorizedUsername, role = 'posting' }, cb) => {
hiveBroadcast.removeAccountAuth = ({ signingKey, username, authorizedUsername, role = 'posting' }, cb) => {
api.getAccounts([username], (err, [userAccount]) => {
if (err) { return cb(new Error(err), null); }
if (!userAccount) { return cb(new Error('Invalid account name'), null); }
......@@ -60,7 +60,7 @@ exports = module.exports = steemBroadcast => {
const active = role === 'active' ? updatedAuthority : undefined;
const posting = role === 'posting' ? updatedAuthority : undefined;
steemBroadcast.accountUpdate(
hiveBroadcast.accountUpdate(
signingKey,
userAccount.name,
owner,
......@@ -73,7 +73,7 @@ exports = module.exports = steemBroadcast => {
});
};
steemBroadcast.addKeyAuth = ({ signingKey, username, authorizedKey, role = 'posting', weight }, cb) => {
hiveBroadcast.addKeyAuth = ({ signingKey, username, authorizedKey, role = 'posting', weight }, cb) => {
api.getAccounts([username], (err, [userAccount]) => {
if (err) { return cb(new Error(err), null); }
if (!userAccount) { return cb(new Error('Invalid account name'), null); }
......@@ -95,7 +95,7 @@ exports = module.exports = steemBroadcast => {
const posting = role === 'posting' ? updatedAuthority : undefined;
/** Add authority on user account */
steemBroadcast.accountUpdate(
hiveBroadcast.accountUpdate(
signingKey,
userAccount.name,
owner,
......@@ -108,7 +108,7 @@ exports = module.exports = steemBroadcast => {
});
};
steemBroadcast.removeKeyAuth = ({ signingKey, username, authorizedKey, role = 'posting' }, cb) => {
hiveBroadcast.removeKeyAuth = ({ signingKey, username, authorizedKey, role = 'posting' }, cb) => {
api.getAccounts([username], (err, [userAccount]) => {
if (err) { return cb(new Error(err), null); }
if (!userAccount) { return cb(new Error('Invalid account name'), null); }
......@@ -132,7 +132,7 @@ exports = module.exports = steemBroadcast => {
const active = role === 'active' ? updatedAuthority : undefined;
const posting = role === 'posting' ? updatedAuthority : undefined;
steemBroadcast.accountUpdate(
hiveBroadcast.accountUpdate(
signingKey,
userAccount.name,
owner,
......
import Promise from 'bluebird';
import newDebug from 'debug';
import broadcastHelpers from './helpers';
import formatterFactory from '../formatter';
import operations from './operations';
import steemApi from '../api';
import steemAuth from '../auth';
import hiveApi from '../api';
import hiveAuth from '../auth';
import { camelCase } from '../utils';
var operations = require('./operations');
const config = require('../config')
const HF23_CHAIN_ID = '0000000000000000000000000000000000000000000000000000000000000000'
const HF24_CHAIN_ID = 'beeab0de00000000000000000000000000000000000000000000000000000000'
const debug = newDebug('steem:broadcast');
const debug = newDebug('hive:broadcast');
const noop = function() {}
const formatter = formatterFactory(steemApi);
const formatter = formatterFactory(hiveApi);
const steemBroadcast = {};
const hiveBroadcast = {};
// Base transaction logic -----------------------------------------------------
/**
* Sign and broadcast transactions on the steem network
* Sign and broadcast transactions on the hive network
*/
steemBroadcast.send = function steemBroadcast$send(tx, privKeys, callback) {
const resultP = steemBroadcast._prepareTransaction(tx)
hiveBroadcast.send = function hiveBroadcast$send(tx, privKeys, callback) {
const resultP = hiveBroadcast._prepareTransaction(tx)
.then((transaction) => {
debug(
'Signing transaction (transaction, transaction.operations)',
......@@ -34,7 +33,7 @@ steemBroadcast.send = function steemBroadcast$send(tx, privKeys, callback) {
);
return Promise.join(
transaction,
steemAuth.signTransaction(transaction, privKeys)
hiveAuth.signTransaction(transaction, privKeys)
);
})
.spread((transaction, signedTransaction) => {
......@@ -42,7 +41,7 @@ steemBroadcast.send = function steemBroadcast$send(tx, privKeys, callback) {
'Broadcasting transaction (transaction, transaction.operations)',
transaction, transaction.operations
);
return steemApi.broadcastTransactionSynchronousAsync(
return hiveApi.broadcastTransactionSynchronousAsync(
signedTransaction
).then((result) => {
return Object.assign({}, result, signedTransaction);
......@@ -52,11 +51,11 @@ steemBroadcast.send = function steemBroadcast$send(tx, privKeys, callback) {
resultP.nodeify(callback || noop);
};
steemBroadcast._prepareTransaction = function steemBroadcast$_prepareTransaction(tx) {
const propertiesP = steemApi.getDynamicGlobalPropertiesAsync();
hiveBroadcast._prepareTransaction = function hiveBroadcast$_prepareTransaction(tx) {
const propertiesP = hiveApi.getDynamicGlobalPropertiesAsync();
return propertiesP
.then((properties) => {
const hfVersion = steemApi.getHardforkVersionAsync();
const hfVersion = hiveApi.getHardforkVersionAsync();
return hfVersion.then(HFV => {
if (HFV == '0.23.0') {
config.set('chain_id', HF23_CHAIN_ID)
......@@ -66,7 +65,7 @@ steemBroadcast._prepareTransaction = function steemBroadcast$_prepareTransaction
// Set defaults on the transaction
const chainDate = new Date(properties.time + 'Z');
const refBlockNum = (properties.last_irreversible_block_num - 1) & 0xFFFF;
return steemApi.getBlockHeaderAsync(properties.last_irreversible_block_num).then((block) => {
return hiveApi.getBlockHeaderAsync(properties.last_irreversible_block_num).then((block) => {
const headBlockId = block ? block.previous : '0000000000000000000000000000000000000000';
return Object.assign({
ref_block_num: refBlockNum,
......@@ -84,51 +83,62 @@ steemBroadcast._prepareTransaction = function steemBroadcast$_prepareTransaction
// Generated wrapper ----------------------------------------------------------
// Generate operations from operations.json
operations.forEach((operation) => {
const operationName = camelCase(operation.operation);
const operationParams = operation.params || [];
const useCommentPermlink =
operationParams.indexOf('parent_author') !== -1 &&
operationParams.indexOf('parent_permlink') !== -1;
steemBroadcast[`${operationName}With`] =
function steemBroadcast$specializedSendWith(wif, options, callback) {
debug(`Sending operation "${operationName}" with`, {options, callback});
const keys = {};
if (operation.roles && operation.roles.length) {
keys[operation.roles[0]] = wif; // TODO - Automatically pick a role? Send all?
}
return steemBroadcast.send({
extensions: [],
operations: [[operation.operation, Object.assign(
{},
options,
options.json_metadata != null ? {
json_metadata: toString(options.json_metadata),
} : {},
useCommentPermlink && options.permlink == null ? {
permlink: formatter.commentPermlink(options.parent_author, options.parent_permlink),
} : {}
)]],
}, keys, callback);
};
steemBroadcast[operationName] =
function steemBroadcast$specializedSend(wif, ...args) {
debug(`Parsing operation "${operationName}" with`, {args});
const options = operationParams.reduce((memo, param, i) => {
memo[param] = args[i]; // eslint-disable-line no-param-reassign
return memo;
}, {});
const callback = args[operationParams.length];
return steemBroadcast[`${operationName}With`](wif, options, callback);
};
});
const updateOperations = () => {
// This function declaration + module redeclaration can be removed after hf24
delete require.cache[require.resolve('./operations')];
operations = require('./operations');
hiveAuth.updateOperations();
// end module redeclaration
operations.forEach((operation) => {
const operationName = camelCase(operation.operation);
const operationParams = operation.params || [];
const useCommentPermlink =
operationParams.indexOf('parent_author') !== -1 &&
operationParams.indexOf('parent_permlink') !== -1;
hiveBroadcast[`${operationName}With`] =
function hiveBroadcast$specializedSendWith(wif, options, callback) {
debug(`Sending operation "${operationName}" with`, {options, callback});
const keys = {};
if (operation.roles && operation.roles.length) {
keys[operation.roles[0]] = wif; // TODO - Automatically pick a role? Send all?
}
return hiveBroadcast.send({
extensions: [],
operations: [[operation.operation, Object.assign(
{},
options,
options.json_metadata != null ? {
json_metadata: toString(options.json_metadata),
} : {},
useCommentPermlink && options.permlink == null ? {
permlink: formatter.commentPermlink(options.parent_author, options.parent_permlink),
} : {}
)]],
}, keys, callback);
};
hiveBroadcast[operationName] =
function hiveBroadcast$specializedSend(wif, ...args) {
debug(`Parsing operation "${operationName}" with`, {args});
const options = operationParams.reduce((memo, param, i) => {
memo[param] = args[i]; // eslint-disable-line no-param-reassign
return memo;
}, {});
const callback = args[operationParams.length];
return hiveBroadcast[`${operationName}With`](wif, options, callback);
};
});
};
hiveBroadcast.updateOperations = updateOperations
updateOperations()
const toString = obj => typeof obj === 'object' ? JSON.stringify(obj) : obj;
broadcastHelpers(steemBroadcast);
broadcastHelpers(hiveBroadcast);
Promise.promisifyAll(steemBroadcast);
Promise.promisifyAll(hiveBroadcast);
exports = module.exports = steemBroadcast;
exports = module.exports = hiveBroadcast;
const config = require("../config")
const hiveVar = () => config.get("rebranded_api") ? "hive" : "steem"
const hbdVar = () => config.get("rebranded_api") ? "hbd" : "sbd"
module.exports = [
{
"roles": ["posting", "active", "owner"],
......@@ -192,7 +196,7 @@ module.exports = [
"author",
"permlink",
"max_accepted_payout",
"percent_steem_dollars",
"percent_" + hiveVar() === 'hive' ? "hbd" : "steem_dollars",
"allow_votes",
"allow_curation_rewards",
"extensions"
......@@ -280,8 +284,8 @@ module.exports = [
"to",
"agent",
"escrow_id",
"sbd_amount",
"steem_amount",
hbdVar() + "_amount",
hiveVar() + "_amount",
"fee",
"ratification_deadline",
"escrow_expiration",
......@@ -309,8 +313,8 @@ module.exports = [
"who",
"receiver",
"escrow_id",
"sbd_amount",
"steem_amount"
hbdVar() + "_amount",
hiveVar() + "_amount"
]
},
{
......@@ -401,8 +405,8 @@ module.exports = [
"operation": "claim_reward_balance",
"params": [
"account",
"reward_steem",
"reward_sbd",
"reward_" + hiveVar(),
"reward_" + hbdVar(),
"reward_vests"
]
},
......@@ -528,7 +532,7 @@ module.exports = [
"contribution_begin_time",
"contribution_end_time",
"launch_time",
"steem_units_min",
hiveVar() + "_units_min",
"min_unit_ratio",
"max_unit_ratio",
"extensions"
......@@ -562,7 +566,7 @@ module.exports = [
"params": [
"control_account",
"symbol",
"steem_units_cap",
hiveVar() + "_units_cap",
"generation_policy",
"remove",
"extensions"
......
import get from "lodash/get";
import { key_utils } from "./auth/ecc";
import config from "./config"
module.exports = steemAPI => {
const hiveVar = () => config.get("rebranded_api") ? "hive" : "steem"
const hbdVar = () => config.get("rebranded_api") ? "hbd" : "sbd"
module.exports = hiveAPI => {
function numberWithCommas(x) {
return x.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
// Deprecating - Replacement: vestingHive
function vestingSteem(account, gprops) {
const vests = parseFloat(account.vesting_shares.split(" ")[0]);
const total_vests = parseFloat(gprops.total_vesting_shares.split(" ")[0]);
const total_vest_steem = parseFloat(
gprops.total_vesting_fund_steem.split(" ")[0]
const total_vest_hive = parseFloat(
gprops['total_vesting_fund_' + hiveVar()].split(" ")[0]
);
const vesting_steemf = total_vest_steem * (vests / total_vests);
return vesting_steemf;
const vesting_hivef = total_vest_hive * (vests / total_vests);
return vesting_hivef;