update sdk api reference

pull/67/head
Ganesha Upadhyaya 4 years ago
parent c6fbf597a5
commit cc4872a9f9
  1. 2
      README.md
  2. 0
      TYPEDOC.md
  3. 414
      packages/harmony-account/guide.ts
  4. 253
      packages/harmony-contract/src/abi/abiCoder.ts
  5. 243
      packages/harmony-core/src/blockchain.ts
  6. 136
      packages/harmony-crypto/src/errors.ts
  7. 42
      packages/harmony-network/src/rpcMethod/rpc.ts
  8. 89
      packages/harmony-staking/src/stakingTransaction.ts
  9. 228
      packages/harmony-transaction/src/types.ts
  10. 180
      packages/harmony-utils/src/chain.ts

@ -5,6 +5,8 @@
This is the Harmony javascript library which provides an easier way to interact with Harmony's blockchain. This is the Harmony javascript library which provides an easier way to interact with Harmony's blockchain.
Please read the [documentation](https://harmony-js-sdk-doc.s3-us-west-1.amazonaws.com/index.html) for more.
This libraries contains a few packages. This libraries contains a few packages.
1. [@harmony-js/core](https://github.com/harmony-one/sdk/tree/master/packages/harmony-core) 1. [@harmony-js/core](https://github.com/harmony-one/sdk/tree/master/packages/harmony-core)

@ -1,270 +1,214 @@
/** /**
## About This Package # @harmony-js/account
`@harmony-js/account` is dealing with account related features. This package provides a collection of apis to create accounts and wallets and sign using them. A wallet can hold multiple accounts and account is associated with a unique `one` address. This package also provides facilies to manage account keys.
Developers can use this package to: ## Installation
- 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`. ```
npm install @harmony-js/account
- 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
### Dependencies
- @harmony-js/network
- @harmony-js/staking
- @harmony-js/transaction
- @harmony-js/utils
### Examples ## Usage
Create a random account Creating new account and display hex and bech32 (one) addresses
```javascript ```javascript
// import the Account class const account = new Account(); // or const account = Account.new()
import {Account} from '@harmony-js/account' console.log(account.checksumAddress);
console.log(account.bech32Address);
// Messenger is optional, by default, we have a defaultMessenger
// If you like to change, you will import related package here.
import { HttpProvider, Messenger } from '@harmony-js/network';
import { ChainType, ChainID } from '@harmony-js/utils';
// create a custom messenger
const customMessenger = new Messenger(
new HttpProvider('http://localhost:9500'),
ChainType.Harmony, // if you are connected to Harmony's blockchain
ChainID.HmyLocal, // check if the chainId is correct
)
// to create an Account with random privateKey
// and you can setMessenger later
const randomAccount = new Account()
randomAccount.setMessenger(customMessenger)
// or you can set messenger on `new`
const randomAccountWithCustomMessenger = new Account(undefined, customMessenger)
// you can display the account
console.log({randomAccount,randomAccountWithCustomMessenger})
// or you can use static method to create an Account
const staticCreatedAccount = Account.new()
// but you have to set messenger manually after
staticCreatedAccount.setMessenger(customMessenger)
console.log({staticCreatedAccount})
``` ```
### Import an existing privateKey to create Account Creating new account using private key
```javascript
```typescript const account = Account.add('45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e');
// import the Account class
import {Account} from '@harmony-js/account'
// NOTED: Key with or without `0x` are accepted, makes no different
// NOTED: DO NOT import `mnemonic phrase` using `Account` class, use `Wallet` instead
const myPrivateKey = '0xe19d05c5452598e24caad4a0d85a49146f7be089515c905ae6a19e8a578a6930'
const myAccountWithMyPrivateKey = new Account(myPrivateKey)
// you can also import privateKey use static method
const myAccountWithMyPrivateKeyUsingStatic = Account.add(myPrivateKey)
console.log({ myAccountWithMyPrivateKey, myAccountWithMyPrivateKeyUsingStatic })
``` ```
### Encrypt/Export keyStore file, Decrypt/Import keyStore file Creating account using private key and custom messenger
```javascript
```typescript * const account = new Account(
* '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e',
// import the Account class * new Messenger(
import {Account} from '@harmony-js/account' * new HttpProvider('https://api.s0.b.hmny.io'),
* ChainType.Harmony,
// suppose we have an account * ChainID.HmyTestnet,
const myPrivateKey = '0xe19d05c5452598e24caad4a0d85a49146f7be089515c905ae6a19e8a578a6930' * ),
const myAccountWithMyPrivateKey = new Account(myPrivateKey) * );
// suppose we have a password, and we want to encrypt the account above
const myStrongPassword = '123'
async function encryptAndDecrypt(password) {
// we get the privateKey before encrypted as comparison
const unencryptedPrivateKey = myAccountWithMyPrivateKey.privateKey
// export the account to keyStore string, which will make the privateKey encrpyted
const keyStoreFile = await myAccountWithMyPrivateKey.toFile(password)
// exported keyStoreFile
console.log({ keyStoreFile })
// see if the account is encrypted
console.log(`Is this account encrypted? \n ${myAccountWithMyPrivateKey.encrypted}`)
// keystore file should be equal to encrypted privateKey
console.log(
`Is privateKey equal to keyStore string? \n ${keyStoreFile ===
myAccountWithMyPrivateKey.privateKey}`,
)
}
encryptAndDecrypt(myStrongPassword)
// suppose we have keyStorefile, in this example, we just use same password and keystore string encrypted above
const someKeyStoreFile =
'{"version":3,"id":"62326332-3139-4839-b534-656134623066","address":"1fe3da351d9fc0c4f02de5412ad7def8aee956c5","Crypto":{"ciphertext":"b86ab81682c9f5a35738ad9bd38cd9b46c1b852ef33f16dd83068f79e20d5531","cipherparams":{"iv":"44efb5a514f34968e92cafad80566487"},"cipher":"aes-128-ctr","kdf":"scrypt","kdfparams":{"salt":"d70ae1f311601562113f98c8ebe382f52a332dca1588886e5ea91e2f8a647134","n":8192,"r":8,"p":1,"dklen":32},"mac":"7b63e4e31a75a22b7091291bb58302655b738539ef3e30b30a7a7f170f6163ef"}}'
async function importKeyStoreFileAndDecrypt(keyStoreFile, password) {
// import keyStore string and provide the password, remember to make a new Account first
const importedAccount = await Account.new().fromFile(keyStoreFile, password)
// the account should decypted which `Account.encrypted` is false
console.log(`Is this account encrypted? \n ${importedAccount.encrypted}`)
// see if the privatekey is equal to unencrypted one?
console.log(
`Is the account recovered from keystore? \n ${importedAccount.privateKey === myPrivateKey}`,
)
}
importKeyStoreFileAndDecrypt(someKeyStoreFile, myStrongPassword)
``` ```
Creating account and setting custom messenger
### Address format getter ```javascript
// uses by default http://localhost:9500 as messenger
```typescript * const account = new Account();
* const customMessenger = new Messenger(
// import the Account class * new HttpProvider('https://api.s0.b.hmny.io'),
import {Account} from '@harmony-js/account' * ChainType.Harmony,
* ChainID.HmyTestnet,
// suppose we have an account * );
const myPrivateKey = '0xe19d05c5452598e24caad4a0d85a49146f7be089515c905ae6a19e8a578a6930'
const myAccountWithMyPrivateKey = new Account(myPrivateKey) account.setMessenger(customMessenger);
// Account.address is bytes20/base16 address
console.log(myAccountWithMyPrivateKey.address)
// Account.bech32Address is bech32 format address, in Harmony, it's `one1` prefixed
console.log(myAccountWithMyPrivateKey.bech32Address)
// Account.bech32TestNetAddress is bech32 format address, in Harmony, it's `tone1` prefixed, used in testnet
console.log(myAccountWithMyPrivateKey.bech32TestNetAddress)
// Account.checksumAddress is checksumed address from base16
console.log(myAccountWithMyPrivateKey.checksumAddress)
``` ```
Storing the account data to keystore file
```javascript
* const passphrase = '';
* const account = new Account('45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e');
* account.toFile(passphrase).then(keystore => {
* console.log(keystore);
* });
```
### Sign a transaction Fetching account from keystore file
```javascript
```typescript * const passphrase = '';
* const keystore = '{"version":3,"id":"33363566-3564-4264-a638-363531666335","address":"7c41e0668b551f4f902cfaec05b5bdca68b124ce","crypto":{"ciphertext":"9b09380afb742838b32d9afc0ec1a3df35dbd7a41e3a160d08c07a4d0e79b855","cipherparams":{"iv":"1cd0e0522260eef055b9170f4825f4a0"},"cipher":"aes-128-ctr","kdf":"scrypt","kdfparams":{"salt":"bf35e36c45cccefcef73a4c900f41c682c94c28630d94d2d1f764760d245f30b","n":8192,"r":8,"p":1,"dklen":32},"mac":"25b4442972356bea02af57eba3b87803086d90b5e7657a57b528b89b1aa25f2f"}}';
// import the Account class * const account = new Account();
import {Account} from '@harmony-js/account' * account.fromFile(keystore, passphrase).then(account => {
* console.log(account.bech32Address);
// import Transaction class from '@harmony-js/transaction' * });
import {Transaction} from '@harmony-js/transaction' ```
// Messenger is optional, by default, we have a defaultMessenger
// If you like to change, you will import related package here.
import { HttpProvider, Messenger } from '@harmony-js/network';
import { ChainType, ChainID, Unit } from '@harmony-js/utils';
// create a custom messenger
const customMessenger = new Messenger(
new HttpProvider('http://localhost:9500'),
ChainType.Harmony, // if you are connected to Harmony's blockchain
ChainID.HmyLocal, // check if the chainId is correct
)
// suppose we have an account
const myPrivateKey = '0xe19d05c5452598e24caad4a0d85a49146f7be089515c905ae6a19e8a578a6930'
const myAccountWithMyPrivateKey = new Account(myPrivateKey)
const txnObject = {
// token send to
to: 'one166axnkjmghkf3df7xfvd0hn4dft8kemrza4cd2',
// amount to send
value: '1000000000000000000000',
// gas limit, you can use string or use BN value
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 Unit('100').asGwei().toWei(),
// if you set nonce manually here, and remember, the `updateNonce` of `Account.signTransaction` should be set to false
nonce: 0,
};
const txn = new Transaction(txnObject, customMessenger); Get the account balance
```javascript
* const account = new Account(
* '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e',
* new Messenger(
* new HttpProvider('https://api.s0.b.hmny.io'),
* ChainType.Harmony,
* ChainID.HmyTestnet,
* ),
* );
* account.getBalance().then(response => {
* console.log(response);
* });
```
outputs `{ balance: '9126943763247054940484', nonce: 45, shardID: 0 }`
async function signTheTxn() { Create a transaction and account, and sign it
// Account.signTransaction(transaction: Transaction, updateNonce?: boolean, encodeMode?: string, blockNumber?: string): Promise<Transaction> ```javascript
// If the 2nd parameter `updateNonce` is set to true, it will query and update account's nonce before it signs * const account = new Account(
const signedTxn = await myAccountWithMyPrivateKey.signTransaction(txn, false, 'rlp', 'latest'); * '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e',
* new Messenger(
* new HttpProvider('https://api.s0.b.hmny.io'),
* ChainType.Harmony,
* ChainID.HmyTestnet,
* ),
* );
* const { TransactionFactory } = require('@harmony-js/transaction');
* const { Unit } = require('@harmony-js/utils');
* const factory = new TransactionFactory();
* const txn = factory.newTx({
* to: 'one166axnkjmghkf3df7xfvd0hn4dft8kemrza4cd2',
* value: new Unit(1).asOne().toWei(),
* // gas limit, you can use string
* gasLimit: '21000',
* // 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 Unit('1').asGwei().toWei(),
* });
* account.signTransaction(txn).then((signedTxn) => {
* console.log(signedTxn);
* });
```
// see if the transaction is signed Similarily staking transactions can be created and signed using account.
console.log(`\n see if transaction is signed: \n ${signedTxn.isSigned()} \n`);
// get the tranaction bytes A wallet represents user wallet that can hold one or more user accounts.
console.log(`\n the signed bytes is: \n ${signedTxn.getRawTransaction()} \n`);
return signTheTxn; Creating an empty wallet
} ```javascript
* const { Wallet } = require('@harmony-js/account')
* const wallet = new Wallet();
```
signTheTxn(); Setting a messenger to be used to send wallet transactions
```javascript
* wallet.setMessenger(
* new Messenger(
* new HttpProvider('https://api.s0.b.hmny.io'),
* ChainType.Harmony,
* ChainID.HmyTestnet,
* ),
* );
``` ```
Create an empty wallet with messenger
```javascript
* const wallet = new Wallet(
* new Messenger(
* new HttpProvider('https://api.s0.b.hmny.io'),
* ChainType.Harmony,
* ChainID.HmyTestnet,
* ),
* );
```
## Usage of Wallet An account could be added to a wallet using different ways. Adding account using mnemonics
```javascript
const mnemonics = 'horse distance dry brother pretty manual chicken mushroom town swim prize clutch';
const account = wallet.addByMnemonic(mnemonics);
```
### Dependencies Adding account using private key
- @harmony-js/crypto ```javascript
- @harmony-js/network const account = wallet.addByPrivateKey('0x676cd9773dd23a4c1d7f22767c61c7b6723cc6be37b078545f6e0e91433a23dd')
- @harmony-js/staking ```
- @harmony-js/transaction
- @harmony-js/utils
```typescript Adding account using keystore file
// constructor ```javascript
const { Wallet } = require('@harmony-js/account'); * const keystore = '{"version":3,"id":"33363566-3564-4264-a638-363531666335","address":"7c41e0668b551f4f902cfaec05b5bdca68b124ce","crypto":{"ciphertext":"9b09380afb742838b32d9afc0ec1a3df35dbd7a41e3a160d08c07a4d0e79b855","cipherparams":{"iv":"1cd0e0522260eef055b9170f4825f4a0"},"cipher":"aes-128-ctr","kdf":"scrypt","kdfparams":{"salt":"bf35e36c45cccefcef73a4c900f41c682c94c28630d94d2d1f764760d245f30b","n":8192,"r":8,"p":1,"dklen":32},"mac":"25b4442972356bea02af57eba3b87803086d90b5e7657a57b528b89b1aa25f2f"}}';
const wallet = new Wallet(customMessenger); * const passphrase = '';
* wallet.addByKeyStore(keystore, passphrase).then(account => {
* console.log(account.bech32Address);
* });
```
// get signer Creating a new account using passphrase
const wallet = new Wallet(customMessenger); ```javascript
const key_1 = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e'; * const passphrase = 'harmony-one';
console.log(wallet.addByPrivateKey(key_1)); * wallet.createAccount(passphrase).then(account => {
console.log(wallet.signer) * console.log(account.bech32Address);
* });
```
// createAccount Get all accounts in the wallet
console.log(wallet.accounts); ```javascript
wallet.createAccount(); * wallet.accounts.forEach(addr => {
wallet.createAccount(); * const account = wallet.getAccount(addr);
console.log(wallet.accounts); * console.log(account.bech32Address);
* });
```
// encryptAccount Set wallet signer when multiple accounts exists in the wallet
const key_1 = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e'; ```javascript
wallet.addByPrivateKey(key_1); wallet.setSigner(signerAddr);
wallet.encryptAccount('one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7', '12345').then((value) => { ```
console.log(value);
})
// decrptAccount Sign transaction using wallet, will sign the transaction using the wallet signer
const key_1 = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e'; ```javascript
wallet.addByPrivateKey(key_1); * const txn = factory.newTx({
wallet.encryptAccount('one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7', '12345').then(() => { * to: 'one166axnkjmghkf3df7xfvd0hn4dft8kemrza4cd2',
wallet.decryptAccount('one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7', '12345').then((value) => { * value: new Unit(1).asOne().toWei(),
console.log(value); * // gas limit, you can use string
}) * gasLimit: '21000',
}); * // 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 Unit('1').asGwei().toWei(),
* });
* wallet.signTransaction(txn).then((signedTxn) => {
* console.log(signedTxn);
* });
``` ```
Similarily staking transactions can be signed using `signStaking` api.
* *
* @packageDocumentation * @packageDocumentation
* @module harmony-account * @module harmony-account

@ -1,110 +1,151 @@
/** /**
* ## About this package # @harmony-js/contract
*
* `@harmony-js/contract` makes it easy to interact with smart contract on the Harmony Blockchain. This allows you to interact with smart contracts as if they were JavaScript objects. This package provides a collection of apis to create, deploy, and interact with smart contracts. In Harmony, smart contracts all fully EVM compatible and the formats and terminologies match 1-to-1 with EVM smart contracts.
*
* ## How to use this package ## Installation
*
* ### Deploy a contract to blockchain ```
* ```javascript npm install @harmony-js/contract
* // Step 1: Use Solidity to build a sample contract instance ```
* contract Inbox {
* string public message; ## Usage
* constructor() public {
* message = "hello"; Deploying a contract using `contractConstructor`
* } ```javascript
* function setMessage(string memory newMessage) public { const { ContractFactory } = require('@harmony-js/contract');
* message = newMessage; const { Wallet } = require('@harmony-js/account');
* } const { Messenger, HttpProvider } = require('@harmony-js/network');
* } const { ChainID, ChainType, hexToNumber } = require('@harmony-js/utils');
*
* // Step 2: Use truffle to compile the contract * const wallet = new Wallet(
* $ truffle compile * new Messenger(
* * new HttpProvider('https://api.s0.b.hmny.io'),
* // Step 3: Use truffle to deploy the contract (by truffle) * ChainType.Harmony,
* $ truffle migrate --network local --reset * ChainID.HmyTestnet,
* $ truffle migrate --network testnet --reset * ),
* ``` * );
* [Tutorial: using truffle to compile and deploy smart-contract](https://github.com/harmony-one/HRC/tree/master/examples/dapp_Lottery) * const factory = new ContractFactory(wallet);
*
* ### Interact with the contract * const contractJson = require("./Counter.json");
* ```javascript * const contract = factory.createContract(contractJson.abi);
* // Step 1: create a harmony instance
* const { Harmony } = require('@harmony-js/core'); * const options1 = { gasPrice: '0x3B9ACA00' }; // gas price in hex corresponds to 1 Gwei or 1000000000
* const { ChainID, ChainType } = require('@harmony-js/utils'); * let options2 = { gasPrice: 1000000000, gasLimit: 21000 }; // setting the default gas limit, but changing later based on estimate gas
* const hmy = new Harmony(
* // let's assume we deploy smart contract to this end-point URL * const options3 = { data: contractJson.bytecode }; // contractConstructor needs contract bytecode to deploy
* 'https://api.s0.b.hmny.io'
* { * contract.wallet.addByPrivateKey('1f054c21a0f57ebc402c00e14bd1707ddf45542d4ed9989933dbefc4ea96ca68');
* chainType: ChainType.Harmony,
* chainId: ChainID.HmyLocal, * contract.methods.contractConstructor(options3).estimateGas(options1).then(gas => {
* } * options2 = {...options2, gasLimit: hexToNumber(gas)};
* ) * contract.methods.contractConstructor(options3).send(options2).then(response => {
* * console.log('contract deployed at ' + response.transaction.receipt.contractAddress);
* // Step 2: get a contract instance * });
* const getContractInstance = (hmy, artifact) => { * });
* return hmy.contracts.createContract(artifact.abi, address); ```
* } Instead of `contract.methods.contractConstructor`, `contract.deploy` could be used and it will work.
* const inbox = getContractInstance(hmy, inboxJson)
* Loading a contract object using the contract json and contract address for interacting with it
* // Step 3: interact with the instance ```javascript
* // Example 1: methods.myMethod.call() * const { Harmony } = require("@harmony-js/core");
* const message = await inbox.methods.message().call(); * const { ChainID, ChainType } = require("@harmony-js/utils");
* console.log(message); * const hmy = new Harmony("https://api.s0.b.hmny.io", {
* * chainType: ChainType.Harmony,
* // Example 2: methods.myMethod.send() * chainId: ChainID.HmyTestnet,
* inbox.methods.setMessage('666').send({ * });
* gasLimit: '1000001',
* gasPrice: new hmy.utils.Unit('10').asGwei().toWei(), const contractJson = require("./Counter.json");
* }); const contractAddr = "0x19f64050e6b2d376e52AC426E366c49EEb0724B1";
* ```
* const contract = hmy.contracts.createContract(contractJson.abi, contractAddr);
* ### Integrate MathWallet console.log(contract.methods);
* Using MathWallet to sign Transaction ```
* ```javascript
* // Step 0: set up MathWallet extension on Chrome Directly loading contract using `ContractFactory`
* ```javascript
* // Step 1: Create a harmonyExtension instance const { ContractFactory } = require('@harmony-js/contract');
* const { Harmony, HarmonyExtension } = require('@harmony-js/core'); const { Wallet } = require('@harmony-js/account');
* let hmyEx, ExContract; const { Messenger, HttpProvider } = require('@harmony-js/network');
* export const initExtension = async() => { const { ChainID, ChainType, hexToNumber } = require('@harmony-js/utils');
* hmyEx = await new HarmonyExtension(window.harmony);
* * const wallet = new Wallet(new Messenger(
* exContract = hmyEx.contracts.createContract(abi, address); * new HttpProvider('https://api.s0.b.hmny.io'),
* return exContract; * ChainType.Harmony,
* }; * ChainID.HmyTestnet,
* * ));
* // Step 2: interact with hmyEx instance const factory = new ContractFactory(wallet);
* // wait for hmy inject into window const contract = factory.createContract(contractJson.abi, contractAddr);
* async componentDidMount() { ```
* ...
* await waitForInjected() Estimate gas for contract methods
* ... ```javascript
* } * const options1 = { gasPrice: '0x3B9ACA00' }; // gas price in hex corresponds to 1 Gwei or 1000000000
* // Example: methods.myMethod.send()
* onSubmit = async event => { * contract.methods.getCount().estimateGas(options1).then(gas => {
* const exContract = await initExtension() * console.log('gas required for getCount is ' + hexToNumber(gas));
* await exContract.methods.Mymethod().send({ * });
* value: new hmy.utils.Unit('1').asOne().toWei(), ```
* })
* } Call contract read-only methods. Harmony uses 1 Gwei gas price and gas limit of 21000 by default. Use the estimate gas api to correctly set the gas limit.
* ```javascript
* // wait for injected * const options1 = { gasPrice: '0x3B9ACA00' }; // gas price in hex corresponds to 1 Gwei or 1000000000
* export const waitForInjected = () => new Promise((resolve) => { * let options2 = { gasPrice: 1000000000, gasLimit: 21000 }; // setting the default gas limit, but changing later based on estimate gas
* const check = () => {
* if (!window.harmony) setTimeout(check, 250); * contract.methods.getCount().estimateGas(options1).then(gas => {
* else resolve(window.harmony); * options2 = {...options2, gasLimit: hexToNumber(gas)};
* } * contract.methods.getCount().call(options2).then(count => {
* check(); * console.log('counter value: ' + count);
* }); * });
* ``` * });
* ```
* ## [More Examples: HRC repo](https://github.com/harmony-one/HRC/tree/master/examples)
* - Lottery Invoking contract modification methods using `send` api. Need to add a signing account to the contract wallet, otherwise `send` api will not work.
* - HRC 20 ```javascript
* - HRC 721 * const options1 = { gasPrice: '0x3B9ACA00' }; // gas price in hex corresponds to 1 Gwei or 1000000000
* - Node-dao * let options2 = { gasPrice: 1000000000, gasLimit: 21000 }; // setting the default gas limit, but changing later based on estimate gas
* - Node-faucet
* contract.wallet.addByPrivateKey('1f054c21a0f57ebc402c00e14bd1707ddf45542d4ed9989933dbefc4ea96ca68');
* contract.methods.incrementCounter().estimateGas(options1).then(gas => {
* options2 = {...options2, gasLimit: hexToNumber(gas)};
* contract.methods.incrementCounter().send(options2).then(response => {
* console.log(response.transaction.receipt);
* });
* });
```
All the above apis can also be asynchronously executed using `async` and `await`.
Subscribing to the contract events requires web socket based messenger.
```javascript
* const { ContractFactory } = require('@harmony-js/contract');
* const { Wallet } = require('@harmony-js/account');
* const { Messenger, WSProvider } = require('@harmony-js/network');
* const { ChainID, ChainType, hexToNumber } = require('@harmony-js/utils');
* const ws = new WSProvider('wss://ws.s0.b.hmny.io');
* const wallet = new Wallet(
* new Messenger(
* ws,
* ChainType.Harmony,
* ChainID.HmyTestnet,
* ),
* );
* const factory = new ContractFactory(wallet);
* const contractJson = require("./Counter.json");
* const contractAddr = '0x8ada52172abda19b9838eb00498a40952be6a019';
* const contract = factory.createContract(contractJson.abi, contractAddr);
* contract.events
* .IncrementedBy()
* .on('data', (event) => {
* console.log(event);
* })
* .on('error', console.error);
```
* *
* @packageDocumentation * @packageDocumentation
* @module harmony-contract * @module harmony-contract

@ -1,83 +1,168 @@
/** /**
* ## About this package # @harmony-js/core
*
* `@harmony-js/core` is collection of modules to guide user to interacte with harmony blockchian. This package provides a collection of apis to interact with Harmony blockchain.
*
* Develops can use this package to: ## Installation
* - Create a `harmony` instance
* - Create a `harmonyExtension` instance, which support fo `MathWallet` ```
* - Get block and transaction by hash or blocknumber npm install @harmony-js/core
* - Send transaction ```
* - Get balance of address
* ## Usage
* ## How to use `@harmony-core`
* ### Dependencies Create a Harmony instance connecting to testnet
* - @harmony-js/core
* - @harmony-js/utils ```javascript
* * const { Harmony } = require('@harmony-js/core');
* ### Step 1: Initialize the Harmony instance * const {
* Before using harmony-core package, you should initialize the Harmony instance * ChainID,
* ```javascript * ChainType,
* // import or require Harmony class * hexToNumber,
* const { Harmony } = require('@harmony-js/core'); * numberToHex,
* // import or require settings * fromWei,
* const { ChainID, ChainType } = require('@harmony-js/utils'); * Units,
* * Unit,
* // initialize the Harmony instance * } = require('@harmony-js/utils');
* const hmy = new Harmony(
* // rpc url * const hmy = new Harmony(
* 'https://api.s0.b.hmny.io/', * 'https://api.s0.b.hmny.io/',
* { * {
* // chainType set to Harmony * chainType: ChainType.Harmony,
* chainType: ChainType.Harmony, * chainId: ChainID.HmyTestnet,
* // chainType set to HmyLocal * },
* chainId: ChainID.HmyLocal, * );
* }, ```
* );
* ``` Getting balance of account `one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7`
* ```javascript
* ### Step 2: Use the instance to call specific functions * hmy.blockchain
* Example 1: get balance * .getBalance({ address: 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7' })
* ```javascript * .then((response) => {
* // get balance * console.log('balance in ONEs: ' + fromWei(hexToNumber(response.result), Units.one));
* hmy.blockchain.getBalance({ * });
* address: 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7', ```
* blockNumber: 'latest'
* }).then((value) => { Getting the latest block number
* console.log(value.result); ```javascript
* }); * hmy.blockchain.getBlockNumber().then((response) => {
* ``` * console.log('current block number: ' + hexToNumber(response.result));
* * });
* Example 2: send transaction ```
* ```
* // add privateKey to wallet Getting the block using block hash
* const privateKey = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e'; ```javascript
* hmy.wallet.addByPrivateKey(privateKey); * hmy.blockchain
* * .getBlockByHash({
* async function transfer() { * blockHash: '0x08c46ae7249362a7d1f602d44c5a81f33ebdab6a7dcb6068f99610b57911aafd',
* const txn = hmy.transactions.newTx({ * })
* // token send to * .then((response) => {
* to: 'one166axnkjmghkf3df7xfvd0hn4dft8kemrza4cd2', * console.log(response.result);
* // amount to send * });
* value: '10000', ```
* // gas limit, you can use string
* gasLimit: '210000', Getting the block using block number
* // send token from shardID ```javascript
* shardID: 0, * hmy.blockchain
* // send token to toShardID * .getBlockByNumber({
* toShardID: 0, * blockNumber: numberToHex(422635),
* // 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(), * .then((response) => {
* }); * console.log(response.result);
* * });
* // sign the transaction use wallet; ```
* const signedTxn = await hmy.wallet.signTransaction(txn);
* const txnHash = await hmy.blockchain.sendTransaction(signedTxn); Getting the transaction using hash
* console.log(txnHash.result); ```javascript
* } * hmy.blockchain
* * .getTransactionByHash({
* transfer(); * txnHash: '0x56c73eb993b18dc04baacec5c2e9d1292a090f6a978a4a1c461db5255fcbc831',
* ``` * })
* .then((response) => {
* console.log(response.result);
* });
```
Getting the transaction receipt
```javascript
* hmy.blockchain
* .getTransactionReceipt({
* txnHash: '0x56c73eb993b18dc04baacec5c2e9d1292a090f6a978a4a1c461db5255fcbc831',
* })
* .then((response) => {
* console.log(response.result);
* });
```
Getting the cross-shard transaction receipt
```javascript
* hmy.blockchain
* .getCxReceiptByHash({
* txnHash: '0xcd36a90ff5d5373285c2896ba7bbcd3f5324263c0cb8ecfb7cad2f5fc2fbdbda',
* shardID: 1,
* })
* .then((value) => {
* console.log(value.result);
* });
```
Getting the deployed smart contract code
```javascript
* hmy.blockchain
* .getCode({
* address: '0x08AE1abFE01aEA60a47663bCe0794eCCD5763c19',
* blockNumber: 'latest',
* })
* .then((response) => {
* console.log(response.result);
* });
```
Getting the transaction count of an account
```javascript
* hmy.blockchain
* .getTransactionCount({
* address: 'one1pdv9lrdwl0rg5vglh4xtyrv3wjk3wsqket7zxy',
* })
* .then((response) => {
* console.log(hexToNumber(response.result));
* });
```
Getting the shard structure and details
```javascript
* hmy.blockchain.getShardingStructure().then((response) => {
* console.log(response.result);
* });
```
Transferring funds using `sendTransaction`
```javascript
// key corresponds to one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7, only has testnet balance
* hmy.wallet.addByPrivateKey('45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e');
* async function transfer() {
* const txn = hmy.transactions.newTx({
* to: 'one166axnkjmghkf3df7xfvd0hn4dft8kemrza4cd2',
* value: new Unit(1).asOne().toWei(),
* // gas limit, you can use string
* gasLimit: '21000',
* // 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('1').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 * @packageDocumentation
* @module harmony-core * @module harmony-core

@ -1,65 +1,79 @@
/** /**
* ## About this package # @harmony-js/crypto
*
* `@harmony-js/crypot` provides a series of functions to deal with keys This package provides a collection of apis related to address management, kestore, encoding, and encrypt/decrypt.
*
* ## How to use this package ## Installation
*
* ### Create a Harmony Instance ```
* ```javascript npm install @harmony-js/crypto
* const { Harmony } = require('@harmony-js/core'); ```
* const { ChainID, ChainType } = require('@harmony-js/utils');
* ## Usage
* const hmy = new Harmony(
* 'http://localhost:9500', ```javascript
* { * const {
* chainType: ChainType.Harmony, * encode,
* chainId: ChainID.HmyLocal, * decode,
* }, * randomBytes,
* ); * toBech32,
* ``` * fromBech32,
* * HarmonyAddress,
* ### Some examples * generatePrivateKey,
* * getPubkeyFromPrivateKey,
* ```javascript * getAddressFromPublicKey,
* // randomBytes * getAddressFromPrivateKey,
* const bytes = hmy.crypto.randomBytes(20); * encryptPhrase,
* console.log(bytes) * decryptPhrase
* * } = require('@harmony-js/crypto');
* // encryptPhrase * const { isPrivateKey, isAddress, isPublicKey } = require('@harmony-js/utils');
* const myPhrase = hmy.wallet.newMnemonic(); ```
* const pwd = '1234';
* hmy.crypto.encryptPhrase(myPhrase, pwd).then((value) => { Address apis
* console.log(value); ```javascript
* }) const bytes = randomBytes(20);
* const addr = new HarmonyAddress(bytes);
* // decryptThePhrase
* hmy.crypto.encryptPhrase(myPhrase, pwd).then((keystore) => { console.log(addr.checksum);
* hmy.crypto.decryptPhrase(JSON.parse(keystore), pwd).then((value) => { console.log(addr.bech32);
* console.log(value);
* }) console.log(HarmonyAddress.isValidBech32(addr.bech32));
* }) ```
*
* // generatePrivateKey RLP apis
* const privateKey = hmy.crypto.generatePrivateKey(); ```javascript
* console.log(privateKey) const encoded = '0x89010101010101010101';
* const decoded = '0x010101010101010101';
* // getPubkeyFromPrivateKey console.log(encode(decoded));
* const publicKey = hmy.crypto.getPubkeyFromPrivateKey(privateKey); console.log(decode(encoded));
* console.log(publicKey); ```
*
* // getAddressFromPrivateKey Keystore apis
* const address = hmy.crypto.getAddressFromPrivateKey(privateKey); ```javascript
* console.log(address); const prv = generatePrivateKey();
* const pub = getPubkeyFromPrivateKey(prv);
* // getAddressFromPublicKey const addr = getAddressFromPublicKey(pub);
* const address = hmy.crypto.getAddressFromPublicKey(publicKey); const addrPrv = getAddressFromPrivateKey(prv);
* console.log(address); console.log(isPrivateKey(prv));
* console.log(isPublicKey(pub));
* // toChecksumAddress console.log(isAddress(addr));
* const checksumAddr = hmy.crypto.toChecksumAddress(address); console.log(isAddress(addrPrv));
* console.log(checksumAddr); ```
* ```
Encrypt/decrypt apis
```javascript
* const { Wallet } = require('@harmony-js/account');
* const myPhrase = new Wallet().newMnemonic();
* console.log(myPhrase);
* const pwd = '1234';
* encryptPhrase(myPhrase, pwd).then((value) => {
* console.log(value);
* decryptPhrase(JSON.parse(value), pwd).then(value => {
* console.log(value);
* });
* });
```
* *
* @packageDocumentation * @packageDocumentation
* @module harmony-crypto * @module harmony-crypto

@ -1,22 +1,28 @@
/** /**
* ## About this package # @harmony-js/network
*
* `@harmony-js/network` provides functions to handle messenger, providers and subscriptions... This package provides a collection of apis to create messengers (HTTP, WebSocket) to connect to blockchain networks.
*
* ## How to use this package ## Installation
*
* ### 1. Create a Message ```
* ```javascript npm install @harmony-js/network
* const { HttpProvider, Messenger } = require('@harmony-js/network'); ```
* const { ChainType, ChainID } = require('@harmony-js/utils');
* ## Usage
* // create a custom messenger
* const customMessenger = new Messenger( ```javascript
* new HttpProvider('http://localhost:9500'), const { Messenger, HttpProvider, WSProvider } = require('@harmony-js/network');
* ChainType.Harmony, // if you are connected to Harmony's blockchain const { ChainID, ChainType } = require('@harmony-js/utils');
* ChainID.HmyLocal, // check if the chainId is correct const testnetHTTP = 'https://api.s0.b.hmny.io';
* ) const testnetWS = 'wss://ws.s0.b.hmny.io';
* ``` const localHTTP = 'http://localhost:9500/';
const localWS = 'http://localhost:9800/';
const http = new HttpProvider(testnetHTTP); // for local use localHTTP
const ws = new WSProvider(testnetWS); // for local use testnetWS
const customHTTPMessenger = new Messenger(http, ChainType.Harmony, ChainID.HmyTestnet); // for local ChainID.HmyLocal
const customWSMessenger = new Messenger(ws, ChainType.Harmony, ChainID.HmyTestnet); // for local ChainID.HmyLocal
```
* *
* @packageDocumentation * @packageDocumentation
* @module harmony-network * @module harmony-network

@ -1,4 +1,93 @@
/** /**
* # @harmony-js/staking
This package provides a collection of apis to create, sign/send staking transaction, and receive confirm/receipt.
## Installation
```
npm install @harmony-js/staking
```
## Usage
Create a Harmony instance connecting to testnet
```javascript
* const { Harmony } = require('@harmony-js/core');
* const {
* ChainID,
* ChainType,
* hexToNumber,
* numberToHex,
* fromWei,
* Units,
* Unit,
* } = require('@harmony-js/utils');
* const hmy = new Harmony(
* 'https://api.s0.b.hmny.io/',
* {
* chainType: ChainType.Harmony,
* chainId: ChainID.HmyTestnet,
* },
* );
```
Below, examples show how to send delegate, undelegate, and collect rewards staking transactions. First, set the chainId, gasLimit, gasPrice for all subsequent staking transactions
```javascript
* hmy.stakings.setTxParams({
* gasLimit: 25000,
* gasPrice: numberToHex(new hmy.utils.Unit('1').asGwei().toWei()),
* chainId: 2
* });
```
<span style="color:red">Note: create and edit validator transactions are not fully supported in the sdk</span>
Create delegate staking transaction
```javascript
* const delegate = hmy.stakings.delegate({
* delegatorAddress: 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7',
* validatorAddress: 'one1vfqqagdzz352mtvdl69v0hw953hm993n6v26yl',
* amount: numberToHex(new Unit(1000).asOne().toWei())
* });
* const delegateStakingTx = delegate.build();
```
Sign and send the delegate transaction and receive confirmation
```javascript
* // key corresponds to one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7, only has testnet balance
* hmy.wallet.addByPrivateKey('45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e');
* hmy.wallet.signStaking(delegateStakingTx).then(signedTxn => {
* signedTxn.sendTransaction().then(([tx, hash]) => {
* console.log(hash);
* signedTxn.confirm(hash).then(response => {
* console.log(response.receipt);
* });
* });
* });
```
Similarily, undelegate and collect reward transactions can be composed, signed and sent
Create undelegate staking transaction
```javascript
* const undelegate = hmy.stakings.undelegate({
* delegatorAddress: 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7',
* validatorAddress: 'one1vfqqagdzz352mtvdl69v0hw953hm993n6v26yl',
* amount: numberToHex(new Unit(1000).asOne().toWei())
* });
* const undelegateStakingTx = undelegate.build();
```
Create collect rewards staking transaction
```javascript
* const collectRewards = hmy.stakings.collectRewards({
* delegatorAddress: 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7'
* });
* const collectRewardsStakingTx = collectRewards.build();
```
Also, similar to normal transaction, signing and sending can be performed asynchronously.
* @packageDocumentation * @packageDocumentation
* @module harmony-staking * @module harmony-staking
*/ */

@ -1,84 +1,152 @@
/** /**
* ## About this package # @harmony-js/transaction
*
* `@harmony-js/transaction` provides the functions to build transactions This package provides a collection of apis to create, sign/send transaction, and receive confirm/receipt.
*
* Develop can use this package to: ## Installation
* - build a transaction offline!
* - set params of transaction ```
* - npm install @harmony-js/transaction
* ```
* ## How to use this package
* ### Step 1: create a Harmony Instance ## Usage
* ```javascript
* const { Harmony } = require('@harmony-js/core'); Create a Harmony instance connecting to testnet
* const { ChainID, ChainType } = require('@harmony-js/utils');
* const { BN } = require('@harmony-js/crypto'); ```javascript
* * const { Harmony } = require('@harmony-js/core');
* const hmy = new Harmony( * const {
* 'http://localhost:9500', * ChainID,
* { * ChainType,
* chainType: ChainType.Harmony, * hexToNumber,
* chainId: ChainID.HmyLocal, * numberToHex,
* }, * fromWei,
* ); * Units,
* ``` * Unit,
* * } = require('@harmony-js/utils');
* ### Step 2: build a transaction
* ```javascript * const hmy = new Harmony(
* const txn = hmy.transactions.newTx({ * 'https://api.s0.b.hmny.io/',
* to: 'one166axnkjmghkf3df7xfvd0hn4dft8kemrza4cd2', * {
* value: '10000', * chainType: ChainType.Harmony,
* gasLimit: '210000', * chainId: ChainID.HmyTestnet,
* shardID: 0, * },
* toShardID: 0, * );
* gasPrice: new hmy.utils.Unit('100').asGwei().toWei(), ```
* });
* ``` Creating a new transaction using parameters
* ```javascript
* ## some important information * const txn = hmy.transactions.newTx({
* Transaction Parameters * to: 'one166axnkjmghkf3df7xfvd0hn4dft8kemrza4cd2',
* ```java * value: new Unit(1).asOne().toWei(),
* // interface TxParams * // gas limit, you can use string
* id: string; * gasLimit: '21000',
* from: string; * // send token from shardID
* to: string; * shardID: 0,
* nonce: number | string; * // send token to toShardID
* gasLimit: number | string | BN; * toShardID: 0,
* gasPrice: number | string | BN; * // gas Price, you can use Unit class, and use Gwei, then remember to use toWei(), which will be transformed to BN
* shardID: number | string; * gasPrice: new hmy.utils.Unit('1').asGwei().toWei(),
* toShardID: number | string; * });
* data: string; ```
* value: number | string | BN;
* chainId: number; Recovering transaction from raw transaction hash
* rawTransaction: string; ```javascript
* unsignedRawTransaction: string; * const raw = '0xf86d21843b9aca00825208808094d6ba69da5b45ec98b53e3258d7de756a567b6763880de0b6b3a76400008028a0da8887719f377401963407fc1d82d2ab52404600cf7bea37c27bd2dfd7c86aaaa03c405b0843394442b303256a804bde835821a8a77bd88a2ced9ffdc8b0a409e9';
* signature: Signature; * const tx = hmy.transactions.recover(raw);
* receipt?: TransasctionReceipt; ```
* ```
* Getting the RLP encoding of a transaction (rawTransaction), along with raw transaction field values that were encoded
* Transaction Receipt ```javascript
* ```java * const [encoded, raw] = txn.getRLPUnsigned()
* // interface TransasctionReceipt ```
* transactionHash: string;
* transactionIndex: string; Sign the transaction using a wallet and send the transaction, wait for confirmation and print receipt
* blockHash: string; ```javascript
* blockNumber: string; // 11 * // key corresponds to one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7, only has testnet balance
* from: string; * hmy.wallet.addByPrivateKey('45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e');
* to: string;
* gasUsed: string; * hmy.wallet.signTransaction(txn).then(signedTxn => {
* cumulativeGasUsed: string; // 13244 * signedTxn.sendTransaction().then(([tx, hash]) => {
* contractAddress?: string | null; // or null, if none was created * console.log('tx hash: ' + hash);
* logs: any[]; * signedTxn.confirm(hash).then(response => {
* logsBloom: string; // 256 byte bloom filter * console.log(response.receipt);
* v: string; * });
* r: string; * });
* s: string; * });
* responseType?: string; ```
* byzantium?: boolean;
* status?: string; // post Byzantium will return `0x0` or `0x1` Asynchronous transaction sign, send, and confirm
* root?: string; // pre Byzantium will return `root` ```javascript
* ``` * async function transfer() {
* hmy.wallet.addByPrivateKey('45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e');
* const signedTxn = await hmy.wallet.signTransaction(txn);
* signedTxn
* .observed()
* .on('transactionHash', (txnHash) => {
* console.log('');
* console.log('--- hash ---');
* console.log('');
* console.log(txnHash);
* console.log('');
* })
* .on('receipt', (receipt) => {
* console.log('');
* console.log('--- receipt ---');
* console.log('');
* console.log(receipt);
* console.log('');
* })
* .on('cxReceipt', (receipt) => {
* console.log('');
* console.log('--- cxReceipt ---');
* console.log('');
* console.log(receipt);
* console.log('');
* })
* .on('error', (error) => {
* console.log('');
* console.log('--- error ---');
* console.log('');
* console.log(error);
* console.log('');
* });
* const [sentTxn, txnHash] = await signedTxn.sendTransaction();
* const confiremdTxn = await sentTxn.confirm(txnHash);
* // if the transactino is cross-shard transaction
* if (!confiremdTxn.isCrossShard()) {
* if (confiremdTxn.isConfirmed()) {
* console.log('--- Result ---');
* console.log('');
* console.log('Normal transaction');
* console.log(`${txnHash} is confirmed`);
* console.log('');
* console.log('please see detail in explorer:');
* console.log('');
* console.log('https://explorer.testnet.harmony.one/#/tx/' + txnHash);
* console.log('');
* process.exit();
* }
* }
* if (confiremdTxn.isConfirmed() && confiremdTxn.isCxConfirmed()) {
* console.log('--- Result ---');
* console.log('');
* console.log('Cross-Shard transaction');
* console.log(`${txnHash} is confirmed`);
* console.log('');
* console.log('please see detail in explorer:');
* console.log('');
* console.log('https://explorer.testnet.harmony.one/#/tx/' + txnHash);
* console.log('');
* process.exit();
* }
* }
* transfer();
```
* *
* @packageDocumentation * @packageDocumentation
* @module harmony-transaction * @module harmony-transaction

@ -1,124 +1,64 @@
/** /**
* ## About this package # @harmony-js/utils
*
* `@harmony-js/util` provides utility functions for Harmony dapps and other `harmony-js` packages This package provides a collection of utility apis for unit conversions like `fromWei`, `toWei`, `hexToNumber`, `numberToHex`, `isAddress`, etc.
*
* Develop can use this package to: ## Installation
* - Transform the unit of token (fromWei, toWei...)
* - Convert variable to different type (hexToBN, numberToHex...) ```
* - Check validators information (isAddress, isPublicKey, isBlockNumber...) npm install @harmony-js/utils
* ```
* ## How to use this package
* ## Usage
* ### Step 1: create a Harmony Instance
* ```javascript Available units
* const { Harmony } = require('@harmony-js/core'); ```
* const { ChainID, ChainType } = require('@harmony-js/utils'); const { Units } = require('@harmony-js/utils');
* const { BN } = require('@harmony-js/crypto');
* [Units.wei, '1'], // 1 wei
* const hmy = new Harmony( [Units.Kwei, '1000'], // 1e3 wei
* 'http://localhost:9500', [Units.Mwei, '1000000'], // 1e6 wei
* { [Units.Gwei, '1000000000'], // 1e9 wei
* chainType: ChainType.Harmony, [Units.szabo, '1000000000000'], // 1e12 wei
* chainId: ChainID.HmyLocal, [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
* ### Step 2: Select and call functions [Units.Gether, '1000000000000000000000000000'], // 1e27 wei
* Here are some examples: [Units.Tether, '1000000000000000000000000000000'], // 1e30 wei
* ```
* ```javascript
* // numberToString Converting between different units
* const num = 123; ```javascript
* const str = hmy.utils.numberToString(num) const { Units, Unit, numberToString, add0xToString, fromWei, toWei, numToStr} = require('@harmony-js/utils');
* console.log(str); const { BN } = require('@harmony-js/crypto');
*
* // add0xToString const one = new Unit('1').asOne();
* const str = '12345'; const oneToGwei = one.toGwei();
* const expected = hmy.utils.add0xToString(str) console.log(oneToGwei);
* console.log(expected);
* // numberToString
* // fromWei const num = 123;
* const Wei = new BN('1000000000000000000'); const str = numberToString(num)
* const expected = hmy.utils.fromWei(Wei, hmy.utils.Units.one); console.log(str);
* console.log(expected);
* // add0xToString
* // toWei const str = '12345';
* const one = new BN('1'); const expected = add0xToString(str)
* const expected = hmy.utils.toWei(one, hmy.utils.Units.one); console.log(expected);
* const num = hmy.utils.numToStr(expected);
* console.log(num); // fromWei
* ``` const Wei = new BN('1000000000000000000');
* const expected = fromWei(Wei, Units.one);
* ### Step 3: Using unit class to convet the token unit console.log(expected);
* ```javascript
* // convert one to Gwei // toWei
* const one = new hmy.utils.Unit('1').asOne(); const one = new BN('1');
* const oneToGwei = one.toGwei(); const expected = toWei(one, hmy.utils.Units.one);
* console.log(oneToGwei); const num = numToStr(expected);
* ``` console.log(num);
* ```
* ## 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 * @packageDocumentation
* @module harmony-utils * @module harmony-utils

Loading…
Cancel
Save