finish package '@harmony-js/utils'

pull/21/head
Wen Zhang 5 years ago committed by Ganesha Upadhyaya
parent 61a8b8e7c0
commit 95474d74fe
  1. 73
      packages/harmony-account/guide.ts
  2. 7
      packages/harmony-contract/src/abi/abiCoder.ts
  3. 67
      packages/harmony-core/src/blockchain.ts
  4. 30
      packages/harmony-crypto/src/address.ts
  5. 1
      packages/harmony-transaction/src/shardingTransaction.ts
  6. 121
      packages/harmony-utils/src/chain.ts
  7. 21
      packages/harmony-utils/src/transformers.ts
  8. 1
      packages/harmony-utils/src/utils.ts

@ -1,48 +1,33 @@
/**
# Contents
1. [About This Package](#about-this-package)
2. [Usage of Account](#usage-of-account)
1. [Dependencies](#dependencies)
2. [Examples](#examples)
1. [Create a random account](#create-a-random-account)
2. [Import an existing privateKey to create Account](#import-an-existing-privatekey-to-create-account)
3. [Encrypt/Export keyStore file, Decrypt/Import keyStore file](#encryptexport-keystore-file-decryptimport-keystore-file)
4. [Address format getter](#address-format-getter)
5. [Sign a transaction](#sign-a-transaction)
3. [Usage of Wallet](#usage-of-wallet)
1. [Dependencies](#dependencies-1)
# About This Package
## About This Package
`@harmony-js/account` is dealing with account related features.
Developers can use this packages to:
* create `Account` instance
* create `Wallet` instance
* sign `Transaction`
* convert address format
* manage `privateKey` or `mnemonic phrases` and do the `encrypt` and `decrypt` job
Developers can use this package to:
- Create `Account` instance
- Create `Wallet` instance
- Sign `Transaction`
- Convert address format
- Manage `privateKey` or `mnemonic phrases` and do the `encrypt` and `decrypt` job
There are 2 main classes in this package, `Account` and `Wallet`.
The `Account` class is basic instance that contains most features mentioned above.
The `Wallet` class is class that stores all `Account` instance, you can do CRUD on it.
- The `Account` class is basic instance that contains most features mentioned above.
- The `Wallet` class is class that stores all `Account` instance, you can do CRUD on it.
# Usage of Account
## Usage of Account
## Dependencies
* "@harmony-js/network",
* "@harmony-js/staking",
* "@harmony-js/transaction",
* "@harmony-js/utils"
### Dependencies
- @harmony-js/network
- @harmony-js/staking
- @harmony-js/transaction
- @harmony-js/utils
### Examples
## Examples
### Create a random account
```typescript
Create a random account
```javascript
// import the Account class
import {Account} from '@harmony-js/account'
@ -75,7 +60,6 @@ The `Wallet` class is class that stores all `Account` instance, you can do CRUD
staticCreatedAccount.setMessenger(customMessenger)
console.log({staticCreatedAccount})
```
### Import an existing privateKey to create Account
@ -239,21 +223,18 @@ The `Wallet` class is class that stores all `Account` instance, you can do CRUD
```
# Usage of Wallet
## Usage of Wallet
## Dependencies
* "@harmony-js/crypto",
* "@harmony-js/network",
* "@harmony-js/staking",
* "@harmony-js/transaction",
* "@harmony-js/utils"
### Dependencies
- @harmony-js/crypto
- @harmony-js/network
- @harmony-js/staking
- @harmony-js/transaction
- @harmony-js/utils
```typescript
import {Wallet} from '@harmony-js/account'
const wallet=new Wallet()
import { Wallet } from '@harmony-js/account'
const wallet = new Wallet()
```
*
* @packageDocumentation

@ -1,4 +1,11 @@
/**
* ## Harmony Smart Contract
* Create an Contract instance
* ```javascript
* import { waitForInjected, getExtAccount } from '../util/hmy-util'
* import { Harmony, HarmonyExtension } from '@harmony-js/core'
* import { ChainID, ChainType } from '@harmony-js/utils'
* ```
* @packageDocumentation
* @module harmony-contract
*/

