beautify index page and simplify the navigation bar, add annotation to each page for next comments work

pull/21/head
Wen Zhang 5 years ago committed by Ganesha Upadhyaya
parent ff6c207e9e
commit a9e825f0e3
  1. 10
      package.json
  2. 10
      packages/harmony-account/src/account.ts
  3. 5
      packages/harmony-account/src/hdnode.ts
  4. 5
      packages/harmony-account/src/index.ts
  5. 5
      packages/harmony-account/src/types.ts
  6. 5
      packages/harmony-account/src/utils.ts
  7. 5
      packages/harmony-account/src/wallet.ts
  8. 130
      packages/harmony-contract/src/abi/abiCoder.ts
  9. 9
      packages/harmony-contract/src/abi/api.ts
  10. 5
      packages/harmony-contract/src/abi/index.ts
  11. 9
      packages/harmony-contract/src/abi/utils.ts
  12. 6
      packages/harmony-contract/src/contract.ts
  13. 5
      packages/harmony-contract/src/contractFactory.ts
  14. 5
      packages/harmony-contract/src/events/event.ts
  15. 5
      packages/harmony-contract/src/events/eventFactory.ts
  16. 12
      packages/harmony-contract/src/index.ts
  17. 5
      packages/harmony-contract/src/methods/method.ts
  18. 12
      packages/harmony-contract/src/methods/methodFactory.ts
  19. 5
      packages/harmony-contract/src/models/AbiItemModel.ts
  20. 5
      packages/harmony-contract/src/models/AbiModel.ts
  21. 5
      packages/harmony-contract/src/models/types.ts
  22. 11
      packages/harmony-contract/src/utils/decoder.ts
  23. 5
      packages/harmony-contract/src/utils/encoder.ts
  24. 24
      packages/harmony-contract/src/utils/formatter.ts
  25. 9
      packages/harmony-contract/src/utils/mapper.ts
  26. 5
      packages/harmony-contract/src/utils/options.ts
  27. 5
      packages/harmony-contract/src/utils/status.ts
  28. 5
      packages/harmony-contract/test/abiCoder.test.ts
  29. 52188
      packages/harmony-contract/test/fixtures/abiv2.ts
  30. 5
      packages/harmony-core/src/blockchain.ts
  31. 5
      packages/harmony-core/src/harmony.ts
  32. 5
      packages/harmony-core/src/harmonyExtension.ts
  33. 5
      packages/harmony-core/src/index.ts
  34. 5
      packages/harmony-core/src/truffleProvider.ts
  35. 5
      packages/harmony-core/src/types.ts
  36. 5
      packages/harmony-core/src/util.ts
  37. 47
      packages/harmony-core/test/blockchain.test.ts
  38. 5
      packages/harmony-crypto/src/address.ts
  39. 11
      packages/harmony-crypto/src/bech32.ts
  40. 5
      packages/harmony-crypto/src/bytes.ts
  41. 31
      packages/harmony-crypto/src/errors.ts
  42. 6
      packages/harmony-crypto/src/index.ts
  43. 6
      packages/harmony-crypto/src/keccak256.ts
  44. 5
      packages/harmony-crypto/src/keyTool.ts
  45. 5
      packages/harmony-crypto/src/keystore.ts
  46. 11
      packages/harmony-crypto/src/random.ts
  47. 23
      packages/harmony-crypto/src/rlp.ts
  48. 5
      packages/harmony-crypto/src/signature.ts
  49. 6
      packages/harmony-crypto/src/types.ts
  50. 5
      packages/harmony-crypto/test/address.test.ts
  51. 5
      packages/harmony-crypto/test/bytes.test.ts
  52. 5
      packages/harmony-crypto/test/keccak256.test.ts
  53. 5
      packages/harmony-crypto/test/keyTool.test.ts
  54. 5
      packages/harmony-crypto/test/rlp.test.ts
  55. 5
      packages/harmony-network/src/index.ts
  56. 5
      packages/harmony-network/src/messenger/messenger.ts
  57. 18
      packages/harmony-network/src/messenger/responseMiddleware.ts
  58. 15
      packages/harmony-network/src/providers/baseProvider.ts
  59. 5
      packages/harmony-network/src/providers/baseSocket.ts
  60. 20
      packages/harmony-network/src/providers/defaultFetcher.ts
  61. 5
      packages/harmony-network/src/providers/emitter.ts
  62. 5
      packages/harmony-network/src/providers/http.ts
  63. 5
      packages/harmony-network/src/providers/provider.ts
  64. 5
      packages/harmony-network/src/providers/ws.ts
  65. 17
      packages/harmony-network/src/rpcMethod/builder.ts
  66. 9
      packages/harmony-network/src/rpcMethod/net.ts
  67. 5
      packages/harmony-network/src/rpcMethod/rpc.ts
  68. 8
      packages/harmony-network/src/subscriptions/LogSub.ts
  69. 5
      packages/harmony-network/src/subscriptions/NewHeadersSub.ts
  70. 5
      packages/harmony-network/src/subscriptions/NewPendingTransactionsSub.ts
  71. 5
      packages/harmony-network/src/subscriptions/Subscription.ts
  72. 5
      packages/harmony-network/src/subscriptions/SyncingSub.ts
  73. 17
      packages/harmony-network/src/tracker/baseTracker.ts
  74. 9
      packages/harmony-network/src/tracker/pollingTracker.ts
  75. 9
      packages/harmony-network/src/tracker/subscribeTracker.ts
  76. 5
      packages/harmony-network/src/types.ts
  77. 5
      packages/harmony-network/src/util.ts
  78. 5
      packages/harmony-staking/src/factory.ts
  79. 6
      packages/harmony-staking/src/index.ts
  80. 5
      packages/harmony-staking/src/stakingTransaction.ts
  81. 8
      packages/harmony-staking/test/testSign.test.ts
  82. 5
      packages/harmony-transaction/src/abstractTransaction.ts
  83. 5
      packages/harmony-transaction/src/factory.ts
  84. 5
      packages/harmony-transaction/src/index.ts
  85. 5
      packages/harmony-transaction/src/shardingTransaction.ts
  86. 5
      packages/harmony-transaction/src/transaction.ts
  87. 5
      packages/harmony-transaction/src/transactionBase.ts
  88. 5
      packages/harmony-transaction/src/types.ts
  89. 5
      packages/harmony-transaction/src/utils.ts
  90. 6
      packages/harmony-transaction/test/testSend.test.ts
  91. 6
      packages/harmony-transaction/test/testSign.test.ts
  92. 5
      packages/harmony-utils/src/chain.ts
  93. 4
      packages/harmony-utils/src/errors.ts
  94. 6
      packages/harmony-utils/src/index.ts
  95. 5
      packages/harmony-utils/src/tools.ts
  96. 5
      packages/harmony-utils/src/transformers.ts
  97. 29
      packages/harmony-utils/src/utils.ts
  98. 11
      packages/harmony-utils/src/validators.ts
  99. 15
      packages/harmony-utils/test/fixture.ts
  100. 6
      packages/harmony-utils/test/transformer.test.ts
  101. Some files were not shown because too many files have changed in this diff Show More

@ -125,8 +125,8 @@
"tslib": "^1.11.1", "tslib": "^1.11.1",
"tslint": "^5.11.0", "tslint": "^5.11.0",
"tslint-config-prettier": "^1.15.0", "tslint-config-prettier": "^1.15.0",
"typedoc": "^0.15.0", "typedoc": "^0.16.9",
"typedoc-plugin-markdown": "^2.1.0", "typedoc-plugin-external-module-name": "^3.0.0",
"typescript": "^3.8.3", "typescript": "^3.8.3",
"typescript-json-schema": "^0.36.0", "typescript-json-schema": "^0.36.0",
"webpack": "^4.20.2", "webpack": "^4.20.2",
@ -140,5 +140,9 @@
} }
}, },
"name": "harmony-sdk-core", "name": "harmony-sdk-core",
"dependencies": {} "dependencies": {
"@harmony-js/core": "^0.1.36",
"tslib": "^1.10.0",
"typedoc-plugin-internal-external": "^2.1.1"
}
} }