@ -1,7 +1,28 @@
/**
* ## Initialize the Harmony instance
* ## About this package
*
* `@harmony-js/core` is collection of modules to guide user to interacte with harmony blockchian.
*
* Develops can use this package to:
* - Create a `harmony` instance
* - Create a `harmonyExtension` instance, which support fo `MathWallet`
* - Get block and transaction by hash or blocknumber
* - Send transaction
* - Get balance of address
*
* ## How to use `@harmony-core`
* ### Dependencies
* - @harmony-js/core
* - @harmony-js/utils
*
* ### Step 1: Initialize the Harmony instance
* Before using harmony-core package, you should initialize the Harmony instance
* ```javascript
* // import or require Harmony class
* const { Harmony } = require('@harmony-js/core');
* // import or require settings
* const { ChainID, ChainType } = require('@harmony-js/utils');
*
* // initialize the Harmony instance
* const hmy = new Harmony(
* // rpc url
@ -14,6 +35,50 @@
* },
* );
* ```
*
* ### Step 2: Use the instance to call specific functions
* Example 1: get balance
* ```javascript
* // get balance
* hmy.blockchain.getBalance({
* address: 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7',
* blockNumber: 'latest'
* }).then((value) => {
* console.log(value.result);
* });
* ```
*
* Example 2: send transaction
* ```
* // add privateKey to wallet
* const privateKey = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e';
* hmy.wallet.addByPrivateKey(privateKey);
*
* async function transfer() {
* const txn = hmy.transactions.newTx({
* // token send to
* to: 'one166axnkjmghkf3df7xfvd0hn4dft8kemrza4cd2',
* // amount to send
* value: '10000',
* // gas limit, you can use string
* gasLimit: '210000',
* // send token from shardID
* shardID: 0,
* // send token to toShardID
* toShardID: 0,
* // gas Price, you can use Unit class, and use Gwei, then remember to use toWei(), which will be transformed to BN
* gasPrice: new hmy.utils.Unit('100').asGwei().toWei(),
* });
*
* // sign the transaction use wallet;
* const signedTxn = await hmy.wallet.signTransaction(txn);
* const txnHash = await hmy.blockchain.sendTransaction(signedTxn);
* console.log(txnHash.result);
* }
*
* transfer();
* ```
*
* @packageDocumentation
* @module harmony-core
*/

@ -53,6 +53,12 @@ export class HarmonyAddress {
this.basic = this.getBasic(this.raw);
}
/**
* Check whether the address has an valid address format
*
* @param addr string, the address
*
*/
private getBasic(addr: string) {
const basicBool = isAddress(addr);
const bech32Bool = isBech32Address(addr);
@ -76,6 +82,30 @@ export class HarmonyAddress {
}
}
/**
* Using this function to get Harmony format address
*
* @param address
*
* @example
* ```javascript
* const { Harmony } = require('@harmony-js/core');
* const { ChainID, ChainType } = require('@harmony-js/utils');
* const { randomBytes } = require('@harmony-js/crypto')
*
* const hmy = new Harmony(
* 'http://localhost:9500',
* {
* chainType: ChainType.Harmony,
* chainId: ChainID.HmyLocal,
* },
* );
*
* const bytes = randomBytes(20);
* const hAddress = hmy.crypto.getAddress(bytes);
* console.log(hAddress)
* ```
*/
export function getAddress(address: string) {
try {
return new HarmonyAddress(address);

@ -1,7 +1,6 @@
/**
* @packageDocumentation
* @module harmony-transaction
* @hidden
*/
import { Messenger } from '@harmony-js/network';

@ -1,4 +1,125 @@
/**
* ## About this package
*
* `@harmony-js/util` provides utility functions for Harmony dapps and other `harmony-js` packages
*
* Develop can use this package to:
* - Transform the unit of token (fromWei, toWei...)
* - Convert variable to different type (hexToBN, numberToHex...)
* - Check validators information (isAddress, isPublicKey, isBlockNumber...)
*
* ## How to use this package
*
* ### Step 1: create a Harmony Instance
* ```javascript
* const { Harmony } = require('@harmony-js/core');
* const { ChainID, ChainType } = require('@harmony-js/utils');
* const { BN } = require('@harmony-js/crypto');
*
* const hmy = new Harmony(
* 'http://localhost:9500',
* {
* chainType: ChainType.Harmony,
* chainId: ChainID.HmyLocal,
* },
* );
* ```
*
* ### Step 2: Select and call functions
* Here are some examples:
*
* ```javascript
* // numberToString
* const num = 123;
* const str = hmy.utils.numberToString(num)
* console.log(str);
*
* // add0xToString
* const str = '12345';
* const expected = hmy.utils.add0xToString(str)
* console.log(expected);
*
* // fromWei
* const Wei = new BN('1000000000000000000');
* const expected = hmy.utils.fromWei(Wei, hmy.utils.Units.one);
* console.log(expected);
*
* // toWei
* const one = new BN('1');
* const expected = hmy.utils.toWei(one, hmy.utils.Units.one);
* const num = hmy.utils.numToStr(expected);
* console.log(num);
* ```
*
* ### Step 3: Using unit class to convet the token unit
* ```javascript
* // convert one to Gwei
* const one = new hmy.utils.Unit('1').asOne();
* const oneToGwei = one.toGwei();
* console.log(oneToGwei);
* ```
*
* ## Some Important consts and Enums
* ### Chain Type
* ```javascript
* Harmony = 'hmy',
* Ethereum = 'eth',
* ```
*
* ### Chain ID
* ```javascript
* Default = 0,
EthMainnet = 1,
Morden = 2,
Ropsten = 3,
Rinkeby = 4,
RootstockMainnet = 30,
RootstockTestnet = 31,
Kovan = 42,
EtcMainnet = 61,
EtcTestnet = 62,
Geth = 1337,
Ganache = 0,
HmyMainnet = 1,
HmyTestnet = 2,
HmyLocal = 2,
HmyPangaea = 3,
* ```
*
* ### Default Config
* ```javascript
* export const defaultConfig = {
* Default: {
* Chain_ID: ChainID.HmyLocal,
* Chain_Type: ChainType.Harmony,
* Chain_URL: 'http://localhost:9500',
* Network_ID: 'Local',
* },
* DefaultWS: {
* Chain_ID: ChainID.HmyLocal,
* Chain_Type: ChainType.Harmony,
* Chain_URL: 'ws://localhost:9800',
* Network_ID: 'LocalWS',
* },
* };
* ```
*
* ### Unit Map
* ```
* [Units.wei, '1'], // 1 wei
* [Units.Kwei, '1000'], // 1e3 wei
* [Units.Mwei, '1000000'], // 1e6 wei
* [Units.Gwei, '1000000000'], // 1e9 wei
* [Units.szabo, '1000000000000'], // 1e12 wei
* [Units.finney, '1000000000000000'], // 1e15 wei
* [Units.ether, '1000000000000000000'], // 1e18 wei
* [Units.one, '1000000000000000000'], // 1e18 wei
* [Units.Kether, '1000000000000000000000'], // 1e21 wei
* [Units.Mether, '1000000000000000000000000'], // 1e24 wei
* [Units.Gether, '1000000000000000000000000000'], // 1e27 wei
* [Units.Tether, '1000000000000000000000000000000'], // 1e30 wei
* ```
*
* @packageDocumentation
* @module harmony-utils
*/

@ -42,6 +42,9 @@ const DEFAULT_OPTIONS = {
pad: false,
};
/**
* Convert Number to String
*/
export const numberToString = (obj: BN | number | string, radix: number = 10): string => {
if (BN.isBN(obj)) {
return obj.toString(radix);
@ -54,6 +57,9 @@ export const numberToString = (obj: BN | number | string, radix: number = 10): s
}
};
/**
* Convert Number to String
*/
export const numToStr = (input: any) => {
if (typeof input === 'string') {
if (!input.match(/^-?[0-9.]+$/)) {
@ -87,6 +93,9 @@ export const strip0x = (obj: string): string => {
return obj.toLowerCase().replace('0x', '');
};
/**
* Convert number to hex
*/
export const numberToHex = (obj: any): string => {
try {
return add0xToString(numberToString(obj, 16));
@ -95,6 +104,9 @@ export const numberToHex = (obj: any): string => {
}
};
/**
* Convert hex to Decimal number
*/
export const hexToNumber = (hex: string): string => {
if (isHex(hex) && hex[0] !== '-') {
return new BN(strip0x(hex), 'hex').toString();
@ -106,6 +118,9 @@ export const hexToNumber = (hex: string): string => {
}
};
/**
* Convert hex to Big Number
*/
export const hexToBN = (hex: string): BN => {
if (isHex(hex) && hex[0] !== '-') {
return new BN(strip0x(hex), 'hex');
@ -117,6 +132,9 @@ export const hexToBN = (hex: string): BN => {
}
};
/**
* Converts any ONE value into wei
*/
export const toWei = (input: BN | string, unit: Units): BN => {
try {
let inputStr = numToStr(input);
@ -175,6 +193,9 @@ export const toWei = (input: BN | string, unit: Units): BN => {
}
};
/**
* Converts any wei value into a ONE value.
*/
export const fromWei = (wei: BN | string, unit: Units, options: any = DEFAULT_OPTIONS): string => {
try {
const weiBN: BN = !BN.isBN(wei) ? new BN(wei) : wei;

@ -22,6 +22,7 @@ import {
isBlockNumber,
} from './validators';
/** @hidden */
export const enum AssertType {
required = 'required',
optional = 'optional',

Loading…
Cancel
Save