@ -1,3 +1,9 @@
/**
* @packageDocumentation
* @module harmony-account
*
*/
import { import {
generatePrivateKey, generatePrivateKey,
getAddressFromPrivateKey, getAddressFromPrivateKey,
@ -183,6 +189,10 @@ class Account {
} }
} }
/**
* @function signTransaction
* @ignore
*/
async signTransaction( async signTransaction(
transaction: Transaction, transaction: Transaction,
updateNonce: boolean = true, updateNonce: boolean = true,

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-account
*/
import { bip39, hdkey, getAddress, BN, Signature } from '@harmony-js/crypto'; import { bip39, hdkey, getAddress, BN, Signature } from '@harmony-js/crypto';
import { import {
HDPath, HDPath,

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-account
*/
export * from './account'; export * from './account';
export * from './wallet'; export * from './wallet';
export * from './types'; export * from './types';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-account
*/
/** /**
* test type docs * test type docs
*/ */

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-account
*/
import { HttpProvider, Messenger } from '@harmony-js/network'; import { HttpProvider, Messenger } from '@harmony-js/network';
import { ChainType, ChainID } from '@harmony-js/utils'; import { ChainType, ChainID } from '@harmony-js/utils';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-account
*/
import { bip39, hdkey, EncryptOptions, getAddress, generatePrivateKey } from '@harmony-js/crypto'; import { bip39, hdkey, EncryptOptions, getAddress, generatePrivateKey } from '@harmony-js/crypto';
import { Messenger } from '@harmony-js/network'; import { Messenger } from '@harmony-js/network';
import { isPrivateKey, isAddress, ChainType } from '@harmony-js/utils'; import { isPrivateKey, isAddress, ChainType } from '@harmony-js/utils';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
// this file is mainly ported from `ethers.js`, but done some fixes // this file is mainly ported from `ethers.js`, but done some fixes
// 1. added bytesPadRight support // 1. added bytesPadRight support
// 2. ts-lint // 2. ts-lint
@ -25,8 +30,7 @@ const NegativeOne: BN = new BN(-1);
const One: BN = new BN(1); const One: BN = new BN(1);
// const Two: BN = new BN(2); // const Two: BN = new BN(2);
const Zero: BN = new BN(0); const Zero: BN = new BN(0);
const HashZero = const HashZero = '0x0000000000000000000000000000000000000000000000000000000000000000';
'0x0000000000000000000000000000000000000000000000000000000000000000';
const MaxUint256: BN = hexToBN( const MaxUint256: BN = hexToBN(
'0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
@ -73,10 +77,7 @@ const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/);
const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/); const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/);
const paramTypeArray = new RegExp(/^(.*)\[([0-9]*)\]$/); const paramTypeArray = new RegExp(/^(.*)\[([0-9]*)\]$/);
export const defaultCoerceFunc: CoerceFunc = ( export const defaultCoerceFunc: CoerceFunc = (type: string, value: any): any => {
type: string,
value: any,
): any => {
const match = type.match(paramTypeNumber); const match = type.match(paramTypeNumber);
if (match && parseInt(match[2], 10) <= 48) { if (match && parseInt(match[2], 10) <= 48) {
// return value.toNumber(); // return value.toNumber();
@ -155,9 +156,7 @@ function parseParam(param: string, allowIndexed?: boolean): ParamType {
node.type = verifyType(node.type); node.type = verifyType(node.type);
} }
node.components = [ node.components = [{ type: '', name: '', parent: node, state: { allowType: true } }];
{ type: '', name: '', parent: node, state: { allowType: true } },
];
node = node.components[0]; node = node.components[0];
break; break;
@ -415,7 +414,7 @@ function parseSignatureFunction(fragment: string): FunctionFragment {
// We have outputs // We have outputs
if (comps.length > 1) { if (comps.length > 1) {
const right = comps[1].match(regexParen); const right = comps[1].match(regexParen);
if (right === null || (right[1].trim() !== '' || right[3].trim() !== '')) { if (right === null || right[1].trim() !== '' || right[3].trim() !== '') {
throw new Error('unexpected tokens'); throw new Error('unexpected tokens');
} }
@ -439,20 +438,11 @@ function parseSignatureFunction(fragment: string): FunctionFragment {
} }
// @TODO: Allow a second boolean to expose names and modifiers // @TODO: Allow a second boolean to expose names and modifiers
export function formatSignature( export function formatSignature(fragment: EventFragment | FunctionFragment): string {
fragment: EventFragment | FunctionFragment, return fragment.name + '(' + fragment.inputs.map((i) => formatParamType(i)).join(',') + ')';
): string {
return (
fragment.name +
'(' +
fragment.inputs.map((i) => formatParamType(i)).join(',') +
')'
);
} }
export function parseSignature( export function parseSignature(fragment: string): EventFragment | FunctionFragment {
fragment: string,
): EventFragment | FunctionFragment {
if (typeof fragment === 'string') { if (typeof fragment === 'string') {
// Make sure the "returns" is surrounded by a space and all whitespace is exactly one space // Make sure the "returns" is surrounded by a space and all whitespace is exactly one space
fragment = fragment.replace(/\s/g, ' '); fragment = fragment.replace(/\s/g, ' ');
@ -548,12 +538,7 @@ class CoderNull extends Coder {
class CoderNumber extends Coder { class CoderNumber extends Coder {
readonly size: number; readonly size: number;
readonly signed: boolean; readonly signed: boolean;
constructor( constructor(coerceFunc: CoerceFunc, size: number, signed: boolean, localName: string) {
coerceFunc: CoerceFunc,
size: number,
signed: boolean,
localName: string,
) {
const name = (signed ? 'int' : 'uint') + size * 8; const name = (signed ? 'int' : 'uint') + size * 8;
super(coerceFunc, name, name, localName, false); super(coerceFunc, name, name, localName, false);
@ -597,15 +582,11 @@ class CoderNumber extends Coder {
decode(data: Uint8Array, offset: number): DecodedResult { decode(data: Uint8Array, offset: number): DecodedResult {
if (data.length < offset + 32) { if (data.length < offset + 32) {
throwError( throwError('insufficient data for ' + this.name + ' type', INVALID_ARGUMENT, {
'insufficient data for ' + this.name + ' type', arg: this.localName,
INVALID_ARGUMENT, coderType: this.name,
{ value: hexlify(data.slice(offset, offset + 32)),
arg: this.localName, });
coderType: this.name,
value: hexlify(data.slice(offset, offset + 32)),
},
);
} }
const junkLength = 32 - this.size; const junkLength = 32 - this.size;
const dataValue = hexlify(data.slice(offset + junkLength, offset + 32)); const dataValue = hexlify(data.slice(offset + junkLength, offset + 32));
@ -711,10 +692,7 @@ class CoderFixedBytes extends Coder {
return { return {
consumed: 32, consumed: 32,
value: this.coerceFunc( value: this.coerceFunc(this.name, hexlify(data.slice(offset, offset + this.length))),
this.name,
hexlify(data.slice(offset, offset + this.length)),
),
}; };
} }
} }
@ -763,11 +741,7 @@ function _encodeDynamicBytes(value: Uint8Array): Uint8Array {
return concat([uint256Coder.encode(new BN(value.length)), value, padding]); return concat([uint256Coder.encode(new BN(value.length)), value, padding]);
} }
function _decodeDynamicBytes( function _decodeDynamicBytes(data: Uint8Array, offset: number, localName: string): DecodedResult {
data: Uint8Array,
offset: number,
localName: string,
): DecodedResult {
if (data.length < offset + 32) { if (data.length < offset + 32) {
throwError('insufficient data for dynamicBytes length', INVALID_ARGUMENT, { throwError('insufficient data for dynamicBytes length', INVALID_ARGUMENT, {
arg: localName, arg: localName,
@ -920,11 +894,7 @@ function pack(coders: Coder[], values: any[]): Uint8Array {
return data; return data;
} }
function unpack( function unpack(coders: Coder[], data: Uint8Array, offset: number): DecodedResult {
coders: Coder[],
data: Uint8Array,
offset: number,
): DecodedResult {
const baseOffset = offset; const baseOffset = offset;
let consumed = 0; let consumed = 0;
const value: any = []; const value: any = [];
@ -974,12 +944,7 @@ function unpack(
class CoderArray extends Coder { class CoderArray extends Coder {
readonly coder: Coder; readonly coder: Coder;
readonly length: number; readonly length: number;
constructor( constructor(coerceFunc: CoerceFunc, coder: Coder, length: number, localName: string) {
coerceFunc: CoerceFunc,
coder: Coder,
length: number,
localName: string,
) {
const type = coder.type + '[' + (length >= 0 ? length : '') + ']'; const type = coder.type + '[' + (length >= 0 ? length : '') + ']';
const dynamic = length === -1 || coder.dynamic; const dynamic = length === -1 || coder.dynamic;
super(coerceFunc, 'array', type, localName, dynamic); super(coerceFunc, 'array', type, localName, dynamic);
@ -1033,15 +998,11 @@ class CoderArray extends Coder {
try { try {
decodedLength = uint256Coder.decode(data, offset); decodedLength = uint256Coder.decode(data, offset);
} catch (error) { } catch (error) {
throwError( throwError('insufficient data for dynamic array length', INVALID_ARGUMENT, {
'insufficient data for dynamic array length', arg: this.localName,
INVALID_ARGUMENT, coderType: 'array',
{ value: error.value,
arg: this.localName, });
coderType: 'array',
value: error.value,
},
);
} }
try { try {
count = decodedLength.value.toNumber(); count = decodedLength.value.toNumber();
@ -1168,12 +1129,7 @@ function getParamCoder(coerceFunc: CoerceFunc, param: ParamType | any): any {
value: param, value: param,
}); });
} }
return new CoderNumber( return new CoderNumber(coerceFunc, size / 8, matcher[1] === 'int', param.name || '');
coerceFunc,
size / 8,
matcher[1] === 'int',
param.name || '',
);
} }
const matcher2 = param.type.match(paramTypeBytes); const matcher2 = param.type.match(paramTypeBytes);
@ -1194,20 +1150,11 @@ function getParamCoder(coerceFunc: CoerceFunc, param: ParamType | any): any {
param = shallowCopy(param); param = shallowCopy(param);
param.type = matcher3[1]; param.type = matcher3[1];
param = deepCopy(param); param = deepCopy(param);
return new CoderArray( return new CoderArray(coerceFunc, getParamCoder(coerceFunc, param), size, param.name || '');
coerceFunc,
getParamCoder(coerceFunc, param),
size,
param.name || '',
);
} }
if (param.type.substring(0, 5) === 'tuple') { if (param.type.substring(0, 5) === 'tuple') {
return getTupleParamCoder( return getTupleParamCoder(coerceFunc, param.components || [], param.name || '');
coerceFunc,
param.components || [],
param.name || '',
);
} }
if (param.type === '') { if (param.type === '') {
@ -1307,9 +1254,7 @@ export function toUtf8String(bytes: Arrayish, ignoreErrors?: boolean): string {
} else { } else {
if (!ignoreErrors) { if (!ignoreErrors) {
if ((c & 0xc0) === 0x80) { if ((c & 0xc0) === 0x80) {
throw new Error( throw new Error('invalid utf8 byte sequence; unexpected continuation byte');
'invalid utf8 byte sequence; unexpected continuation byte',
);
} }
throw new Error('invalid utf8 byte sequence; invalid prefix'); throw new Error('invalid utf8 byte sequence; invalid prefix');
} }
@ -1350,9 +1295,7 @@ export function toUtf8String(bytes: Arrayish, ignoreErrors?: boolean): string {
if (res === null) { if (res === null) {
if (!ignoreErrors) { if (!ignoreErrors) {
throw new Error( throw new Error('invalid utf8 byte sequence; invalid continuation byte');
'invalid utf8 byte sequence; invalid continuation byte',
);
} }
continue; continue;
} }
@ -1387,10 +1330,7 @@ export function toUtf8String(bytes: Arrayish, ignoreErrors?: boolean): string {
} }
res -= 0x10000; res -= 0x10000;
result += String.fromCharCode( result += String.fromCharCode(((res >> 10) & 0x3ff) + 0xd800, (res & 0x3ff) + 0xdc00);
((res >> 10) & 0x3ff) + 0xd800,
(res & 0x3ff) + 0xdc00,
);
} }
return result; return result;
@ -1537,9 +1477,7 @@ export class AbiCoder {
coders.push(getParamCoder(this.coerceFunc, typeObject)); coders.push(getParamCoder(this.coerceFunc, typeObject));
}, this); }, this);
const encodedArray = new CoderTuple(this.coerceFunc, coders, '_').encode( const encodedArray = new CoderTuple(this.coerceFunc, coders, '_').encode(values);
values,
);
return hexlify(encodedArray); return hexlify(encodedArray);
} }

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
import { AbiCoder as ABICoder, ParamType, toUtf8Bytes } from './abiCoder'; import { AbiCoder as ABICoder, ParamType, toUtf8Bytes } from './abiCoder';
import { isObject, isArray } from '@harmony-js/utils'; import { isObject, isArray } from '@harmony-js/utils';
import { keccak256, Arrayish } from '@harmony-js/crypto'; import { keccak256, Arrayish } from '@harmony-js/crypto';
@ -124,9 +129,7 @@ export class AbiCoderClass {
decodedValue = values[index]; decodedValue = values[index];
returnValues[itemKey] = bnToString(decodedValue); returnValues[itemKey] = bnToString(decodedValue);
returnValues[nonIndexedInputItems[index].name] = bnToString( returnValues[nonIndexedInputItems[index].name] = bnToString(decodedValue);
decodedValue,
);
}); });
} }

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
import { AbiCoderClass } from './api'; import { AbiCoderClass } from './api';
import { AbiCoder as EtherCoder } from './abiCoder'; import { AbiCoder as EtherCoder } from './abiCoder';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
import { isObject, isArray } from '@harmony-js/utils'; import { isObject, isArray } from '@harmony-js/utils';
import { BN } from '@harmony-js/crypto'; import { BN } from '@harmony-js/crypto';
@ -16,9 +21,7 @@ export const flattenTypes = (includeTuple: any, puts: any[]) => {
puts.forEach((param: any) => { puts.forEach((param: any) => {
if (typeof param.components === 'object') { if (typeof param.components === 'object') {
if (param.type.substring(0, 5) !== 'tuple') { if (param.type.substring(0, 5) !== 'tuple') {
throw new Error( throw new Error('components found but type is not tuple; report on GitHub');
'components found but type is not tuple; report on GitHub',
);
} }
let suffix = ''; let suffix = '';
const arrayBracket = param.type.indexOf('['); const arrayBracket = param.type.indexOf('[');

@ -1,3 +1,9 @@
/**
* @packageDocumentation
* @module harmony-contract
*
*/
import { Wallet } from '@harmony-js/account'; import { Wallet } from '@harmony-js/account';
import { Messenger } from '@harmony-js/network'; import { Messenger } from '@harmony-js/network';
import { Transaction } from '@harmony-js/transaction'; import { Transaction } from '@harmony-js/transaction';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
import { Wallet } from '@harmony-js/account'; import { Wallet } from '@harmony-js/account';
import { Contract } from './contract'; import { Contract } from './contract';
import { ContractOptions } from './utils/options'; import { ContractOptions } from './utils/options';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
import { LogSub } from '@harmony-js/network'; import { LogSub } from '@harmony-js/network';
import { AbiItemModel } from '../models/types'; import { AbiItemModel } from '../models/types';
import { Contract } from '../contract'; import { Contract } from '../contract';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
import { isArray } from '@harmony-js/utils'; import { isArray } from '@harmony-js/utils';
import { AbiCoderClass } from '../abi/api'; import { AbiCoderClass } from '../abi/api';
import { AbiModel, AbiItemModel } from '../models/types'; import { AbiModel, AbiItemModel } from '../models/types';

@ -1,10 +1,10 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
export * from './abi/index'; export * from './abi/index';
export { export { toUtf8Bytes, toUtf8String, formatBytes32String, parseBytes32String } from './abi/abiCoder';
toUtf8Bytes,
toUtf8String,
formatBytes32String,
parseBytes32String,
} from './abi/abiCoder';
export { Contract } from './contract'; export { Contract } from './contract';
export { ContractFactory } from './contractFactory'; export { ContractFactory } from './contractFactory';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
import { Wallet } from '@harmony-js/account'; import { Wallet } from '@harmony-js/account';
import { TransactionFactory, Transaction, TxStatus } from '@harmony-js/transaction'; import { TransactionFactory, Transaction, TxStatus } from '@harmony-js/transaction';
import { RPCMethod, getResultForData, Emitter } from '@harmony-js/network'; import { RPCMethod, getResultForData, Emitter } from '@harmony-js/network';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
import { AbiCoderClass } from '../abi/api'; import { AbiCoderClass } from '../abi/api';
import { AbiModel } from '../models/types'; import { AbiModel } from '../models/types';
import { Contract } from '../contract'; import { Contract } from '../contract';
@ -21,12 +26,7 @@ export class MethodFactory {
this.methodKeys.forEach((key: string) => { this.methodKeys.forEach((key: string) => {
const newObject: any = {}; const newObject: any = {};
newObject[key] = (...params: any[]) => newObject[key] = (...params: any[]) =>
new ContractMethod( new ContractMethod(key, params, this.abiModel.getMethod(key), this.contract);
key,
params,
this.abiModel.getMethod(key),
this.contract,
);
Object.assign(this.contract.methods, newObject); Object.assign(this.contract.methods, newObject);
}); });

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
import { isArray } from '@harmony-js/utils'; import { isArray } from '@harmony-js/utils';
import { AbiItemModel, AbiOutput, AbiInput } from './types'; import { AbiItemModel, AbiOutput, AbiInput } from './types';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
import { AbiItemModel } from './types'; import { AbiItemModel } from './types';
export class AbiModel { export class AbiModel {

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
// defined by web3.js // defined by web3.js
// fixed // fixed
export interface AbiModel { export interface AbiModel {

@ -1,11 +1,12 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
import { AbiItemModel } from '../models/types'; import { AbiItemModel } from '../models/types';
import { AbiCoderClass } from '../abi/api'; import { AbiCoderClass } from '../abi/api';
export const decode = ( export const decode = (abiCoder: AbiCoderClass, abiItemModel: AbiItemModel, response: any) => {
abiCoder: AbiCoderClass,
abiItemModel: AbiItemModel,
response: any,
) => {
let argumentTopics = response.topics; let argumentTopics = response.topics;
if (!abiItemModel.anonymous) { if (!abiItemModel.anonymous) {

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
import { isArray } from '@harmony-js/utils'; import { isArray } from '@harmony-js/utils';
import { AbiItemModel } from '../models/types'; import { AbiItemModel } from '../models/types';
import { AbiCoderClass } from '../abi/api'; import { AbiCoderClass } from '../abi/api';

@ -1,9 +1,9 @@
import { /**
hexlify, * @packageDocumentation
isHexString, * @module harmony-contract
keccak256, */
toChecksumAddress,
} from '@harmony-js/crypto'; import { hexlify, isHexString, keccak256, toChecksumAddress } from '@harmony-js/crypto';
import { import {
numberToHex, numberToHex,
isArray, isArray,
@ -92,11 +92,7 @@ export const outputLogFormatter = (log: any) => {
}; };
export const inputBlockNumberFormatter = (blockNumber: any) => { export const inputBlockNumberFormatter = (blockNumber: any) => {
if ( if (blockNumber === undefined || blockNumber === null || isPredefinedBlockNumber(blockNumber)) {
blockNumber === undefined ||
blockNumber === null ||
isPredefinedBlockNumber(blockNumber)
) {
return blockNumber; return blockNumber;
} }
@ -112,11 +108,7 @@ export const inputBlockNumberFormatter = (blockNumber: any) => {
}; };
export const isPredefinedBlockNumber = (blockNumber: string) => { export const isPredefinedBlockNumber = (blockNumber: string) => {
return ( return blockNumber === 'latest' || blockNumber === 'pending' || blockNumber === 'earliest';
blockNumber === 'latest' ||
blockNumber === 'pending' ||
blockNumber === 'earliest'
);
}; };
export const inputAddressFormatter = (address: string) => { export const inputAddressFormatter = (address: string) => {

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
import { isArray } from '@harmony-js/utils'; import { isArray } from '@harmony-js/utils';
import { AbiItem } from '../models/AbiItemModel'; import { AbiItem } from '../models/AbiItemModel';
import { AbiModel } from '../models/AbiModel'; import { AbiModel } from '../models/AbiModel';
@ -86,9 +91,7 @@ export const abiMapper = (abi: any[], abiCoder: AbiCoderClass): AbiModel => {
export const isConstant = (abiItem: AbiItemModel) => { export const isConstant = (abiItem: AbiItemModel) => {
return ( return (
abiItem.stateMutability === 'view' || abiItem.stateMutability === 'view' || abiItem.stateMutability === 'pure' || abiItem.constant
abiItem.stateMutability === 'pure' ||
abiItem.constant
); );
}; };

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
export interface ContractOptions { export interface ContractOptions {
data?: string; data?: string;
shardID?: number; shardID?: number;

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-contract
*/
export enum ContractStatus { export enum ContractStatus {
INITIALISED = 'initialised', INITIALISED = 'initialised',
TESTED = 'tested', TESTED = 'tested',

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @ignore
*/
import { AbiCoder } from '../src/abi/abiCoder'; import { AbiCoder } from '../src/abi/abiCoder';
import { BN } from '@harmony-js/crypto'; import { BN } from '@harmony-js/crypto';
import { isArray } from '@harmony-js/utils'; import { isArray } from '@harmony-js/utils';

File diff suppressed because one or more lines are too long

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-core
*/
import { import {
RPCMethod, RPCMethod,
Messenger, Messenger,

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-core
*/
import * as crypto from '@harmony-js/crypto'; import * as crypto from '@harmony-js/crypto';
import * as utils from '@harmony-js/utils'; import * as utils from '@harmony-js/utils';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-core
*/
import { import {
HttpProvider, HttpProvider,
WSProvider, WSProvider,

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-core
*/
export * from './harmony'; export * from './harmony';
export * from './blockchain'; export * from './blockchain';
export * from './truffleProvider'; export * from './truffleProvider';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-core
*/
import { import {
HttpProvider, HttpProvider,
WSProvider, WSProvider,

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-core
*/
import { HttpProvider, Messenger } from '@harmony-js/network'; import { HttpProvider, Messenger } from '@harmony-js/network';
import { TransactionFactory, Transaction } from '@harmony-js/transaction'; import { TransactionFactory, Transaction } from '@harmony-js/transaction';
import { Wallet, Account } from '@harmony-js/account'; import { Wallet, Account } from '@harmony-js/account';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-core
*/
import { ChainType, ChainID, defaultConfig } from '@harmony-js/utils'; import { ChainType, ChainID, defaultConfig } from '@harmony-js/utils';
import { Harmony } from './harmony'; import { Harmony } from './harmony';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @ignore
*/
// tslint:disable-next-line: no-implicit-dependencies // tslint:disable-next-line: no-implicit-dependencies
import fetch from 'jest-fetch-mock'; import fetch from 'jest-fetch-mock';
import { Blockchain } from '../src/blockchain'; import { Blockchain } from '../src/blockchain';
@ -36,25 +41,19 @@ describe('test Blockchain', () => {
extraData: '0x', extraData: '0x',
gasLimit: '0x254a0e6f8', gasLimit: '0x254a0e6f8',
gasUsed: '0x22da16', gasUsed: '0x22da16',
hash: hash: '0x7e1ef610f700805b93cf85b1e55bce84fcbd04373252a968755366a8d2215424',
'0x7e1ef610f700805b93cf85b1e55bce84fcbd04373252a968755366a8d2215424',
logsBloom: logsBloom:
'0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
miner: '0x0000000000000000000000000000000000000000', miner: '0x0000000000000000000000000000000000000000',
mixHash: mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000',
'0x0000000000000000000000000000000000000000000000000000000000000000',
nonce: '0x0000000000000000', nonce: '0x0000000000000000',
number: '0x0', number: '0x0',
parentHash: parentHash: '0x057e52af22d94cd40626d1e157e3468219d8236847c13bb3aa11f31fd6c4e71a',
'0x057e52af22d94cd40626d1e157e3468219d8236847c13bb3aa11f31fd6c4e71a', receiptsRoot: '0xf9c8a65a3224a4c6e6ae3b9f0ee992c4cefdbe4db318c4ec52880e324f1b77bd',
receiptsRoot:
'0xf9c8a65a3224a4c6e6ae3b9f0ee992c4cefdbe4db318c4ec52880e324f1b77bd',
size: '0x2de9', size: '0x2de9',
stateRoot: stateRoot: '0x112322fee869910b9a0e390ae536addca7a2a82bac7c17a61ed43a715e845218',
'0x112322fee869910b9a0e390ae536addca7a2a82bac7c17a61ed43a715e845218',
timestamp: 1556265598, timestamp: 1556265598,
transactionsRoot: transactionsRoot: '0x7687794ce8479d36c1a6d8b161dca37d90bd824da1c36d6d8f33f7bf4015c1d0',
'0x7687794ce8479d36c1a6d8b161dca37d90bd824da1c36d6d8f33f7bf4015c1d0',
uncles: [], uncles: [],
}, },
}; };
@ -73,14 +72,12 @@ describe('test Blockchain', () => {
expect(res3.result.timestamp).toEqual(1556265598); expect(res3.result.timestamp).toEqual(1556265598);
const res4 = await bc.getBlockByHash({ const res4 = await bc.getBlockByHash({
blockHash: blockHash: '0x7e1ef610f700805b93cf85b1e55bce84fcbd04373252a968755366a8d2215424',
'0x7e1ef610f700805b93cf85b1e55bce84fcbd04373252a968755366a8d2215424',
}); });
expect(res4.responseType).toEqual('raw'); expect(res4.responseType).toEqual('raw');
expect(res4.result.size).toEqual('0x2de9'); expect(res4.result.size).toEqual('0x2de9');
const res5 = await bc.getBlockByHash({ const res5 = await bc.getBlockByHash({
blockHash: blockHash: '0x7e1ef610f700805b93cf85b1e55bce84fcbd04373252a968755366a8d2215424',
'0x7e1ef610f700805b93cf85b1e55bce84fcbd04373252a968755366a8d2215424',
returnObject: true, returnObject: true,
}); });
expect(res5.responseType).toEqual('raw'); expect(res5.responseType).toEqual('raw');
@ -94,14 +91,12 @@ describe('test Blockchain', () => {
jsonrpc: '2.0', jsonrpc: '2.0',
id: 1, id: 1,
result: { result: {
blockHash: blockHash: '0x359036996c7ad7fdaa42b18de2fc157ae97d4cd3f32c688af349225f7e8f8fc6',
'0x359036996c7ad7fdaa42b18de2fc157ae97d4cd3f32c688af349225f7e8f8fc6',
blockNumber: '0x1', blockNumber: '0x1',
from: '0x15a128e599b74842bccba860311efa92991bffb5', from: '0x15a128e599b74842bccba860311efa92991bffb5',
gas: '0x81650', gas: '0x81650',
gasPrice: '0x0', gasPrice: '0x0',
hash: hash: '0x9a71ea0839511c95b0818bd54a38ab56a05337a8282245d853d0ae3a1aedd7da',
'0x9a71ea0839511c95b0818bd54a38ab56a05337a8282245d853d0ae3a1aedd7da',
input: input:
'0x6080604052678ac7230489e80000600155600280546001600160a01b0319163317905561014d806100316000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c806327c78c421461003b5780634ddd108a14610063575b600080fd5b6100616004803603602081101561005157600080fd5b50356001600160a01b031661007d565b005b61006b61011c565b60408051918252519081900360200190f35b6002546001600160a01b0316331461009457600080fd5b600154303110156100a457600080fd5b6001600160a01b03811660009081526020819052604090205460ff16156100ca57600080fd5b6001600160a01b038116600081815260208190526040808220805460ff1916600190811790915554905181156108fc0292818181858888f19350505050158015610118573d6000803e3d6000fd5b5050565b30319056fea165627a7a72305820b83c347551d539b44b318fb7b4601a635a7d3a6d7063d11e6e05e4886b6d88050029', '0x6080604052678ac7230489e80000600155600280546001600160a01b0319163317905561014d806100316000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c806327c78c421461003b5780634ddd108a14610063575b600080fd5b6100616004803603602081101561005157600080fd5b50356001600160a01b031661007d565b005b61006b61011c565b60408051918252519081900360200190f35b6002546001600160a01b0316331461009457600080fd5b600154303110156100a457600080fd5b6001600160a01b03811660009081526020819052604090205460ff16156100ca57600080fd5b6001600160a01b038116600081815260208190526040808220805460ff1916600190811790915554905181156108fc0292818181858888f19350505050158015610118573d6000803e3d6000fd5b5050565b30319056fea165627a7a72305820b83c347551d539b44b318fb7b4601a635a7d3a6d7063d11e6e05e4886b6d88050029',
nonce: '0x0', nonce: '0x0',
@ -117,16 +112,14 @@ describe('test Blockchain', () => {
runMocks(mockRpcResponse, 4); runMocks(mockRpcResponse, 4);
const res1 = await bc.getTransactionByHash({ const res1 = await bc.getTransactionByHash({
txnHash: txnHash: '0x9a71ea0839511c95b0818bd54a38ab56a05337a8282245d853d0ae3a1aedd7da',
'0x9a71ea0839511c95b0818bd54a38ab56a05337a8282245d853d0ae3a1aedd7da',
}); });
expect(res1.responseType).toEqual('raw'); expect(res1.responseType).toEqual('raw');
expect(res1.result.blockHash).toEqual( expect(res1.result.blockHash).toEqual(
'0x359036996c7ad7fdaa42b18de2fc157ae97d4cd3f32c688af349225f7e8f8fc6', '0x359036996c7ad7fdaa42b18de2fc157ae97d4cd3f32c688af349225f7e8f8fc6',
); );
const res2 = await bc.getTransactionByBlockHashAndIndex({ const res2 = await bc.getTransactionByBlockHashAndIndex({
blockHash: blockHash: '0x359036996c7ad7fdaa42b18de2fc157ae97d4cd3f32c688af349225f7e8f8fc6',
'0x359036996c7ad7fdaa42b18de2fc157ae97d4cd3f32c688af349225f7e8f8fc6',
index: '0x0', index: '0x0',
}); });
expect(res2.responseType).toEqual('raw'); expect(res2.responseType).toEqual('raw');
@ -161,8 +154,7 @@ describe('test Blockchain', () => {
runMocks(mockRpcResponse, 5); runMocks(mockRpcResponse, 5);
const res1 = await bc.getBlockTransactionCountByHash({ const res1 = await bc.getBlockTransactionCountByHash({
blockHash: blockHash: '0x7e1ef610f700805b93cf85b1e55bce84fcbd04373252a968755366a8d2215424',
'0x7e1ef610f700805b93cf85b1e55bce84fcbd04373252a968755366a8d2215424',
}); });
expect(res1.result).toEqual('0x65'); expect(res1.result).toEqual('0x65');
try { try {
@ -223,8 +215,7 @@ describe('test Blockchain', () => {
const mockRpcResponse = { const mockRpcResponse = {
jsonrpc: '2.0', jsonrpc: '2.0',
id: 1, id: 1,
result: result: '0x0000000000000000000000000000000000000000000000000000000000000000',
'0x0000000000000000000000000000000000000000000000000000000000000000',
}; };
// set mocks to test methods // set mocks to test methods
runMocks(mockRpcResponse, 2); runMocks(mockRpcResponse, 2);

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-crypto
*/
import { isAddress, isBech32Address, isBech32TestNetAddress } from '@harmony-js/utils'; import { isAddress, isBech32Address, isBech32TestNetAddress } from '@harmony-js/utils';
import { toChecksumAddress } from './keyTool'; import { toChecksumAddress } from './keyTool';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-crypto
*/
import { isAddress } from '@harmony-js/utils'; import { isAddress } from '@harmony-js/utils';
import { toChecksumAddress } from './keyTool'; import { toChecksumAddress } from './keyTool';
@ -192,11 +197,7 @@ export const toBech32 = (address: string, useHRP: string = HRP): string => {
throw new Error('Invalid address format.'); throw new Error('Invalid address format.');
} }
const addrBz = convertBits( const addrBz = convertBits(Buffer.from(address.replace('0x', ''), 'hex'), 8, 5);
Buffer.from(address.replace('0x', ''), 'hex'),
8,
5,
);
if (addrBz === null) { if (addrBz === null) {
throw new Error('Could not convert byte Buffer to 5-bit Buffer'); throw new Error('Could not convert byte Buffer to 5-bit Buffer');

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-crypto
*/
// This file is ported from ether.js/src.ts/utils/bytes.ts // This file is ported from ether.js/src.ts/utils/bytes.ts
// and done some fixes // and done some fixes

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-crypto
*/
// This file is ported from ether.js/src.ts/errors.ts // This file is ported from ether.js/src.ts/errors.ts
// Unknown Error // Unknown Error
@ -62,11 +67,7 @@ let _permanentCensorErrors = false;
let _censorErrors = false; let _censorErrors = false;
// @TODO: Enum // @TODO: Enum
export function throwError( export function throwError(message: string, code: string | null | undefined, params: any): never {
message: string,
code: string | null | undefined,
params: any,
): never {
if (_censorErrors) { if (_censorErrors) {
throw new Error('unknown error'); throw new Error('unknown error');
} }
@ -111,11 +112,7 @@ export function checkNew(self: any, kind: any): void {
} }
} }
export function checkArgumentCount( export function checkArgumentCount(count: number, expectedCount: number, suffix?: string): void {
count: number,
expectedCount: number,
suffix?: string,
): void {
if (!suffix) { if (!suffix) {
suffix = ''; suffix = '';
} }
@ -155,18 +152,14 @@ export function checkNormalize(): void {
} }
}); });
if ( if (String.fromCharCode(0xe9).normalize('NFD') !== String.fromCharCode(0x65, 0x0301)) {
String.fromCharCode(0xe9).normalize('NFD') !==
String.fromCharCode(0x65, 0x0301)
) {
throw new Error('broken implementation'); throw new Error('broken implementation');
} }
} catch (error) { } catch (error) {
throwError( throwError('platform missing String.prototype.normalize', UNSUPPORTED_OPERATION, {
'platform missing String.prototype.normalize', operation: 'String.prototype.normalize',
UNSUPPORTED_OPERATION, form: error.message,
{ operation: 'String.prototype.normalize', form: error.message }, });
);
} }
} }

@ -1,3 +1,9 @@
/**
* @packageDocumentation
* @module harmony-crypto
* @ignore
*/
import hdkey from 'hdkey'; import hdkey from 'hdkey';
import bip39 from 'bip39'; import bip39 from 'bip39';
import BN from 'bn.js'; import BN from 'bn.js';

@ -1,3 +1,9 @@
/**
* @packageDocumentation
* @module harmony-crypto
* @ignore
*/
// this file is ported from 'ether.js' and done some fixes // this file is ported from 'ether.js' and done some fixes
import * as sha3 from 'js-sha3'; import * as sha3 from 'js-sha3';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-crypto
*/
import elliptic from 'elliptic'; import elliptic from 'elliptic';
import * as bytes from './bytes'; import * as bytes from './bytes';
import * as errors from './errors'; import * as errors from './errors';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-crypto
*/
import aes from 'aes-js'; import aes from 'aes-js';
// import scrypt from 'scrypt.js'; // import scrypt from 'scrypt.js';
import scrypt from 'scrypt-shim'; import scrypt from 'scrypt-shim';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @ignore
*/
/** /**
* @function randomBytes * @function randomBytes
* @description Uses JS-native CSPRNG to generate a specified number of bytes. * @description Uses JS-native CSPRNG to generate a specified number of bytes.
@ -8,11 +13,7 @@
export const randomBytes = (bytes: number): string => { export const randomBytes = (bytes: number): string => {
let randBz: number[] | Uint8Array; let randBz: number[] | Uint8Array;
if ( if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) {
typeof window !== 'undefined' &&
window.crypto &&
window.crypto.getRandomValues
) {
randBz = window.crypto.getRandomValues(new Uint8Array(bytes)); randBz = window.crypto.getRandomValues(new Uint8Array(bytes));
} else if (typeof require !== 'undefined') { } else if (typeof require !== 'undefined') {
randBz = require('crypto').randomBytes(bytes); randBz = require('crypto').randomBytes(bytes);

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-crypto
*/
// this file is ported from https://github.com/ethers-io/ethers.js/blob/master/src.ts/utils/rlp.ts // this file is ported from https://github.com/ethers-io/ethers.js/blob/master/src.ts/utils/rlp.ts
// and done some fixes // and done some fixes
import { arrayify, hexlify, Arrayish } from './bytes'; import { arrayify, hexlify, Arrayish } from './bytes';
@ -11,11 +16,7 @@ function arrayifyInteger(value: number): number[] {
return result; return result;
} }
function unarrayifyInteger( function unarrayifyInteger(data: Uint8Array, offset: number, length: number): number {
data: Uint8Array,
offset: number,
length: number,
): number {
let result = 0; let result = 0;
for (let i = 0; i < length; i++) { for (let i = 0; i < length; i++) {
result = result * 256 + data[offset + i]; result = result * 256 + data[offset + i];
@ -89,10 +90,7 @@ function _decodeChildren(
} }
// returns { consumed: number, result: Object } // returns { consumed: number, result: Object }
function _decode( function _decode(data: Uint8Array, offset: number): { consumed: number; result: any } {
data: Uint8Array,
offset: number,
): { consumed: number; result: any } {
if (data.length === 0) { if (data.length === 0) {
throw new Error('invalid rlp data'); throw new Error('invalid rlp data');
} }
@ -109,12 +107,7 @@ function _decode(
throw new Error('to short'); throw new Error('to short');
} }
return _decodeChildren( return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length);
data,
offset,
offset + 1 + lengthLength,
lengthLength + length,
);
} else if (data[offset] >= 0xc0) { } else if (data[offset] >= 0xc0) {
const length = data[offset] - 0xc0; const length = data[offset] - 0xc0;
if (offset + 1 + length > data.length) { if (offset + 1 + length > data.length) {

@ -2,3 +2,8 @@
// //
// This software is released under the MIT License. // This software is released under the MIT License.
// https://opensource.org/licenses/MIT // https://opensource.org/licenses/MIT
/**
* @packageDocumentation
* @ignore
*/

@ -1,3 +1,9 @@
/**
* @packageDocumentation
* @module harmony-crypto
* @ignore
*/
export type KDF = 'pbkdf2' | 'scrypt'; export type KDF = 'pbkdf2' | 'scrypt';
export interface PBKDF2Params { export interface PBKDF2Params {

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @ignore
*/
import { getAddress, HarmonyAddress } from '../src/address'; import { getAddress, HarmonyAddress } from '../src/address';
import { randomBytes } from '../src/random'; import { randomBytes } from '../src/random';
import { toBech32, fromBech32, HRP, tHRP } from '../src/bech32'; import { toBech32, fromBech32, HRP, tHRP } from '../src/bech32';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @ignore
*/
import * as bytes from '../src/bytes'; import * as bytes from '../src/bytes';
describe('Bytes', () => { describe('Bytes', () => {

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @ignore
*/
import * as hash from '../src/keccak256'; import * as hash from '../src/keccak256';
import hashes from './fixtures/hashes.json'; import hashes from './fixtures/hashes.json';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @ignore
*/
import * as keys from '../src/keyTool'; import * as keys from '../src/keyTool';
import { isPrivateKey, isAddress, isPublicKey } from '@harmony-js/utils'; import { isPrivateKey, isAddress, isPublicKey } from '@harmony-js/utils';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @ignore
*/
import * as rlp from '../src/rlp'; import * as rlp from '../src/rlp';
import cases from './fixtures/rlpcoder.json'; import cases from './fixtures/rlpcoder.json';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import mitt from 'mitt'; import mitt from 'mitt';
export { mitt }; export { mitt };
// provider related // provider related

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import { HarmonyCore, ChainType, isString, ChainID, defaultConfig } from '@harmony-js/utils'; import { HarmonyCore, ChainType, isString, ChainID, defaultConfig } from '@harmony-js/utils';
import { JsonRpc } from '../rpcMethod/builder'; import { JsonRpc } from '../rpcMethod/builder';
import { ResponseMiddleware } from './responseMiddleware'; import { ResponseMiddleware } from './responseMiddleware';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import { RPCResponseBody } from '../types'; import { RPCResponseBody } from '../types';
import { isObject } from '@harmony-js/utils'; import { isObject } from '@harmony-js/utils';
/** /**
@ -19,15 +24,11 @@ class ResponseMiddleware {
} }
get getResult() { get getResult() {
return isObject(this.result) return isObject(this.result) ? { ...this.result, responseType: 'result' } : this.result;
? { ...this.result, responseType: 'result' }
: this.result;
} }
get getError() { get getError() {
return isObject(this.error) return isObject(this.error) ? { ...this.error, responseType: 'error' } : this.error;
? { ...this.error, responseType: 'error' }
: this.error;
} }
get getRaw() { get getRaw() {
@ -37,10 +38,7 @@ class ResponseMiddleware {
getResponseType(): string { getResponseType(): string {
if (this.error) { if (this.error) {
return 'error'; return 'error';
} else if ( } else if (this.result || (this.result === null && this.result !== undefined)) {
this.result ||
(this.result === null && this.result !== undefined)
) {
return 'result'; return 'result';
} else { } else {
return 'raw'; return 'raw';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import { ReqMiddleware, ResMiddleware, MiddlewareType } from '../types'; import { ReqMiddleware, ResMiddleware, MiddlewareType } from '../types';
import { RPCMethod } from '../rpcMethod/rpc'; import { RPCMethod } from '../rpcMethod/rpc';
@ -28,11 +33,7 @@ class BaseProvider {
this.url = url; this.url = url;
} }
protected pushMiddleware( protected pushMiddleware(fn: any, type: MiddlewareType, match: string | RPCMethod | RegExp) {
fn: any,
type: MiddlewareType,
match: string | RPCMethod | RegExp,
) {
if (type !== MiddlewareType.REQ && type !== MiddlewareType.RES) { if (type !== MiddlewareType.REQ && type !== MiddlewareType.RES) {
throw new Error('Please specify the type of middleware being added'); throw new Error('Please specify the type of middleware being added');
} }
@ -44,9 +45,7 @@ class BaseProvider {
this.resMiddleware.set(match, [...current, <ResMiddleware>fn]); this.resMiddleware.set(match, [...current, <ResMiddleware>fn]);
} }
} }
protected getMiddleware( protected getMiddleware(method: RPCMethod | string): [ReqMiddleware[], ResMiddleware[]] {
method: RPCMethod | string,
): [ReqMiddleware[], ResMiddleware[]] {
const requests: ReqMiddleware[] = []; const requests: ReqMiddleware[] = [];
const responses: ResMiddleware[] = []; const responses: ResMiddleware[] = [];

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import { isWs } from '@harmony-js/utils'; import { isWs } from '@harmony-js/utils';
import mitt from 'mitt'; import mitt from 'mitt';
import { BaseProvider } from './baseProvider'; import { BaseProvider } from './baseProvider';

@ -1,13 +1,15 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import fetch from 'cross-fetch'; import fetch from 'cross-fetch';
import { RPCRequest, RPCResponseBody, RPCError, RPCResult } from '../types'; import { RPCRequest, RPCResponseBody, RPCError, RPCResult } from '../types';
export const fetchRPC = { export const fetchRPC = {
requestHandler: (request: RPCRequest<any[]>, headers: any) => requestHandler: (request: RPCRequest<any[]>, headers: any) =>
fetch(request.url, { fetch(request.url, {
method: method: request.options && request.options.method ? request.options.method : 'POST',
request.options && request.options.method
? request.options.method
: 'POST',
cache: 'no-cache', cache: 'no-cache',
mode: 'cors', mode: 'cors',
redirect: 'follow', redirect: 'follow',
@ -15,16 +17,10 @@ export const fetchRPC = {
body: JSON.stringify(request.payload), body: JSON.stringify(request.payload),
headers: { headers: {
...headers, ...headers,
...(request.options && request.options.headers ...(request.options && request.options.headers ? request.options.headers : {}),
? request.options.headers
: {}),
}, },
}), }),
responseHandler: ( responseHandler: (response: Response, request: RPCRequest<any>, handler: any) =>
response: Response,
request: RPCRequest<any>,
handler: any,
) =>
response response
.json() .json()
.then((body: RPCResponseBody<RPCResult, RPCError>) => { .then((body: RPCResponseBody<RPCResult, RPCError>) => {

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import mitt from 'mitt'; import mitt from 'mitt';
class Emitter { class Emitter {

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import { BaseProvider } from './baseProvider'; import { BaseProvider } from './baseProvider';
import { fetchRPC } from './defaultFetcher'; import { fetchRPC } from './defaultFetcher';
import { composeMiddleware, performRPC, DEFAULT_TIMEOUT, DEFAULT_HEADERS } from '../rpcMethod/net'; import { composeMiddleware, performRPC, DEFAULT_TIMEOUT, DEFAULT_HEADERS } from '../rpcMethod/net';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import { HttpProvider } from './http'; import { HttpProvider } from './http';
import { WSProvider } from './ws'; import { WSProvider } from './ws';
import { defaultConfig, isHttp, isWs } from '@harmony-js/utils'; import { defaultConfig, isHttp, isWs } from '@harmony-js/utils';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
// TODO: implement Websocket Provider // TODO: implement Websocket Provider
import { w3cwebsocket as W3CWebsocket } from 'websocket'; import { w3cwebsocket as W3CWebsocket } from 'websocket';
import { import {

@ -1,5 +1,10 @@
import {RPCRequestPayload} from '../types'; /**
import {RPCMethod} from './rpc'; * @packageDocumentation
* @module harmony-network
*/
import { RPCRequestPayload } from '../types';
import { RPCMethod } from './rpc';
/** /**
* @class JsonRpc * @class JsonRpc
* @description json rpc instance * @description json rpc instance
@ -37,11 +42,7 @@ class JsonRpc {
this.messageId += 1; this.messageId += 1;
const sendParams = const sendParams =
params === undefined params === undefined ? [] : typeof params === 'string' ? [params] : [...params];
? []
: typeof params === 'string'
? [params]
: [...params];
return { return {
jsonrpc: '2.0', jsonrpc: '2.0',
@ -52,4 +53,4 @@ class JsonRpc {
}; };
} }
export {JsonRpc}; export { JsonRpc };

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
export const DEFAULT_TIMEOUT: number = 120000; export const DEFAULT_TIMEOUT: number = 120000;
export const DEFAULT_HEADERS: object = { 'Content-Type': 'application/json' }; export const DEFAULT_HEADERS: object = { 'Content-Type': 'application/json' };
@ -21,9 +26,7 @@ export const performRPC = async (request: any, handler: any, fetcher: any) => {
try { try {
const response = await _fetch( const response = await _fetch(
fetcher.requestHandler(request, DEFAULT_HEADERS), fetcher.requestHandler(request, DEFAULT_HEADERS),
request.options && request.options.timeout request.options && request.options.timeout ? request.options.timeout : DEFAULT_TIMEOUT,
? request.options.timeout
: DEFAULT_TIMEOUT,
); );
return fetcher.responseHandler(response, request, handler); return fetcher.responseHandler(response, request, handler);
} catch (err) { } catch (err) {

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
export const enum RPCMethod { export const enum RPCMethod {
// 1. hmy_getBlockByHash // 1. hmy_getBlockByHash
GetBlockByHash = 'hmy_getBlockByHash', GetBlockByHash = 'hmy_getBlockByHash',

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import { Messenger } from '../messenger/messenger'; import { Messenger } from '../messenger/messenger';
import { SubscriptionMethod } from './Subscription'; import { SubscriptionMethod } from './Subscription';
import { RPCMethod } from '../rpcMethod/rpc'; import { RPCMethod } from '../rpcMethod/rpc';
@ -11,7 +16,8 @@ export class LogSub extends SubscriptionMethod {
async subscribe() { async subscribe() {
if ( if (
(this.options.fromBlock && this.options.fromBlock !== 'latest') || (this.options.fromBlock && this.options.fromBlock !== 'latest') ||
(this.options.fromBlock === 0 || this.options.fromBlock === '0x') this.options.fromBlock === 0 ||
this.options.fromBlock === '0x'
) { ) {
try { try {
const getPastLogs = await this.messenger.send( const getPastLogs = await this.messenger.send(

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import { Messenger } from '../messenger/messenger'; import { Messenger } from '../messenger/messenger';
import { SubscriptionMethod } from './Subscription'; import { SubscriptionMethod } from './Subscription';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import { Messenger } from '../messenger/messenger'; import { Messenger } from '../messenger/messenger';
import { SubscriptionMethod } from './Subscription'; import { SubscriptionMethod } from './Subscription';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import { Messenger } from '../messenger/messenger'; import { Messenger } from '../messenger/messenger';
import { RPCMethod } from '../rpcMethod/rpc'; import { RPCMethod } from '../rpcMethod/rpc';
import { WSProvider } from '../providers/ws'; import { WSProvider } from '../providers/ws';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import { Messenger } from '../messenger/messenger'; import { Messenger } from '../messenger/messenger';
import { SubscriptionMethod } from './Subscription'; import { SubscriptionMethod } from './Subscription';

@ -1,10 +1,14 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import { isHex, hexToNumber } from '@harmony-js/utils'; import { isHex, hexToNumber } from '@harmony-js/utils';
import { Emitter } from '../providers/emitter'; import { Emitter } from '../providers/emitter';
const sec = 1000; const sec = 1000;
const calculateSum = (accumulator: number, currentValue: number) => const calculateSum = (accumulator: number, currentValue: number) => accumulator + currentValue;
accumulator + currentValue;
const blockTrackerEvents = ['sync', 'latest']; const blockTrackerEvents = ['sync', 'latest'];
export class BaseBlockTracker extends Emitter { export class BaseBlockTracker extends Emitter {
@ -55,9 +59,7 @@ export class BaseBlockTracker extends Emitter {
return this._currentBlock; return this._currentBlock;
} }
// wait for a new latest block // wait for a new latest block
const latestBlock = await new Promise((resolve) => const latestBlock = await new Promise((resolve) => this.once('latest', resolve));
this.once('latest', resolve),
);
// return newly set current block // return newly set current block
return latestBlock; return latestBlock;
} }
@ -169,10 +171,7 @@ export class BaseBlockTracker extends Emitter {
// clear any existing timeout // clear any existing timeout
this._cancelBlockResetTimeout(); this._cancelBlockResetTimeout();
// clear latest block when stale // clear latest block when stale
this._blockResetTimeout = setTimeout( this._blockResetTimeout = setTimeout(this._resetCurrentBlock, this._blockResetDuration);
this._resetCurrentBlock,
this._blockResetDuration,
);
// nodejs - dont hold process open // nodejs - dont hold process open
if (this._blockResetTimeout.unref) { if (this._blockResetTimeout.unref) {
this._blockResetTimeout.unref(); this._blockResetTimeout.unref();

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import { BaseBlockTracker } from './baseTracker'; import { BaseBlockTracker } from './baseTracker';
import { Messenger } from '../messenger/messenger'; import { Messenger } from '../messenger/messenger';
import { RPCMethod } from '../rpcMethod/rpc'; import { RPCMethod } from '../rpcMethod/rpc';
@ -83,9 +88,7 @@ export class PollingBlockTracker extends BaseBlockTracker {
await timeout(this._pollingInterval, !this._keepEventLoopActive); await timeout(this._pollingInterval, !this._keepEventLoopActive);
} catch (err) { } catch (err) {
const newErr = new Error( const newErr = new Error(
`PollingBlockTracker - encountered an error while attempting to update latest block:\n${ `PollingBlockTracker - encountered an error while attempting to update latest block:\n${err.stack}`,
err.stack
}`,
); );
try { try {
this.emit('error', newErr); this.emit('error', newErr);

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import { Messenger } from '../messenger/messenger'; import { Messenger } from '../messenger/messenger';
import { WSProvider } from '../providers/ws'; import { WSProvider } from '../providers/ws';
import { BaseBlockTracker } from './baseTracker'; import { BaseBlockTracker } from './baseTracker';
@ -35,9 +40,7 @@ export class SubscribeBlockTracker extends BaseBlockTracker {
if (blockNumber.isError()) { if (blockNumber.isError()) {
throw blockNumber.message; throw blockNumber.message;
} else if (blockNumber.isResult()) { } else if (blockNumber.isResult()) {
const subs = await this.messenger.subscribe(RPCMethod.Subscribe, [ const subs = await this.messenger.subscribe(RPCMethod.Subscribe, ['newHeads']);
'newHeads',
]);
this.subscriptionId = subs; this.subscriptionId = subs;
subs[0].onData(this._handleSubData); subs[0].onData(this._handleSubData);

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import { RPCMethod, RPCErrorCode } from './rpcMethod/rpc'; import { RPCMethod, RPCErrorCode } from './rpcMethod/rpc';
export type ReqMiddleware = Map<string | RPCMethod | RegExp, any[]>; export type ReqMiddleware = Map<string | RPCMethod | RegExp, any[]>;

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-network
*/
import { ResponseMiddleware } from './messenger/responseMiddleware'; import { ResponseMiddleware } from './messenger/responseMiddleware';
/** /**

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-staking
*/
import { Messenger } from '@harmony-js/network'; import { Messenger } from '@harmony-js/network';
import { Signature } from '@harmony-js/crypto'; import { Signature } from '@harmony-js/crypto';

@ -1,2 +1,8 @@
/**
* @packageDocumentation
* @module harmony-staking
* @ignore
*/
export * from './stakingTransaction'; export * from './stakingTransaction';
export * from './factory'; export * from './factory';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-staking
*/
// tslint:disable: max-classes-per-file // tslint:disable: max-classes-per-file
import { import {

@ -1,4 +1,10 @@
// tslint:disable-next-line: no-implicit-dependencies /**
* @packageDocumentation
* @module harmony-staking
* @ignore
*/
/ tslint:disable-next-line: no-implicit-dependencies
import { Wallet } from '@harmony-js/account'; import { Wallet } from '@harmony-js/account';
import { getAddressFromPrivateKey } from '@harmony-js/crypto'; import { getAddressFromPrivateKey } from '@harmony-js/crypto';
import { HttpProvider, Messenger } from '@harmony-js/network'; import { HttpProvider, Messenger } from '@harmony-js/network';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-transaction
*/
import { Messenger } from '@harmony-js/network'; import { Messenger } from '@harmony-js/network';
import { TxStatus } from './types'; import { TxStatus } from './types';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-transaction
*/
import { getContractAddress, getAddress } from '@harmony-js/crypto'; import { getContractAddress, getAddress } from '@harmony-js/crypto';
import { Messenger } from '@harmony-js/network'; import { Messenger } from '@harmony-js/network';
import { Transaction } from './transaction'; import { Transaction } from './transaction';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-transaction
*/
export * from './factory'; export * from './factory';
export * from './transaction'; export * from './transaction';
export * from './shardingTransaction'; export * from './shardingTransaction';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-transaction
*/
import { Messenger } from '@harmony-js/network'; import { Messenger } from '@harmony-js/network';
import { AddressSuffix } from '@harmony-js/utils'; import { AddressSuffix } from '@harmony-js/utils';
import { Transaction } from './transaction'; import { Transaction } from './transaction';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-transaction
*/
import { import {
BN, BN,
encode, encode,

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-transaction
*/
import { BN, getAddress, HarmonyAddress } from '@harmony-js/crypto'; import { BN, getAddress, HarmonyAddress } from '@harmony-js/crypto';
import { hexToNumber } from '@harmony-js/utils'; import { hexToNumber } from '@harmony-js/utils';
import { Messenger, RPCMethod, Emitter, HttpProvider, NewHeaders } from '@harmony-js/network'; import { Messenger, RPCMethod, Emitter, HttpProvider, NewHeaders } from '@harmony-js/network';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-transaction
*/
import { BN, Signature } from '@harmony-js/crypto'; import { BN, Signature } from '@harmony-js/crypto';
export interface TxParams { export interface TxParams {
id: string; id: string;

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-transaction
*/
import { hexToNumber, isHex, isAddress, strip0x, ChainType } from '@harmony-js/utils'; import { hexToNumber, isHex, isAddress, strip0x, ChainType } from '@harmony-js/utils';
import { import {
decode, decode,

@ -1,3 +1,9 @@
/**
* @packageDocumentation
* @module harmony-transaction
* @ignore
*/
import { TransactionFactory, Transaction, TxStatus } from '../src'; import { TransactionFactory, Transaction, TxStatus } from '../src';
// tslint:disable-next-line: no-implicit-dependencies // tslint:disable-next-line: no-implicit-dependencies
import { Wallet } from '@harmony-js/account'; import { Wallet } from '@harmony-js/account';

@ -1,3 +1,9 @@
/**
* @packageDocumentation
* @module harmony-transaction
* @ignore
*/
import { Transaction } from '../src/transaction'; import { Transaction } from '../src/transaction';
import { RLPSign } from '../src/utils'; import { RLPSign } from '../src/utils';
import { TxStatus } from '../src/types'; import { TxStatus } from '../src/types';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-utils
*/
export const enum ChainType { export const enum ChainType {
Harmony = 'hmy', Harmony = 'hmy',
Ethereum = 'eth', Ethereum = 'eth',

@ -0,0 +1,4 @@
/**
* @packageDocumentation
* @ignore
*/

@ -1,3 +1,9 @@
/**
* @packageDocumentation
* @module harmony-utils
* @ignore
*/
export * from './validators'; export * from './validators';
export * from './transformers'; export * from './transformers';
export * from './utils'; export * from './utils';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-utils
*/
export function defineReadOnly(object: any, name: string, value: any): void { export function defineReadOnly(object: any, name: string, value: any): void {
Object.defineProperty(object, name, { Object.defineProperty(object, name, {
enumerable: true, enumerable: true,

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-utils
*/
import BN from 'bn.js'; import BN from 'bn.js';
import { isString, isNumber, isHex } from './validators'; import { isString, isNumber, isHex } from './validators';

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-utils
*/
import { import {
isNumber, isNumber,
isString, isString,
@ -41,11 +46,7 @@ export const validatorArray: any = {
isValidAddress: [isValidAddress], isValidAddress: [isValidAddress],
}; };
export function validateArgs( export function validateArgs(args: any, requiredArgs: any, optionalArgs: any): boolean {
args: any,
requiredArgs: any,
optionalArgs: any,
): boolean {
for (const key in requiredArgs) { for (const key in requiredArgs) {
if (args[key] !== undefined) { if (args[key] !== undefined) {
// tslint:disable-next-line: prefer-for-of // tslint:disable-next-line: prefer-for-of
@ -56,9 +57,7 @@ export function validateArgs(
if (!requiredArgs[key][i](args[key])) { if (!requiredArgs[key][i](args[key])) {
throw new Error( throw new Error(
`Validation failed for ${key},should be validated by ${ `Validation failed for ${key},should be validated by ${requiredArgs[key][i].validator}`,
requiredArgs[key][i].validator
}`,
); );
} }
} }
@ -77,9 +76,7 @@ export function validateArgs(
if (!optionalArgs[key][i](args[key])) { if (!optionalArgs[key][i](args[key])) {
throw new Error( throw new Error(
`Validation failed for ${key},should be validated by ${ `Validation failed for ${key},should be validated by ${optionalArgs[key][i].validator}`,
optionalArgs[key][i].validator
}`,
); );
} }
} }
@ -88,9 +85,7 @@ export function validateArgs(
return true; return true;
} }
export function generateValidateObjects(validatorObject: { export function generateValidateObjects(validatorObject: { [x: string]: any[] }) {
[x: string]: any[];
}) {
const requiredArgs: any = {}; const requiredArgs: any = {};
const optionalArgs: any = {}; const optionalArgs: any = {};
for (const index in validatorObject) { for (const index in validatorObject) {
@ -108,11 +103,7 @@ export function generateValidateObjects(validatorObject: {
return { requiredArgs, optionalArgs }; return { requiredArgs, optionalArgs };
} }
const assertObject = (input: any) => ( const assertObject = (input: any) => (target: any, key: any, descriptor: PropertyDescriptor) => {
target: any,
key: any,
descriptor: PropertyDescriptor,
) => {
const { requiredArgs, optionalArgs } = generateValidateObjects(input); const { requiredArgs, optionalArgs } = generateValidateObjects(input);
const original = descriptor.value; const original = descriptor.value;
function interceptor(this: any, ...args: any[]) { function interceptor(this: any, ...args: any[]) {

@ -1,3 +1,8 @@
/**
* @packageDocumentation
* @module harmony-utils
*/
export const isKeyString = (keyString: string, lengh: number): boolean => { export const isKeyString = (keyString: string, lengh: number): boolean => {
return !!keyString.replace('0x', '').match(`^[0-9a-fA-F]{${lengh}}$`); return !!keyString.replace('0x', '').match(`^[0-9a-fA-F]{${lengh}}$`);
}; };
@ -174,11 +179,7 @@ export const isValidAddress = (address: string): boolean => {
if (!isString(address)) { if (!isString(address)) {
throw new Error(`${address} is not string`); throw new Error(`${address} is not string`);
} }
if ( if (isAddress(address) || isBech32Address(address) || isBech32TestNetAddress(address)) {
isAddress(address) ||
isBech32Address(address) ||
isBech32TestNetAddress(address)
) {
return true; return true;
} else { } else {
return false; return false;

@ -1,11 +1,16 @@
/**
* @packageDocumentation
* @module harmony-utils
* @ignore
*/
// import BN from 'bn.js'; // import BN from 'bn.js';
export const basicType = { export const basicType = {
zero: 0, zero: 0,
float: 0.1, float: 0.1,
text: 'testString', text: 'testString',
jsonString: jsonString: '{"name":"@harmony-js/utils","version":"0.0.48","description":"utils for harmony"}',
'{"name":"@harmony-js/utils","version":"0.0.48","description":"utils for harmony"}',
hexNumber: 0x123, hexNumber: 0x123,
hexString: '0x123', hexString: '0x123',
bool: true, bool: true,
@ -18,10 +23,8 @@ export const basicType = {
}; };
export const advanceType = { export const advanceType = {
privateKey: privateKey: '0x97d2d3a21d829800eeb01aa7f244926f993a1427d9ba79d9dc3bf14fe04d9e37',
'0x97d2d3a21d829800eeb01aa7f244926f993a1427d9ba79d9dc3bf14fe04d9e37', publicKey: '0x028fe48b60c4511f31cf58906ddaa8422725d9313d4b994fab598d2cf220146228',
publicKey:
'0x028fe48b60c4511f31cf58906ddaa8422725d9313d4b994fab598d2cf220146228',
address: '0x84fece7d1f5629bc728c956ffd313dd0c3ac8f17', address: '0x84fece7d1f5629bc728c956ffd313dd0c3ac8f17',
hexAddress: '0x84fece7d1f5629bc728c956ffd313dd0c3ac8f17', hexAddress: '0x84fece7d1f5629bc728c956ffd313dd0c3ac8f17',
checkSumAddress: '0x84fece7d1f5629Bc728c956Ffd313dD0C3AC8f17', checkSumAddress: '0x84fece7d1f5629Bc728c956Ffd313dD0C3AC8f17',

@ -1,3 +1,9 @@
/**
* @packageDocumentation
* @module harmony-utils
* @ignore
*/
import { BN } from '@harmony-js/crypto'; import { BN } from '@harmony-js/crypto';
import * as transformers from '../src/transformers'; import * as transformers from '../src/transformers';

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save