Compare commits

..

1 Commits

Author SHA1 Message Date
Raptor 44d58f1ba1 Add txParams function to the harmony-js/staking 4 years ago
  1. 5
      .env
  2. 5
      .env.example
  3. 9
      .gitignore
  4. 2
      .travis.yml
  5. 42
      README.md
  6. 4
      RELEASE.md
  7. 12
      docs/README.md
  8. 24
      e2e/fixtures/transactions.json
  9. 161
      e2e/src/blockchain.e2e.ts
  10. 29
      e2e/src/harmony.ts
  11. 147
      e2e/src/transaction.e2e.ts
  12. 282
      e2e/src/txn_rpc.e2e.ts
  13. 39
      e2e/src/woop.ts
  14. 16
      e2e/tsconfig.json
  15. 134
      examples/README.md
  16. 31
      examples/balance.js
  17. 45
      examples/import_keystore.js
  18. 14
      examples/package.json
  19. 79
      examples/staking_create.js
  20. 172
      examples/staking_delegate.js
  21. 74
      examples/staking_test.js
  22. 177
      examples/staking_transfer.js
  23. 173
      examples/staking_undelegate.js
  24. 31
      examples/test.js
  25. 40
      examples/test2.js
  26. 153
      examples/transfer.js
  27. 151
      examples/transfer_dev.js
  28. 137
      examples/transfer_local.js
  29. 16
      gulpfile.js
  30. 2
      lerna.json
  31. 1081
      log.txt
  32. 44661
      package-lock.json
  33. 20
      package.json
  34. 18
      packages/README.md
  35. 0
      packages/harmony-account/LICENSE
  36. 36
      packages/harmony-account/README.md
  37. 274
      packages/harmony-account/guide.ts
  38. 18
      packages/harmony-account/package.json
  39. 111
      packages/harmony-account/src/account.ts
  40. 31
      packages/harmony-account/src/hdnode.ts
  41. 2
      packages/harmony-account/src/index.ts
  42. 2
      packages/harmony-account/src/types.ts
  43. 14
      packages/harmony-account/src/utils.ts
  44. 30
      packages/harmony-account/src/wallet.ts
  45. 19
      packages/harmony-account/test/testAccount.test.ts
  46. 10
      packages/harmony-account/tsconfig.json
  47. 0
      packages/harmony-account/tsconfig.test.json
  48. 8
      packages/harmony-contract/Counter.json
  49. 0
      packages/harmony-contract/LICENSE
  50. 56
      packages/harmony-contract/README.md
  51. 16
      packages/harmony-contract/package.json
  52. 266
      packages/harmony-contract/src/abi/abiCoder.ts
  53. 6
      packages/harmony-contract/src/abi/api.ts
  54. 2
      packages/harmony-contract/src/abi/index.ts
  55. 6
      packages/harmony-contract/src/abi/utils.ts
  56. 17
      packages/harmony-contract/src/contract.ts
  57. 4
      packages/harmony-contract/src/contractFactory.ts
  58. 4
      packages/harmony-contract/src/events/event.ts
  59. 4
      packages/harmony-contract/src/events/eventFactory.ts
  60. 2
      packages/harmony-contract/src/index.ts
  61. 164
      packages/harmony-contract/src/methods/method.ts
  62. 10
      packages/harmony-contract/src/methods/methodFactory.ts
  63. 4
      packages/harmony-contract/src/models/AbiItemModel.ts
  64. 24
      packages/harmony-contract/src/models/AbiModel.ts
  65. 2
      packages/harmony-contract/src/models/types.ts
  66. 2
      packages/harmony-contract/src/utils/decoder.ts
  67. 13
      packages/harmony-contract/src/utils/encoder.ts
  68. 6
      packages/harmony-contract/src/utils/formatter.ts
  69. 11
      packages/harmony-contract/src/utils/mapper.ts
  70. 2
      packages/harmony-contract/src/utils/options.ts
  71. 2
      packages/harmony-contract/src/utils/status.ts
  72. 4
      packages/harmony-contract/test/abiCoder.test.ts
  73. 0
      packages/harmony-contract/test/fixtures/abiv2.ts
  74. 10
      packages/harmony-contract/tsconfig.json
  75. 0
      packages/harmony-contract/tsconfig.test.json
  76. 0
      packages/harmony-core/LICENSE
  77. 48
      packages/harmony-core/README.md
  78. 20
      packages/harmony-core/package.json
  79. 430
      packages/harmony-core/src/blockchain.ts
  80. 68
      packages/harmony-core/src/harmony.ts
  81. 36
      packages/harmony-core/src/harmonyExtension.ts
  82. 6
      packages/harmony-core/src/index.ts
  83. 38
      packages/harmony-core/src/truffleProvider.ts
  84. 31
      packages/harmony-core/src/types.ts
  85. 38
      packages/harmony-core/src/util.ts
  86. 6
      packages/harmony-core/test/blockchain.test.ts
  87. 16
      packages/harmony-core/tsconfig.json
  88. 0
      packages/harmony-core/tsconfig.test.json
  89. 0
      packages/harmony-crypto/LICENSE
  90. 16
      packages/harmony-crypto/README.md
  91. 10
      packages/harmony-crypto/package.json
  92. 54
      packages/harmony-crypto/src/address.ts
  93. 12
      packages/harmony-crypto/src/bech32.ts
  94. 2
      packages/harmony-crypto/src/bytes.ts
  95. 138
      packages/harmony-crypto/src/errors.ts
  96. 2
      packages/harmony-crypto/src/index.ts
  97. 2
      packages/harmony-crypto/src/keccak256.ts
  98. 8
      packages/harmony-crypto/src/keyTool.ts
  99. 7
      packages/harmony-crypto/src/keystore.ts
  100. 2
      packages/harmony-crypto/src/random.ts
  101. Some files were not shown because too many files have changed in this diff Show More

@ -0,0 +1,5 @@
GENESIS_PRIV_KEY=45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e
HTTP_PROVIDER=http://localhost:9500
CHAIN_TYPE=hmy
CHAIN_ID=2

@ -0,0 +1,5 @@
GENESIS_PRIV_KEY=45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e
HTTP_PROVIDER=http://localhost:9500
CHAIN_TYPE=hmy
CHAIN_ID=2

9
.gitignore vendored

@ -5,7 +5,12 @@
*.tsbuildinfo
.vscode/
# babel
# package.json
package-lock.json
packages/*/package-lock.json
/packages/*/package-lock.json
packages/*/babel.rc
# lerna
@ -77,4 +82,4 @@ buck-out/
*.jsbundle
# Jest coverage
coverage/
coverage/

@ -2,7 +2,7 @@ language: node_js
sudo: true
dist: trusty
node_js:
- 16
- 10
branches:
except:
- /^v[0-9]/

@ -1,23 +1,20 @@
# Woop JavaScript SDK
# Harmony JavaScript API
[![npm version](https://img.shields.io/npm/v/@woop-js/core.svg?style=flat-square)](https://www.npmjs.com/package/@woop-js/core)
[![Build Status](https://travis-ci.com/FireStack-Lab/Woop-sdk-core.svg?branch=master)](https://travis-ci.com/FireStack-Lab/Woop-sdk-core)
[![npm version](https://img.shields.io/npm/v/@harmony-js/core.svg?style=flat-square)](https://www.npmjs.com/package/@harmony-js/core)
[![Build Status](https://travis-ci.com/FireStack-Lab/Harmony-sdk-core.svg?branch=master)](https://travis-ci.com/FireStack-Lab/Harmony-sdk-core)
This is the Woop Javascript SDK which provides an easier way to interact with Woop blockchain.
This is the Harmony javascript library which provides an easier way to interact with Harmony's blockchain.
Please read the [documentation](https://jssdk.doc.hmny.io/) for full API doc.
The SDK includes following packages with package-level documentation and examples inside each package.
1. [@woop-js/core](https://github.com/woop-chain/sdk/tree/master/packages/woop-core)
2. [@woop-js/account](https://github.com/woop-chain/sdk/tree/master/packages/woop-account)
3. [@woop-js/crypto](https://github.com/woop-chain/sdk/tree/master/packages/woop-crypto)
4. [@woop-js/network](https://github.com/woop-chain/sdk/tree/master/packages/woop-network)
5. [@woop-js/utils](https://github.com/woop-chain/sdk/tree/master/packages/woop-utils)
6. [@woop-js/transaction](https://github.com/woop-chain/sdk/tree/master/packages/woop-transaction)
7. [@woop-js/contract](https://github.com/woop-chain/sdk/tree/master/packages/woop-contract)
8. [@woop-js/staking](https://github.com/woop-chain/sdk/tree/master/packages/woop-staking)
This libraries contains a few packages.
1. [@harmony-js/core](https://github.com/harmony-one/sdk/tree/master/packages/harmony-core)
2. [@harmony-js/account](https://github.com/harmony-one/sdk/tree/master/packages/harmony-account)
3. [@harmony-js/crypto](https://github.com/harmony-one/sdk/tree/master/packages/harmony-crypto)
4. [@harmony-js/network](https://github.com/harmony-one/sdk/tree/master/packages/harmony-network)
5. [@harmony-js/utils](https://github.com/harmony-one/sdk/tree/master/packages/harmony-utils)
6. [@harmony-js/transaction](https://github.com/harmony-one/sdk/tree/master/packages/harmony-transaction)
7. [@harmony-js/contract](https://github.com/harmony-one/sdk/tree/master/packages/harmony-contract)
8. [@harmony-js/staking](https://github.com/harmony-one/sdk/tree/master/packages/harmony-contract)
# Installation
@ -35,10 +32,10 @@ This library works on both nodejs and browser. Please use it according to your u
```bash
# npm
npm install @woop-js/core@next
npm install @harmony-js/core@next
# yarn
yarn add @woop-js/core@next
yarn add @harmony-js/core@next
# tslib is required, we'd better install it as well
npm install tslib
@ -76,9 +73,12 @@ yarn test:src
```
## e2e tests
1. Remove the `'cross-fetch': 'jest-fetch-mock'` line from `scripts/jest/jest.e2e.config.js`
1. Run woop node locally, follow the instructions: https://github.com/woop-chain/woop
1. Wait for 1-2 mins, and run this:
1. `.env` file defines configuration, edit if you have custom settings
2. Run harmony node locally, follow the instructions: https://github.com/harmony-one/harmony
3. Wait for 1-2 mins, and run this:
```bash
yarn build && yarn test:e2e
```

@ -37,7 +37,7 @@ This will not change the release version of current npm packages(currently 0.0.7
For example.
```bash
npm install @woop-js/core@next
npm install @harmony-js/core@next
```
@ -60,7 +60,7 @@ This will change the release version of current npm packages to the latest versi
For example.
```bash
npm install @woop-js/core
npm install @harmony-js/core
```

@ -1,6 +1,6 @@
# Woop JS-SDK Documentation
# Harmony JS-SDK Documentation
## [CLICK ME!!](https://woop-js-sdk-doc.s3-us-west-1.amazonaws.com/index.html) to see the documentation
## [CLICK ME!!](https://harmony-js-sdk-doc.s3-us-west-1.amazonaws.com/index.html) to see the documentation
# metaDocumentation
## Summary
@ -38,14 +38,14 @@ $ npm install
### Generate HTML
```
$ cd docs
$ npx typedoc --out ./build ../packages/ --ignoreCompilerErrors --theme default --name Woop_SDK_Doc --readme ../README.md
$ npx typedoc --out ./build ../packages/ --ignoreCompilerErrors --theme default --name Harmony_SDK_Doc --readme ../README.md
```
### See the generated doc at local
>open the `index.html` under the path `sdk/docs/build/index.html`
## Step 2: Deploy on AWS (woop core only!)
## Step 2: Deploy on AWS (harmony core only!)
### Create an AWS s3 bucket
Actually, there are just two points needed!
@ -70,7 +70,7 @@ After that, use AWS CLI to do following
1. Create a Bucket
```
aws s3 mb s3://woop-js-sdk-doc
aws s3 mb s3://harmony-js-sdk-doc
```
2. List all buckets you have created
@ -87,7 +87,7 @@ Here is some explanations
> **./account**
> the path of folder which we want to upload
>
> **s3://woop-js-sdk-doc**
> **s3://harmony-js-sdk-doc**
> the bucket name on AWS S3
>
> **--grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers**

@ -110,29 +110,5 @@
"gasPrice": "0x174876e800",
"rawTransaction": "0xf8690985174876e8008252088080949d72989b68777a1f3ffd6f1db079f1928373ee52830f42408028a022efd1decb6e80e88fd33f5e189f48105acc72f7e302931221183f86ca8a7015a02001dee44471a5397a4579f733b3a13a86ba1d6c78ad3312187513d6a424f72b"
}
],
"hashes": [
"0x5aE91eCA3BF7CB97FCd1305bD6e030e24bda9bbfED3b8c741Efe808e8D4F95Ff",
"0xf4CA9DdED0bC36B5AFBCf4fC6De082DFd0F7FCFad1c2aFC1aF52d16d9Dbd733f",
"0x56C2408c5F58ac9aDFE824B7755f3b54CB0848c7A837Ea1CC5a0FdB521D4A1a2",
"0xACFD09AD729E0C9f23EC9eEf27CC68bA37D7EE9D53aABace2dDD42616Eb8351A",
"0xB8baee4EfB120254Afab3092c8Ccc458fF49eBda12ead9950CD39ac8Bb26D4C1",
"0x412D8DBF0BC3dCAf91A0339EEadd1EEB44b44cD0cEBFaea0d35656d31F96Dde9",
"0xbbeDcd6e4dCDef0c666C0C0c7914ba1E5617F8d57ddc40C32cCb31D4BC5CAfBF",
"0x6E008bEbC8F2CE750d208dbF987edEf7476DcFDF8Eb8607f3B3c2E1ce8675ba9",
"0x0Ff0AcBD45cdDf3A8A148eb2F4Fe6dBf74B422eabdD0766ba9284f0Fe8F6dc8a",
"0x7FDCEE6B5EEf5C3F82B2Ffe8a088E0d3d485bEbBcdBCac16ECCb9d1cbfe50c91"
],
"blockHashes": [
"0x9dD4e063d8cc7A6Fe74a0E3AC4feD5F84eB8Bdc4647Ba8DAd651FD1b4a3979cE",
"0xEF5F7D7ca60bE76c1Cc5aADD8DC9e1bC0F7a3BCD0EEDA6e9Cca0EACAd99BE3Bb",
"0x4261B409CCcDA3ab97aABCFe8dECCfd65D1aB9Bb536dD57Fdafd191FC6BbFbbc",
"0x1fb05a17794cAd1ac025469eA1Bf5af4F33f9bdbD3c0e14bCeca323BC5DF0EC3",
"0xEA405dB5dc0E7e2DB2CfdBf272DCeAf69E9CDa2DFD47229b38A3C5b7b9cc41fB",
"0xCC1ADfef1bb2E496A3BbDb181ec5c8EA047AE340FaD6fF4FeF3CCE452c1975B6",
"0x80dffAe15B6619Cc7aD74Bc132C1b29EFc38B8d8CAD1AfbDb9E37f7357E2EBe4",
"0x6BcB9858d8cCE9de2a6ECd6392A5eC712be9b4A79F6Cf84De8aa5ae9C04f60A8",
"0xB6De43A866dFcE1f7AA7DA0E8e9eb7Fe545cB6becF7cf5fdC564B22C4cBb72b9",
"0xc4b4CeAEAEadADfa8CbCcDeFdcBaBeF999dBF42D14C9AFEDd1de2956B571CebD"
]
}

@ -1,169 +1,88 @@
import fetch from 'jest-fetch-mock';
import { woop, checkCalledMethod } from './woop';
import {harmony} from './harmony';
import demoAccounts from '../fixtures/testAccount.json';
import { RPCMethod } from '@woop-js/network';
const bc = woop.blockchain;
const bc = harmony.blockchain;
const testAccount = demoAccounts.Accounts[1];
describe('e2e test blockchain', () => {
beforeEach(() => {
fetch.resetMocks();
});
// net_*
it('should test net_peerCount', async () => {
fetch.mockResponseOnce(
JSON.stringify({"jsonrpc": "2.0", "id": 1, "result": "0x0"}),
);
const peerCount = await bc.net_peerCount();
expect(checkCalledMethod(0, RPCMethod.PeerCount)).toEqual(true);
expect(woop.utils.isHex(peerCount.result)).toEqual(true);
expect(harmony.utils.isHex(peerCount.result)).toEqual(true);
});
it('should test net_version', async () => {
fetch.mockResponseOnce(
JSON.stringify({"jsonrpc": "2.0", "id": 1, "result": "5"}),
);
const netVersion = await bc.net_version();
const versionNumber = parseInt(netVersion.result as string, 10);
expect(netVersion.result).toEqual(`${versionNumber}`);
expect(checkCalledMethod(0, RPCMethod.NetVersion)).toEqual(true);
});
it('should test wiki_protocolVersion', async () => {
fetch.mockResponseOnce(
JSON.stringify({"jsonrpc": "2.0", "id": 1, "result": "0x10"}),
);
it('should test hmy_protocolVersion', async () => {
const protocolVersion = await bc.getProtocolVersion();
expect(woop.utils.isHex(protocolVersion.result)).toEqual(true);
expect(checkCalledMethod(0, RPCMethod.ProtocolVersion)).toEqual(true);
expect(harmony.utils.isHex(protocolVersion.result)).toEqual(true);
});
// block chain info
it('should test wiki_blockNumber', async () => {
fetch.mockResponseOnce(
JSON.stringify({"jsonrpc": "2.0", "id": 1, "result": "0x10"}),
);
it('should test hmy_blockNumber', async () => {
const res = await bc.getBlockNumber();
expect(res.responseType).toEqual('raw');
expect(woop.utils.isHex(res.result)).toEqual(true);
expect(checkCalledMethod(0, RPCMethod.BlockNumber)).toEqual(true);
expect(harmony.utils.isHex(res.result)).toEqual(true);
});
it('should test wiki_getBlockByNumber', async () => {
fetch.mockResponse(
JSON.stringify({
"jsonrpc": "2.0",
"id": 1,
"result": {
"size": "0x1",
"difficulty": 5,
"extraData": "0x",
"gasLimit": "0x80",
"gasUsed": "0x40",
"hash": "0x8a3390ab500Fbca6514eB326d2fcD9B3BFCFbA7DA392593cB4885b8e3399a2D8",
"logsBloom": "0x0",
"miner": "one155jp2y76nazx8uw5sa94fr0m4s5aj8e5xm6fu3",
"mixHash": "0x3A7c1Ae14AfecFf55Da298F66b75F4FfB771c3EaBDeAa267FF33A77d4d0be220",
"nonce": 1,
"number": "0x1",
"parentHash": "0x7CebC07e456F0bCD09dbc9A6f271074d93E27B40A4C67Dcc402e6513e12B9aF9",
"receiptsRoot": "0x02B82e11eDC07775Dc6fCF706be2cdAF9165750Ea7bC1B3Eb48ea16Bb3072F4D",
"stateRoot": "0xAaDc89C8bA4e3fCfC140cFcc8D3efD3BE7a49ab31534A5a3F0E1DEA09aae0f4a",
"timestamp": "0x62c44c0a",
"transactionsRoot": "0xc4bfa888fDCC8ca70E2b0CcdCEcc2fF545acCC2D655Ba33DaF4aBc31cFDBd9Ac",
"uncles": []
}
}),
);
const res = await bc.getBlockByNumber({ blockNumber: 'latest' });
it('should test hmy_getBlockByNumber', async () => {
const res = await bc.getBlockByNumber({blockNumber: 'latest'});
const size = res.result.size;
expect(res.responseType).toEqual('raw');
expect(woop.utils.isHex(size)).toEqual(true);
expect(harmony.utils.isHex(size)).toEqual(true);
expect(checkBlockData(res.result)).toEqual(true);
const res2 = await bc.getBlockByNumber({ blockNumber: res.result.number });
const res2 = await bc.getBlockByNumber({blockNumber: res.result.number});
expect(res2.responseType).toEqual('raw');
expect(woop.utils.isHex(res2.result.size)).toEqual(true);
expect(harmony.utils.isHex(res2.result.size)).toEqual(true);
expect(checkBlockData(res2.result)).toEqual(true);
const res3 = await bc.getBlockByNumber({ returnObject: true });
const res3 = await bc.getBlockByNumber({returnObject: true});
expect(res3.responseType).toEqual('raw');
expect(checkBlockData(res3.result)).toEqual(true);
for(let i = 0; i < 3; i++) {
expect(checkCalledMethod(i, RPCMethod.GetBlockByNumber)).toEqual(true);
}
});
it('should test wiki_getBlockByHash', async () => {
fetch.mockResponse(
JSON.stringify({
"jsonrpc": "2.0",
"id": 1,
"result": {
"size": "0x1",
"difficulty": 5,
"extraData": "0x",
"gasLimit": "0x80",
"gasUsed": "0x40",
"hash": "0x8a3390ab500Fbca6514eB326d2fcD9B3BFCFbA7DA392593cB4885b8e3399a2D8",
"logsBloom": "0x0",
"miner": "one155jp2y76nazx8uw5sa94fr0m4s5aj8e5xm6fu3",
"mixHash": "0x3A7c1Ae14AfecFf55Da298F66b75F4FfB771c3EaBDeAa267FF33A77d4d0be220",
"nonce": 1,
"number": "0x1",
"parentHash": "0x7CebC07e456F0bCD09dbc9A6f271074d93E27B40A4C67Dcc402e6513e12B9aF9",
"receiptsRoot": "0x02B82e11eDC07775Dc6fCF706be2cdAF9165750Ea7bC1B3Eb48ea16Bb3072F4D",
"stateRoot": "0xAaDc89C8bA4e3fCfC140cFcc8D3efD3BE7a49ab31534A5a3F0E1DEA09aae0f4a",
"timestamp": "0x62c44c0a",
"transactionsRoot": "0xc4bfa888fDCC8ca70E2b0CcdCEcc2fF545acCC2D655Ba33DaF4aBc31cFDBd9Ac",
"uncles": []
}
}),
);
const latestBlock = await bc.getBlockByNumber({ blockNumber: 'latest' });
const res = await bc.getBlockByHash({ blockHash: latestBlock.result.hash });
it('should test hmy_getBlockByHash', async () => {
const latestBlock = await bc.getBlockByNumber({blockNumber: 'latest'});
const res = await bc.getBlockByHash({blockHash: latestBlock.result.hash});
expect(res.responseType).toEqual('raw');
expect(latestBlock.result.hash).toEqual(res.result.hash);
expect(woop.utils.isHex(res.result.size)).toEqual(true);
expect(harmony.utils.isHex(res.result.size)).toEqual(true);
expect(checkBlockData(res.result)).toEqual(true);
expect(checkCalledMethod(0, RPCMethod.GetBlockByNumber)).toEqual(true);
expect(checkCalledMethod(1, RPCMethod.GetBlockByHash)).toEqual(true);
});
// account related
it('should test wiki_getBalance', async () => {
fetch.mockResponseOnce(
JSON.stringify({"jsonrpc": "2.0", "id": 1, "result": "0x10"}),
);
const balance = await bc.getBalance({ address: testAccount.Address });
expect(woop.utils.isHex(balance.result)).toEqual(true);
expect(checkCalledMethod(0, RPCMethod.GetBalance)).toEqual(true);
it('should test hmy_getBalance', async () => {
const balance = await bc.getBalance({address: testAccount.Address});
expect(harmony.utils.isHex(balance.result)).toEqual(true);
});
});
function checkBlockData(data: any) {
return woop.utils.validateArgs(
return harmony.utils.validateArgs(
data,
{
difficulty: [woop.utils.isNumber],
difficulty: [harmony.utils.isNumber],
// tslint:disable-next-line: no-shadowed-variable
extraData: [(data: any) => data === '0x' || woop.utils.isHex(data)],
gasLimit: [woop.utils.isHex],
gasUsed: [woop.utils.isHex],
hash: [woop.utils.isHash],
logsBloom: [woop.utils.isHex],
miner: [woop.utils.isBech32Address],
mixHash: [woop.utils.isHash],
nonce: [woop.utils.isNumber],
number: [woop.utils.isHex],
parentHash: [woop.utils.isHash],
receiptsRoot: [woop.utils.isHash],
size: [woop.utils.isHex],
stateRoot: [woop.utils.isHash],
timestamp: [woop.utils.isHex],
transactionsRoot: [woop.utils.isHash],
uncles: [woop.utils.isArray],
extraData: [(data: any) => data === '0x' || harmony.utils.isHex(data)],
gasLimit: [harmony.utils.isHex],
gasUsed: [harmony.utils.isHex],
hash: [harmony.utils.isHash],
logsBloom: [harmony.utils.isHex],
miner: [harmony.utils.isAddress],
mixHash: [harmony.utils.isHash],
nonce: [harmony.utils.isNumber],
number: [harmony.utils.isHex],
parentHash: [harmony.utils.isHash],
receiptsRoot: [harmony.utils.isHash],
size: [harmony.utils.isHex],
stateRoot: [harmony.utils.isHash],
timestamp: [harmony.utils.isHex],
transactionsRoot: [harmony.utils.isHash],
uncles: [harmony.utils.isArray],
},
{ transactions: [woop.utils.isArray] },
{transactions: [harmony.utils.isArray]},
);
}
}

@ -0,0 +1,29 @@
// tslint:disable-next-line: no-implicit-dependencies
import { Harmony } from '@harmony-js/core';
// tslint:disable-next-line: no-implicit-dependencies
import { ChainType } from '@harmony-js/utils';
// tslint:disable-next-line: no-implicit-dependencies
import { Account } from '@harmony-js/account';
const CHAIN_ID: number = parseInt(process.env.CHAIN_ID as string, 10);
const CHAIN_TYPE: string = process.env.CHAIN_TYPE as string;
const HTTP_PROVIDER: string = process.env.HTTP_PROVIDER as string;
const GENESIS_PRIV_KEY: string = process.env.GENESIS_PRIV_KEY as string;
let chainType: ChainType = ChainType.Harmony;
if (CHAIN_TYPE === 'hmy') {
chainType = ChainType.Harmony;
} else if (CHAIN_TYPE === 'eth') {
chainType = ChainType.Ethereum;
}
export const harmony: Harmony = new Harmony(HTTP_PROVIDER, {
chainId: CHAIN_ID,
chainType,
chainUrl: HTTP_PROVIDER,
});
export const myAccount: Account = harmony.wallet.addByPrivateKey(
GENESIS_PRIV_KEY,
);

@ -1,20 +1,15 @@
import fetch from 'jest-fetch-mock';
import { woop, checkCalledMethod } from './woop';
import { harmony } from './harmony';
// tslint:disable-next-line: no-implicit-dependencies
import { Transaction, TxStatus } from '@woop-js/transaction';
import { Transaction, TxStatus } from '@harmony-js/transaction';
// tslint:disable-next-line: no-implicit-dependencies
import { isHash, numberToHex } from '@woop-js/utils';
import { isHash, numberToHex } from '@harmony-js/utils';
import txnJsons from '../fixtures/transactions.json';
import demoAccounts from '../fixtures/testAccount.json';
import { RPCMethod } from '@woop-js/network';
const receiver = demoAccounts.Accounts[3];
jest.useRealTimers();
describe('test Transaction using SDK', () => {
beforeEach(() => {
fetch.resetMocks();
});
let signed: Transaction;
let sent: Transaction;
let txId: string;
@ -23,7 +18,7 @@ describe('test Transaction using SDK', () => {
const txns = txnJsons.transactions;
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < txns.length; i += 1) {
const newTxn = woop.transactions.newTx();
const newTxn = harmony.transactions.newTx();
newTxn.recover(txns[i].rawTransaction);
expect(newTxn.txParams.from).toEqual(txns[i].senderAddress);
@ -36,63 +31,25 @@ describe('test Transaction using SDK', () => {
});
it('should test signTransaction', async () => {
const txnObject = {
to: woop.crypto.getAddress(receiver.Address).bech32,
to: harmony.crypto.getAddress(receiver.Address).bech32,
value: '0x64',
gasLimit: '210000',
gasPrice: new woop.utils.Unit('100').asGwei().toWei(),
gasPrice: new harmony.utils.Unit('100').asGwei().toWei(),
};
const txn = woop.transactions.newTx(txnObject);
signed = await woop.wallet.signTransaction(txn, undefined, undefined, false);
const txn = harmony.transactions.newTx(txnObject);
signed = await harmony.wallet.signTransaction(txn);
expect(signed.isSigned()).toEqual(true);
});
it('should send transaction', async () => {
fetch.mockResponseOnce(
JSON.stringify({
"jsonrpc": "2.0", "id": 1,
"result": "0x323A2B2C81d8948E5109FC32f9d0e4e6d178d14cC732C8E0a7Af74E81C7653eA"
}),
);
const [sentTxn, id] = await signed.sendTransaction();
expect(sentTxn.isPending()).toEqual(true);
expect(woop.utils.isHash(id)).toEqual(true);
expect(checkCalledMethod(0, RPCMethod.SendRawTransaction)).toEqual(true);
expect(harmony.utils.isHash(id)).toEqual(true);
txId = id;
sent = sentTxn;
});
it('should confirm a transaction', async () => {
fetch.mockResponses(
[
JSON.stringify({"jsonrpc": "2.0", "id": 1, "result": "0x1"}),
{ status: 200 },
],
[
JSON.stringify({"jsonrpc": "2.0", "id": 1, "result": "0x2"}),
{ status: 200 },
],
[
JSON.stringify({
"jsonrpc": "2.0",
"id": 1,
"result": {
"contractAddress": null,
"blockNumber": woop.utils.numberToHex(2),
"from": woop.wallet.accounts[0],
"gasUsed": woop.utils.numberToHex(5),
"cumulativeGasUsed": woop.utils.numberToHex(5),
"logs": [],
"logsBloom": woop.utils.numberToHex(5),
"shardID": 0,
"to": demoAccounts.Accounts[3].Address,
"transactionHash": "0x8c26EFdb6e4cAC6F8BeACE59F52fd95beD4Bfbfa8fF30F4a7cEd511fE5f869d9",
"transactionIndex": woop.utils.numberToHex(10),
"blockHash": "0xFECCCCBFd5AC71902BcfE65dDB0b88EEbbD15AD6cDAE7A9FAEb773bF827320fd",
}
}),
{status: 200},
]
)
const toConfirm = await sent.confirm(txId, 20, 1000);
expect(toConfirm.receipt !== undefined).toEqual(true);
expect(checkTransactionReceipt(toConfirm.receipt)).toEqual(true);
@ -101,19 +58,16 @@ describe('test Transaction using SDK', () => {
} else if (toConfirm.isRejected()) {
expect(toConfirm.txStatus).toEqual(TxStatus.REJECTED);
}
expect(checkCalledMethod(0, RPCMethod.BlockNumber)).toEqual(true);
expect(checkCalledMethod(1, RPCMethod.BlockNumber)).toEqual(true);
expect(checkCalledMethod(2, RPCMethod.GetTransactionReceipt)).toEqual(true);
});
it('should test transaction observed events', async () => {
const txnObject = {
to: woop.crypto.getAddress(receiver.Address).bech32,
value: new woop.utils.Unit('100').asGwei().toWei(),
gasLimit: new woop.utils.Unit('210000').asWei().toWei(),
gasPrice: new woop.utils.Unit('100').asGwei().toWei(),
to: harmony.crypto.getAddress(receiver.Address).bech32,
value: new harmony.utils.Unit('100').asGwei().toWei(),
gasLimit: new harmony.utils.Unit('210000').asWei().toWei(),
gasPrice: new harmony.utils.Unit('100').asGwei().toWei(),
};
const txn = woop.transactions.newTx(txnObject);
const txn = harmony.transactions.newTx(txnObject);
txn
.observed()
.on('transactionHash', (transactionHash) => {
@ -130,78 +84,35 @@ describe('test Transaction using SDK', () => {
.on('error', (error) => {
expect(error).toBeTruthy();
});
const txnSigned = await woop.wallet.signTransaction(txn, undefined, undefined, false);
fetch.mockResponseOnce(
JSON.stringify({
"jsonrpc": "2.0", "id": 1,
"result": "0x323A2B2C81d8948E5109FC32f9d0e4e6d178d14cC732C8E0a7Af74E81C7653eA"
}),
);
const txnSigned = await harmony.wallet.signTransaction(txn);
const [txnSent, id] = await txnSigned.sendTransaction();
expect(txnSent.txStatus).toEqual(TxStatus.PENDING);
expect(checkCalledMethod(0, RPCMethod.SendRawTransaction)).toEqual(true);
console.log('Here');
fetch.mockResponses(
[
JSON.stringify({"jsonrpc": "2.0", "id": 1, "result": "0x1"}),
{ status: 200 },
],
[
JSON.stringify({"jsonrpc": "2.0", "id": 1, "result": "0x2"}),
{ status: 200 },
],
[
JSON.stringify({
"jsonrpc": "2.0",
"id": 1,
"result": {
"contractAddress": null,
"blockNumber": woop.utils.numberToHex(2),
"from": woop.wallet.accounts[0],
"gasUsed": woop.utils.numberToHex(5),
"cumulativeGasUsed": woop.utils.numberToHex(5),
"logs": [],
"logsBloom": woop.utils.numberToHex(5),
"shardID": 0,
"to": demoAccounts.Accounts[3].Address,
"transactionHash": "0x8c26EFdb6e4cAC6F8BeACE59F52fd95beD4Bfbfa8fF30F4a7cEd511fE5f869d9",
"transactionIndex": woop.utils.numberToHex(10),
"blockHash": "0xFECCCCBFd5AC71902BcfE65dDB0b88EEbbD15AD6cDAE7A9FAEb773bF827320fd",
"status": "0x1",
}
}),
{status: 200},
]
);
await txnSigned.confirm(id);
expect(checkCalledMethod(1, RPCMethod.BlockNumber)).toEqual(true);
expect(checkCalledMethod(2, RPCMethod.BlockNumber)).toEqual(true);
expect(checkCalledMethod(3, RPCMethod.GetTransactionReceipt)).toEqual(true);
});
});
function checkTransactionReceipt(data: any) {
return woop.utils.validateArgs(
return harmony.utils.validateArgs(
data,
{
blockHash: [woop.utils.isHash],
blockNumber: [woop.utils.isHex],
blockHash: [harmony.utils.isHash],
blockNumber: [harmony.utils.isHex],
contractAddress: [
// tslint:disable-next-line: no-shadowed-variable
(data: any) => data === null || woop.utils.isValidAddress,
(data: any) => data === null || harmony.utils.isValidAddress,
],
cumulativeGasUsed: [woop.utils.isHex],
from: [woop.utils.isValidAddress],
gasUsed: [woop.utils.isHex],
logs: [woop.utils.isArray],
logsBloom: [woop.utils.isHex],
cumulativeGasUsed: [harmony.utils.isHex],
from: [harmony.utils.isValidAddress],
gasUsed: [harmony.utils.isHex],
logs: [harmony.utils.isArray],
logsBloom: [harmony.utils.isHex],
shardID: [woop.utils.isNumber],
shardID: [harmony.utils.isNumber],
// tslint:disable-next-line: no-shadowed-variable
to: [(data: any) => data === '0x' || woop.utils.isValidAddress],
transactionHash: [woop.utils.isHash],
transactionIndex: [woop.utils.isHex],
to: [(data: any) => data === '0x' || harmony.utils.isValidAddress],
transactionHash: [harmony.utils.isHash],
transactionIndex: [harmony.utils.isHex],
},
{ root: [woop.utils.isHash] },
{ root: [harmony.utils.isHash] },
);
}

@ -1,9 +1,7 @@
import fetch from 'jest-fetch-mock';
import { woop, checkCalledMethod } from './woop';
import { harmony } from './harmony';
import txnJsons from '../fixtures/transactions.json';
import { RPCMethod } from '@woop-js/network';
const messenger = woop.messenger;
const messenger = harmony.messenger;
interface TransactionInfo {
blockHash: string;
@ -12,53 +10,23 @@ interface TransactionInfo {
}
describe('e2e test transactions by RPC Method', () => {
beforeEach(() => {
fetch.resetMocks();
});
const txnHashesFixtures: any = [];
const transactionInfoList: any = [];
const { transactions, hashes, blockHashes } = txnJsons;
// net_*
it('should test wiki_sendRawTransaction', async () => {
for(let index = 0; index < transactions.length; index++) {
fetch.mockResponseOnce(
JSON.stringify({"jsonrpc": "2.0", "id": 1, "result": hashes[index]}),
);
const sent = await messenger.send('wiki_sendRawTransaction', transactions[index].rawTransaction);
expect(woop.utils.isHash(sent.result)).toEqual(true);
it('should test hmy_sendRawTransaction', async () => {
const { transactions } = txnJsons;
for (const txn of transactions) {
const sent = await messenger.send('hmy_sendRawTransaction', txn.rawTransaction);
expect(harmony.utils.isHash(sent.result)).toEqual(true);
txnHashesFixtures.push(sent.result);
expect(checkCalledMethod(index, 'wiki_sendRawTransaction')).toEqual(true);
}
});
it('should test wiki_getTransactionByHash', async () => {
for(let index: number = 0; index < txnHashesFixtures.length; index++) {
const txnHash = txnHashesFixtures[index];
fetch.mockResponseOnce(
JSON.stringify({
"jsonrpc": "2.0",
"id": 1,
"result": {
"hash": hashes[index],
"blockHash": blockHashes[index],
"blockNumber": woop.utils.numberToHex(index),
"transactionIndex": woop.utils.numberToHex(index),
"from": transactions[index].senderAddress,
"gas": transactions[index].gasLimit,
"gasPrice": transactions[index].gasPrice,
"input": "0x",
"nonce": transactions[index].nonce,
"to": transactions[index].receiverAddressBech32,
"value": transactions[index].value,
"v": woop.utils.numberToHex(index),
"r": woop.utils.numberToHex(index),
"s": woop.utils.numberToHex(index),
}
})
);
const txnDetail = await woop.blockchain.getTransactionByHash({
txnHash
it('should test hmy_getTransactionByHash', async () => {
for (const txnHash of txnHashesFixtures) {
const txnDetail = await harmony.blockchain.getTransactionByHash({
txnHash,
});
expect(checkCalledMethod(index, RPCMethod.GetTransactionByHash)).toEqual(true);
if (txnDetail.result !== null) {
expect(checkTransactionDetail(txnDetail.result)).toEqual(true);
expect(txnDetail.result.hash).toEqual(txnHash);
@ -69,194 +37,84 @@ describe('e2e test transactions by RPC Method', () => {
index: txnDetail.result.transactionIndex,
};
transactionInfoList.push(transactionInfo);
} else {
fail(`txnDetail for ${txnHash} is null`);
}
}
});
it('should test wiki_getTransactionByBlockHashAndIndex', async () => {
for (let index: number = 0; index < transactionInfoList.length; index++) {
fetch.mockResponseOnce((req) => {
if (!(Buffer.isBuffer(req.body))) {
fail("POST request body not a buffer");
}
const body: any = JSON.parse(req.body.toString());
// validate that the block hash is as expected
if (body.params[0] !== blockHashes[index]) {
fail(`Expected block hash ${blockHashes[index]} but got ${body.params[0]}`);
}
// validate that the transaction index is as expected
let expectedTransactionIndex: string = woop.utils.numberToHex(index);
if (expectedTransactionIndex !== body.params[1]) {
fail(`Expected transactionIndex ${expectedTransactionIndex} but got ${body.params[1]}`);
}
return Promise.resolve(JSON.stringify({
"jsonrpc": "2.0",
"id": 1,
"result": {
"hash": hashes[index],
"blockHash": blockHashes[index],
"blockNumber": woop.utils.numberToHex(index),
"transactionIndex": woop.utils.numberToHex(index),
"from": transactions[index].senderAddress,
"gas": transactions[index].gasLimit,
"gasPrice": transactions[index].gasPrice,
"input": "0x",
"nonce": transactions[index].nonce,
"to": transactions[index].receiverAddressBech32,
"value": transactions[index].value,
"v": woop.utils.numberToHex(index),
"r": woop.utils.numberToHex(index),
"s": woop.utils.numberToHex(index),
}
}));
});
const transactionInfo: TransactionInfo = transactionInfoList[index];
const txnDetail: any = await woop.blockchain.getTransactionByBlockHashAndIndex({
it('should test hmy_getTransactionByBlockHashAndIndex', async () => {
for (const some of transactionInfoList) {
const transactionInfo: TransactionInfo = some;
const txnDetail: any = await harmony.blockchain.getTransactionByBlockHashAndIndex({
blockHash: transactionInfo.blockHash,
index: transactionInfo.index,
});
expect(checkCalledMethod(index, RPCMethod.GetTransactionByBlockHashAndIndex)).toEqual(true);
if (txnDetail.result !== null) {
expect(checkTransactionDetail(txnDetail.result)).toEqual(true);
expect(txnDetail.result.blockHash).toEqual(transactionInfo.blockHash);
expect(txnDetail.result.transactionIndex).toEqual(transactionInfo.index);
} else {
fail(`txnDetail for ${transactionInfo.blockHash}_${transactionInfo.index} is null`);
}
}
});
it('should test wiki_getTransactionByBlockNumberAndIndex', async () => {
for (let index: number = 0; index < transactionInfoList.length; index++) {
fetch.mockResponseOnce((req) => {
if (!(Buffer.isBuffer(req.body))) {
fail("POST request body not a buffer");
}
const body: any = JSON.parse(req.body.toString());
// validate that the block number is as expected
let expectedBlockNumber: string = woop.utils.numberToHex(index);
if (body.params[0] !== expectedBlockNumber) {
fail(`Expected block number ${index} but got ${body.params[0]}`);
}
// validate that the transaction index is as expected
let expectedTransactionIndex: string = woop.utils.numberToHex(index);
if (expectedTransactionIndex !== body.params[1]) {
fail(`Expected transactionIndex ${expectedTransactionIndex} but got ${body.params[1]}`);
}
return Promise.resolve(JSON.stringify({
"jsonrpc": "2.0",
"id": 1,
"result": {
"hash": hashes[index],
"blockHash": blockHashes[index],
"blockNumber": woop.utils.numberToHex(index),
"transactionIndex": woop.utils.numberToHex(index),
"from": transactions[index].senderAddress,
"gas": transactions[index].gasLimit,
"gasPrice": transactions[index].gasPrice,
"input": "0x",
"nonce": transactions[index].nonce,
"to": transactions[index].receiverAddressBech32,
"value": transactions[index].value,
"v": woop.utils.numberToHex(index),
"r": woop.utils.numberToHex(index),
"s": woop.utils.numberToHex(index),
}
}));
});
const transactionInfo: TransactionInfo = transactionInfoList[index];
const txnDetail: any = await woop.blockchain.getTransactionByBlockNumberAndIndex({
it('should test hmy_getTransactionByBlockNumberAndIndex', async () => {
for (const some of transactionInfoList) {
const transactionInfo: TransactionInfo = some;
const txnDetail: any = await harmony.blockchain.getTransactionByBlockNumberAndIndex({
blockNumber: transactionInfo.blockNumber,
index: transactionInfo.index,
});
expect(checkCalledMethod(index, RPCMethod.GetTransactionByBlockNumberAndIndex)).toEqual(true);
if (txnDetail.result !== null) {
expect(checkTransactionDetail(txnDetail.result)).toEqual(true);
expect(txnDetail.result.blockNumber).toEqual(transactionInfo.blockNumber);
expect(txnDetail.result.transactionIndex).toEqual(transactionInfo.index);
} else {
fail(`txnDetail for ${transactionInfo.blockNumber}_${transactionInfo.index} is null`);
}
}
});
it('should test wiki_getTransactionCountByHash', async () => {
it('should test hmy_getTransactionCountByHash', async () => {
for (const some of transactionInfoList) {
fetch.mockResponseOnce(
JSON.stringify({"jsonrpc": "2.0", "id": 1, "result": "0x1"}),
);
const transactionInfo: TransactionInfo = some;
const txnCount: any = await woop.blockchain.getBlockTransactionCountByHash({
const txnCount: any = await harmony.blockchain.getBlockTransactionCountByHash({
blockHash: transactionInfo.blockHash,
});
expect(checkCalledMethod(0, RPCMethod.GetBlockTransactionCountByHash)).toEqual(true);
expect(woop.utils.isHex(txnCount.result)).toEqual(true);
expect(harmony.utils.isHex(txnCount.result)).toEqual(true);
}
});
it('should test wiki_getTransactionCountByNumber', async () => {
it('should test hmy_getTransactionCountByNumber', async () => {
for (const some of transactionInfoList) {
fetch.mockResponseOnce(
JSON.stringify({"jsonrpc": "2.0", "id": 1, "result": "0x1"}),
);
const transactionInfo: TransactionInfo = some;
const txnCount: any = await woop.blockchain.getBlockTransactionCountByNumber({
const txnCount: any = await harmony.blockchain.getBlockTransactionCountByNumber({
blockNumber: transactionInfo.blockNumber,
});
expect(checkCalledMethod(0, RPCMethod.GetBlockTransactionCountByNumber)).toEqual(true);
expect(woop.utils.isHex(txnCount.result)).toEqual(true);
expect(harmony.utils.isHex(txnCount.result)).toEqual(true);
}
});
it('should test wiki_getTransactionReceipt', async () => {
it('should test hmy_getTransactionReceipt', async () => {
const { transactions } = txnJsons;
// tslint:disable-next-line: prefer-for-of
for (let index = 0; index < txnHashesFixtures.length; index += 1) {
const txnHash = txnHashesFixtures[index];
fetch.mockResponseOnce(
JSON.stringify({
"jsonrpc": "2.0",
"id": 1,
"result": {
"contractAddress": null,
"blockNumber": woop.utils.numberToHex(index),
"from": transactions[index].senderAddress,
"gasUsed": woop.utils.numberToHex(index),
"cumulativeGasUsed": woop.utils.numberToHex(index),
"logs": [],
"logsBloom": woop.utils.numberToHex(index),
"shardID": 0,
"to": transactions[index].receiverAddress,
"transactionHash": hashes[index],
"transactionIndex": woop.utils.numberToHex(index),
"blockHash": blockHashes[index]
}
})
);
const receipt: any = await woop.blockchain.getTransactionReceipt({
for (let i = 0; i < txnHashesFixtures.length; i += 1) {
const txnHash = txnHashesFixtures[i];
const receipt: any = await harmony.blockchain.getTransactionReceipt({
txnHash,
});
expect(checkCalledMethod(index, RPCMethod.GetTransactionReceipt)).toEqual(true);
if (receipt.result !== null) {
expect(checkTransactionReceipt(receipt.result)).toEqual(true);
expect(woop.crypto.getAddress(receipt.result.from).checksum).toEqual(
transactions[index].senderAddress,
expect(harmony.crypto.getAddress(receipt.result.from).checksum).toEqual(
transactions[i].senderAddress,
);
expect(woop.crypto.getAddress(receipt.result.to).checksum).toEqual(
transactions[index].receiverAddress,
expect(harmony.crypto.getAddress(receipt.result.to).checksum).toEqual(
transactions[i].receiverAddress,
);
expect(receipt.result.blockHash).toEqual(transactionInfoList[index].blockHash);
expect(receipt.result.blockNumber).toEqual(transactionInfoList[index].blockNumber);
expect(receipt.result.transactionIndex).toEqual(transactionInfoList[index].index);
} else {
fail(`receipt for ${txnHash} is null`);
expect(receipt.result.blockHash).toEqual(transactionInfoList[i].blockHash);
expect(receipt.result.blockNumber).toEqual(transactionInfoList[i].blockNumber);
expect(receipt.result.transactionIndex).toEqual(transactionInfoList[i].index);
}
}
});
it('should test wiki_getTransactionCount', async () => {
it('should test hmy_getTransactionCount', async () => {
const { transactions } = txnJsons;
for (let i = 0; i < transactionInfoList; i += 1) {
fetch.mockResponseOnce(
JSON.stringify({"jsonrpc": "2.0", "id": 1, "result": "0x1"}),
);
const transactionInfo: TransactionInfo = transactionInfoList[i];
const nonce: any = await woop.blockchain.getTransactionCount({
const nonce: any = await harmony.blockchain.getTransactionCount({
address: transactions[i].senderAddressBech32,
blockNumber: transactionInfo.blockNumber,
});
@ -266,52 +124,52 @@ describe('e2e test transactions by RPC Method', () => {
});
function checkTransactionDetail(data: any) {
return woop.utils.validateArgs(
return harmony.utils.validateArgs(
data,
{
blockHash: [woop.utils.isHash],
blockNumber: [woop.utils.isHex],
blockHash: [harmony.utils.isHash],
blockNumber: [harmony.utils.isHex],
// tslint:disable-next-line: no-shadowed-variable
from: [woop.utils.isValidAddress],
gas: [woop.utils.isHex],
gasPrice: [woop.utils.isHex],
hash: [woop.utils.isHash],
from: [harmony.utils.isValidAddress],
gas: [harmony.utils.isHex],
gasPrice: [harmony.utils.isHex],
hash: [harmony.utils.isHash],
// tslint:disable-next-line: no-shadowed-variable
input: [(data: any) => data === '0x' || woop.utils.isHex(data)],
nonce: [woop.utils.isHex],
input: [(data: any) => data === '0x' || harmony.utils.isHex(data)],
nonce: [harmony.utils.isHex],
// tslint:disable-next-line: no-shadowed-variable
to: [(data: any) => data === '0x' || woop.utils.isValidAddress(data)],
transactionIndex: [woop.utils.isHex],
value: [woop.utils.isHex],
v: [woop.utils.isHex],
r: [woop.utils.isHex],
s: [woop.utils.isHex],
to: [(data: any) => data === '0x' || harmony.utils.isValidAddress(data)],
transactionIndex: [harmony.utils.isHex],
value: [harmony.utils.isHex],
v: [harmony.utils.isHex],
r: [harmony.utils.isHex],
s: [harmony.utils.isHex],
},
{},
);
}
function checkTransactionReceipt(data: any) {
return woop.utils.validateArgs(
return harmony.utils.validateArgs(
data,
{
blockNumber: [woop.utils.isHex],
blockNumber: [harmony.utils.isHex],
contractAddress: [
// tslint:disable-next-line: no-shadowed-variable
(data: any) => data === null || woop.utils.isValidAddress,
(data: any) => data === null || harmony.utils.isValidAddress,
],
cumulativeGasUsed: [woop.utils.isHex],
from: [woop.utils.isValidAddress],
gasUsed: [woop.utils.isHex],
logs: [woop.utils.isArray],
logsBloom: [woop.utils.isHex],
cumulativeGasUsed: [harmony.utils.isHex],
from: [harmony.utils.isValidAddress],
gasUsed: [harmony.utils.isHex],
logs: [harmony.utils.isArray],
logsBloom: [harmony.utils.isHex],
shardID: [woop.utils.isNumber],
shardID: [harmony.utils.isNumber],
// tslint:disable-next-line: no-shadowed-variable
to: [(data: any) => data === '0x' || woop.utils.isValidAddress],
transactionHash: [woop.utils.isHash],
transactionIndex: [woop.utils.isHex],
to: [(data: any) => data === '0x' || harmony.utils.isValidAddress],
transactionHash: [harmony.utils.isHash],
transactionIndex: [harmony.utils.isHex],
},
{ blockHash: [woop.utils.isHash], root: [woop.utils.isHash] },
{ blockHash: [harmony.utils.isHash], root: [harmony.utils.isHash] },
);
}

@ -1,39 +0,0 @@
import fetch from 'jest-fetch-mock';
// tslint:disable-next-line: no-implicit-dependencies
import { Woop } from '@woop-js/core';
// tslint:disable-next-line: no-implicit-dependencies
import { ChainType } from '@woop-js/utils';
// tslint:disable-next-line: no-implicit-dependencies
import { Account } from '@woop-js/account';
const CHAIN_ID: number = 2;
const CHAIN_TYPE: string = 'wiki';
const HTTP_PROVIDER: string = 'http://localhost:9500';
const GENESIS_PRIV_KEY: string = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e';
let chainType: ChainType = ChainType.Woop;
if (CHAIN_TYPE === 'wiki') {
chainType = ChainType.Woop;
} else if (CHAIN_TYPE === 'eth') {
chainType = ChainType.Ethereum;
}
export const woop: Woop = new Woop(HTTP_PROVIDER, {
chainId: CHAIN_ID,
chainType,
chainUrl: HTTP_PROVIDER,
});
export const myAccount: Account = woop.wallet.addByPrivateKey(
GENESIS_PRIV_KEY,
);
export function checkCalledMethod(i: number, s: string) {
let params: (string | undefined) = fetch.mock.calls[i][1]?.body?.toString();
if (params) {
let method: string = JSON.parse(params).method;
return method === s;
}
return false;
}

@ -3,17 +3,15 @@
"compilerOptions": {
"outDir": "dist",
"rootDir": "src",
"declarationDir": "dist",
"resolveJsonModule": true,
"esModuleInterop": true
"declarationDir": "dist"
},
"include": ["src", "../typings/**/*.d.ts", "fixtures"],
"references": [
{ "path": "../packages/woop-account" },
{ "path": "../packages/woop-crypto" },
{ "path": "../packages/woop-utils" },
{ "path": "../packages/woop-network" },
{ "path": "../packages/woop-transaction" },
{ "path": "../packages/woop-contract" }
{ "path": "../packages/harmony-account" },
{ "path": "../packages/harmony-crypto" },
{ "path": "../packages/harmony-utils" },
{ "path": "../packages/harmony-network" },
{ "path": "../packages/harmony-transaction" },
{ "path": "../packages/harmony-contract" }
]
}

@ -0,0 +1,134 @@
# Quick start
1. You need Harmony local testnet running.
instruction here:[harmony-one/harmony](https://github.com/harmony-one/harmony)
2. Run this example under nodejs enviorment.
```javascript
// import or require Harmony class
const { Harmony } = require('@harmony-js/core');
// import or require settings
const { ChainID, ChainType } = require('@harmony-js/utils');
// 1. initialize the Harmony instance
const harmony = new Harmony(
// rpc url
'http://localhost:9500',
{
// chainType set to Harmony
chainType: ChainType.Harmony,
// chainType set to HmyLocal
chainId: ChainID.HmyLocal,
},
);
// 2. get wallet ready
// specify the privateKey
const privateKey = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e';
// add privateKey to wallet
const sender = harmony.wallet.addByPrivateKey(privateKey);
// 3. get sharding info
async function setSharding() {
// Harmony is a sharded blockchain, each endpoint have sharding structure,
// However sharding structure is different between mainnet, testnet and local testnet
// We need to get sharding info before doing cross-shard transaction
const res = await harmony.blockchain.getShardingStructure();
harmony.shardingStructures(res.result);
}
// 4. get transaction payload ready
async function transfer() {
// run set sharding first, if you want to make a cross-shard transaction
await setSharding();
const txn = harmony.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 harmony.utils.Unit('100').asGwei().toWei(),
});
// sign the transaction use wallet;
const signedTxn = await harmony.wallet.signTransaction(txn);
// Now you can use `Transaction.observed()` to listen events
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('');
});
// send the txn, get [Transaction, transactionHash] as result
const [sentTxn, txnHash] = await signedTxn.sendTransaction();
// to confirm the result if it is already there
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('');
process.exit();
}
}
if (confiremdTxn.isConfirmed() && confiremdTxn.isCxConfirmed()) {
console.log('--- Result ---');
console.log('');
console.log('Cross-Shard transaction');
console.log(`${txnHash} is confirmed`);
console.log('');
process.exit();
}
}
transfer();
```
# More examples
* [dapp-examples](https://github.com/harmony-one/dapp-examples)

@ -0,0 +1,31 @@
const { Harmony } = require('@harmony-js/core');
// import or require settings
const { ChainID, ChainType } = require('@harmony-js/utils');
const URL_TESTNET = `https://api.s0.b.hmny.io`;
const URL_MAINNET = `https://api.s0.t.hmny.io`;
// 1. initialize the Harmony instance
const harmony = new Harmony(
// rpc url
URL_TESTNET,
{
// chainType set to Harmony
chainType: ChainType.Harmony,
// chainType set to HmyLocal
chainId: ChainID.HmyTestnet,
},
);
harmony.blockchain
.getBalance({
address: `one1vjywuur8ckddmc4dsyx6qdgf590eu07ag9fg4a`,
})
.then((res) => {
console.log(new harmony.utils.Unit(res.result).asWei().toEther());
})
.catch((err) => {
console.log(err);
});

@ -0,0 +1,45 @@
// import the Account class
const { Account } = require('@harmony-js/account');
// suppose we have an account
const myPrivateKey = '0x831f0b3ff835d5ec4602878742fda25591b6d3bb2731366621ac83a05216bec8';
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":"38326265-6165-4961-a338-353063643962","address":"1cc87010760602a576455d6d2f03a3bf92d2c2ca","crypto":{"ciphertext":"a4ee9120b27ba66fb9d3fabd6372fa3a11060cf439a6a1777ced1e6253de8c29","cipherparams":{"iv":"c18772a882ac461fffd1971e9ec57861"},"cipher":"aes-128-ctr","kdf":"scrypt","kdfparams":{"salt":"da4efedeca407279be65e02fc94b7c4b7c74c3396447c71e659c74a73a5d9131","n":8192,"r":8,"p":1,"dklen":32},"mac":"547ee6616dcdf424273c113ceb00728ccdda17ff6449f2cb84a1a8352c87b4e6"}}';
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);

@ -0,0 +1,14 @@
{
"name": "example",
"version": "1.0.0",
"description": "",
"main": "test.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"@harmony-js/core": "^0.1.41"
}
}

@ -0,0 +1,79 @@
const { Harmony } = require('@harmony-js/core');
const { ChainID, ChainType } = require('@harmony-js/utils');
const {
StakingTransaction,
CreateValidator,
Delegate,
Undelegate,
CollectRewards,
StakingFactory,
} = require('@harmony-js/staking');
const harmony = new Harmony('http://localhost:9500', {
chainId: ChainID.HmyLocal,
chainType: ChainType.Harmony,
});
const stakingTxn = harmony.stakings
.createValidator({
validatorAddress: 'one1a0x3d6xpmr6f8wsyaxd9v36pytvp48zckswvv9',
description: {
name: 'Alice',
identity: 'alice',
website: 'alice.harmony.one',
securityContact: 'Bob',
details: "Don't mess with me!!!",
},
commissionRate: {
rate: '0.1',
maxRate: '0.9',
maxChangeRate: '0.05',
},
minSelfDelegation: '0xa',
maxTotalDelegation: '0x0bb8',
slotPubKeys: [
'0xb9486167ab9087ab818dc4ce026edb5bf216863364c32e42df2af03c5ced1ad181e7d12f0e6dd5307a73b62247608611',
],
amount: '0x64',
})
.setTxParams({
nonce: '0x2',
gasPrice: '0x',
gasLimit: '0x64',
chainId: 0,
})
.build();
stakingTxn
.sendTransaction()
.then(([stakingTxn, res]) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
// const delegateMsg = Delegate({
// delegatorAddress: 'one1a0x3d6xpmr6f8wsyaxd9v36pytvp48zckswvv9',
// validatorAddress: 'one1a0x3d6xpmr6f8wsyaxd9v36pytvp48zckswvv9',
// amount: '0xa',
// });
// const stakingTxn = StakingTransaction({
// directive: '0x2',
// stakeMsg: delegateMsg,
// nonce: '0x2',
// gasPrice: '0x',
// gasLimit: '0x64',
// chainId: 0,
// from: 'one1a0x3d6xpmr6f8wsyaxd9v36pytvp48zckswvv9',
// });
// stakingTxn
// .sendTransaction()
// .then((stakingTxn, res) => {
// console.log(res);
// })
// .catch((err) => {
// console.log(err);
// });

@ -0,0 +1,172 @@
const { Harmony } = require('@harmony-js/core');
const { ChainID, ChainType } = require('@harmony-js/utils');
const { Delegate, StakingTransaction, StakingFactory } = require('@harmony-js/staking'); //../packages/harmony-staking
const { TxStatus } = require('@harmony-js/transaction');
const LOCALNET = `http://localhost:9500`;
// 1. initialize the Harmony instance
const harmony = new Harmony(
// rpc url
LOCALNET,
{
// chainType set to Harmony
chainType: ChainType.Harmony,
// chainType set to HmyLocal
chainId: ChainID.HmyLocal,
},
);
// 2. get wallet ready
// one1a2rhuaqjcvfu69met9sque2l3w5v9z6qcdcz65
// surge welcome lion goose gate consider taste injury health march debris kick
// add privateKey to wallet
const private = '63e35b761e9df0d50ddcdaa8e33c235b60c991bfed22925a12768b0c08ef822f';
// one1pdv9lrdwl0rg5vglh4xtyrv3wjk3wsqket7zxy
const sender = harmony.wallet.addByPrivateKey(private);
console.log(sender.address);
// const phrase =
// 'genius cable radar memory high catch blossom correct middle wish gentle
// fiscal';
// one1a2rhuaqjcvfu69met9sque2l3w5v9z6qcdcz65
// surge welcome lion goose gate consider taste injury health march debris kick
// add privateKey to wallet
// const sender = harmony.wallet.addByMnemonic(phrase);
// let r =
// '0xf8f180f8a4940b585f8daefbc68a311fbd4cb20d9174ad174016f83885416c69636585616c69636591616c6963652e6861726d6f6e792e6f6e6583426f6295446f6e2774206d6573732077697468206d65212121ddc988016345785d8a0000c9880c7d713b49da0000c887b1a2bc2ec500000a820bb8f1b0b9486167ab9087ab818dc4ce026edb5bf216863364c32e42df2af03c5ced1ad181e7d12f0e6dd5307a73b6224760861164008080830927c028a064b1b835f5b70a72228920db24e44c0a57d954c1d3dcac3b33c79d9593f96191a05577fd05064a37043a33ff7febb67ab126a8e1f0b67c92b7cab793a87ddf2c82';
// const delegateMsg = new Delegate(
// 'one1pf75h0t4am90z8uv3y0dgunfqp4lj8wr3t5rsp', // from delegate command.
// 'one1pdv9lrdwl0rg5vglh4xtyrv3wjk3wsqket7zxy', // fd416cb87dcf8ed187e85545d7734a192fc8e976f5b540e9e21e896ec2bc25c3
// '0xde0b6b3a7640000', // 0x56BC75E2D63100000
// );
// // one12fuf7x9rgtdgqg7vgq0962c556m3p7afsxgvll;
// const stakingTxn = new StakingTransaction(
// '0x2',
// delegateMsg,
// '0x2',
// '0x',
// '0x0927c0',
// ChainID.HmyLocal,
// );
const stakingTxn = harmony.stakings
.delegate({
delegatorAddress: 'one1pf75h0t4am90z8uv3y0dgunfqp4lj8wr3t5rsp',
validatorAddress: 'one1pdv9lrdwl0rg5vglh4xtyrv3wjk3wsqket7zxy',
amount: '0xde0b6b3a7640000',
})
.setTxParams({ nonce: '0x2', gasPrice: '0x', gasLimit: '0x0927c0', chainId: ChainID.HmyLocal })
.build();
// 3. get sharding info
async function setSharding() {
// Harmony is a sharded blockchain, each endpoint have sharding structure,
// However sharding structure is different between mainnet, testnet and local
// testnet We need to get sharding info before doing cross-shard transaction
const res = await harmony.blockchain.getShardingStructure();
harmony.shardingStructures(res.result);
}
async function execute() {
await setSharding();
const signedTxn = await harmony.wallet.signStaking(stakingTxn);
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('');
});
// console.log(signedTxn);
const [sentTxn, txnHash] = await signedTxn.sendTransaction();
// signedTxn.sendTransaction()
// .then(res => {
// console.log(res);
// })
// .catch(err => {
// console.log(err);
// });
// to confirm the result if it is already there
// console.log(txnHash);
console.log(sentTxn);
const confiremdTxn = await sentTxn.confirm(txnHash);
// if the transactino is cross-shard transaction
if (confiremdTxn.isConfirmed()) {
console.log('--- Result ---');
console.log('');
console.log('Normal transaction');
console.log(`${txnHash} is confirmed`);
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('');
// process.exit();
// }
}
execute();
// const delegateMsg = Delegate({
// delegatorAddress: 'one1a0x3d6xpmr6f8wsyaxd9v36pytvp48zckswvv9',
// validatorAddress: 'one1a0x3d6xpmr6f8wsyaxd9v36pytvp48zckswvv9',
// amount: '0xa',
// });
// const stakingTxn = StakingTransaction({
// directive: '0x2',
// stakeMsg: delegateMsg,
// nonce: '0x2',
// gasPrice: '0x',
// gasLimit: '0x64',
// chainId: 0,
// from: 'one1a0x3d6xpmr6f8wsyaxd9v36pytvp48zckswvv9',
// });
// stakingTxn
// .sendTransaction()
// .then((stakingTxn, res) => {
// console.log(res);
// })
// .catch((err) => {
// console.log(err);
// });

@ -0,0 +1,74 @@
const { Harmony } = require('@harmony-js/core');
const { ChainID, ChainType } = require('@harmony-js/utils');
const { StakingFactory } = require('@harmony-js/staking');
const harmony = new Harmony('http://localhost:9500', {
chainId: ChainID.HmyLocal,
chainType: ChainType.Harmony,
});
const createMsg = {
validatorAddress: 'one1a0x3d6xpmr6f8wsyaxd9v36pytvp48zckswvv9',
description: {
name: 'Alice',
identity: 'alice',
website: 'alice.harmony.one',
securityContact: 'Bob',
details: "Don't mess with me!!!",
},
commissionRate: {
rate: '0.1',
maxRate: '0.9',
maxChangeRate: '0.05',
},
minSelfDelegation: '0xa',
maxTotalDelegation: '0x0bb8',
slotPubKeys: [
'0xb9486167ab9087ab818dc4ce026edb5bf216863364c32e42df2af03c5ced1ad181e7d12f0e6dd5307a73b62247608611',
],
amount: '0x64',
};
const stakingTxn = harmony.stakings
.createValidator(createMsg)
.setTxParams({
nonce: '0x2',
gasPrice: '0x',
gasLimit: '0x64',
chainId: 0,
})
.build();
stakingTxn
.sendTransaction()
.then(([stakingTxn, res]) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
// const delegateMsg = Delegate({
// delegatorAddress: 'one1a0x3d6xpmr6f8wsyaxd9v36pytvp48zckswvv9',
// validatorAddress: 'one1a0x3d6xpmr6f8wsyaxd9v36pytvp48zckswvv9',
// amount: '0xa',
// });
// const stakingTxn = StakingTransaction({
// directive: '0x2',
// stakeMsg: delegateMsg,
// nonce: '0x2',
// gasPrice: '0x',
// gasLimit: '0x64',
// chainId: 0,
// from: 'one1a0x3d6xpmr6f8wsyaxd9v36pytvp48zckswvv9',
// });
// stakingTxn
// .sendTransaction()
// .then((stakingTxn, res) => {
// console.log(res);
// })
// .catch((err) => {
// console.log(err);
// });

@ -0,0 +1,177 @@
const { Harmony } = require('@harmony-js/core');
const { ChainID, ChainType } = require('@harmony-js/utils');
const {
Description,
Decimal,
CommissionRate,
StakingTransaction,
CreateValidator,
} = require('@harmony-js/staking'); //../packages/harmony-staking
const { TxStatus } = require('@harmony-js/transaction');
const LOCALNET = `http://localhost:9500`;
// 1. initialize the Harmony instance
const harmony = new Harmony(
// rpc url
LOCALNET,
{
// chainType set to Harmony
chainType: ChainType.Harmony,
// chainType set to HmyLocal
chainId: ChainID.HmyLocal,
},
);
// 2. get wallet ready
// one1a2rhuaqjcvfu69met9sque2l3w5v9z6qcdcz65
// surge welcome lion goose gate consider taste injury health march debris kick
// add privateKey to wallet
const private = 'fd416cb87dcf8ed187e85545d7734a192fc8e976f5b540e9e21e896ec2bc25c3';
const sender = harmony.wallet.addByPrivateKey(private);
// const phrase =
// 'genius cable radar memory high catch blossom correct middle wish gentle
// fiscal';
// one1a2rhuaqjcvfu69met9sque2l3w5v9z6qcdcz65
// surge welcome lion goose gate consider taste injury health march debris kick
// add privateKey to wallet
// const sender = harmony.wallet.addByMnemonic(phrase);
const stakingTxn = harmony.stakings
.createValidator({
validatorAddress: 'one1pdv9lrdwl0rg5vglh4xtyrv3wjk3wsqket7zxy',
description: {
name: 'Alice',
identity: 'alice',
website: 'alice.harmony.one',
securityContact: 'Bob',
details: "Don't mess with me!!",
},
commissionRate: { rate: '0.1', maxRate: '0.9', maxChangeRate: '0.05' },
minSelfDelegation: '0x8AC7230489E80000',
maxTotalDelegation: '0xA2A15D09519BE00000',
slotPubKeys: [
'0xb9486167ab9087ab818dc4ce026edb5bf216863364c32e42df2af03c5ced1ad181e7d12f0e6dd5307a73b62247608611',
],
amount: '0x56BC75E2D63100000',
})
.setTxParams({
nonce: '0x2',
gasPrice: '0x',
gasLimit: '0x0927c0',
chainId: ChainID.HmyLocal,
})
.build();
// 3. get sharding info
async function setSharding() {
// Harmony is a sharded blockchain, each endpoint have sharding structure,
// However sharding structure is different between mainnet, testnet and local
// testnet We need to get sharding info before doing cross-shard transaction
const res = await harmony.blockchain.getShardingStructure();
harmony.shardingStructures(res.result);
}
async function execute() {
await setSharding();
const signedTxn = await harmony.wallet.signStaking(stakingTxn);
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('');
});
// console.log(signedTxn);
const [sentTxn, txnHash] = await signedTxn.sendTransaction();
// signedTxn
// .sendTransaction()
// .then((res) => {
// console.log(res);
// })
// .catch((err) => {
// console.log(err);
// });
// to confirm the result if it is already there
console.log(txnHash);
console.log(sentTxn);
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('Staking transaction');
console.log(`${txnHash} is confirmed`);
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('');
// process.exit();
// }
}
execute();
// const delegateMsg = Delegate({
// delegatorAddress: 'one1a0x3d6xpmr6f8wsyaxd9v36pytvp48zckswvv9',
// validatorAddress: 'one1a0x3d6xpmr6f8wsyaxd9v36pytvp48zckswvv9',
// amount: '0xa',
// });
// const stakingTxn = StakingTransaction({
// directive: '0x2',
// stakeMsg: delegateMsg,
// nonce: '0x2',
// gasPrice: '0x',
// gasLimit: '0x64',
// chainId: 0,
// from: 'one1a0x3d6xpmr6f8wsyaxd9v36pytvp48zckswvv9',
// });
// stakingTxn
// .sendTransaction()
// .then((stakingTxn, res) => {
// console.log(res);
// })
// .catch((err) => {
// console.log(err);
// });

@ -0,0 +1,173 @@
const { Harmony } = require('@harmony-js/core');
const { ChainID, ChainType } = require('@harmony-js/utils');
const { Undelegate, StakingTransaction, StakingFactory } = require('@harmony-js/staking'); //../packages/harmony-staking
const { TxStatus } = require('@harmony-js/transaction');
const LOCALNET = `http://localhost:9500`;
// 1. initialize the Harmony instance
const harmony = new Harmony(
// rpc url
LOCALNET,
{
// chainType set to Harmony
chainType: ChainType.Harmony,
// chainType set to HmyLocal
chainId: ChainID.HmyLocal,
},
);
// 2. get wallet ready
// one1a2rhuaqjcvfu69met9sque2l3w5v9z6qcdcz65
// surge welcome lion goose gate consider taste injury health march debris kick
// add privateKey to wallet
const private = '63e35b761e9df0d50ddcdaa8e33c235b60c991bfed22925a12768b0c08ef822f';
const sender = harmony.wallet.addByPrivateKey(private);
// const phrase =
// 'genius cable radar memory high catch blossom correct middle wish gentle
// fiscal';
// one1a2rhuaqjcvfu69met9sque2l3w5v9z6qcdcz65
// surge welcome lion goose gate consider taste injury health march debris kick
// add privateKey to wallet
// const sender = harmony.wallet.addByMnemonic(phrase);
// let r =
// '0xf8f180f8a4940b585f8daefbc68a311fbd4cb20d9174ad174016f83885416c69636585616c69636591616c6963652e6861726d6f6e792e6f6e6583426f6295446f6e2774206d6573732077697468206d65212121ddc988016345785d8a0000c9880c7d713b49da0000c887b1a2bc2ec500000a820bb8f1b0b9486167ab9087ab818dc4ce026edb5bf216863364c32e42df2af03c5ced1ad181e7d12f0e6dd5307a73b6224760861164008080830927c028a064b1b835f5b70a72228920db24e44c0a57d954c1d3dcac3b33c79d9593f96191a05577fd05064a37043a33ff7febb67ab126a8e1f0b67c92b7cab793a87ddf2c82';
// const undelegateMsg = new Undelegate(
// 'one1pf75h0t4am90z8uv3y0dgunfqp4lj8wr3t5rsp', // signed should match this
// 'one1pdv9lrdwl0rg5vglh4xtyrv3wjk3wsqket7zxy',
// '0x16345785d8a0000',
// );
// const stakingTxn = new StakingTransaction(
// '0x3',
// undelegateMsg,
// '0x2',
// '0x',
// '0x0927c0',
// ChainID.HmyLocal,
// );
const stakingTxn = harmony.stakings
.undelegate({
delegatorAddress: 'one1pf75h0t4am90z8uv3y0dgunfqp4lj8wr3t5rsp',
validatorAddress: 'one1pdv9lrdwl0rg5vglh4xtyrv3wjk3wsqket7zxy',
amount: '0x16345785d8a0000',
})
.setTxParams({
nonce: '0x2',
gasPrice: '0x',
gasLimit: '0x0927c0',
chainId: ChainID.HmyLocal,
})
.build();
// 3. get sharding info
async function setSharding() {
// Harmony is a sharded blockchain, each endpoint have sharding structure,
// However sharding structure is different between mainnet, testnet and local
// testnet We need to get sharding info before doing cross-shard transaction
const res = await harmony.blockchain.getShardingStructure();
harmony.shardingStructures(res.result);
}
async function execute() {
await setSharding();
const signedTxn = await harmony.wallet.signStaking(stakingTxn);
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('');
});
// console.log(signedTxn);
const [sentTxn, txnHash] = await signedTxn.sendTransaction();
// signedTxn.sendTransaction()
// .then(res => {
// console.log(res);
// })
// .catch(err => {
// console.log(err);
// });
// to confirm the result if it is already there
// console.log(txnHash);
console.log(sentTxn);
const confiremdTxn = await sentTxn.confirm(txnHash);
// if the transactino is cross-shard transaction
if (confiremdTxn.isConfirmed()) {
console.log('--- Result ---');
console.log('');
console.log('Normal transaction');
console.log(`${txnHash} is confirmed`);
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('');
// process.exit();
// }
}
execute();
// const delegateMsg = Delegate({
// delegatorAddress: 'one1a0x3d6xpmr6f8wsyaxd9v36pytvp48zckswvv9',
// validatorAddress: 'one1a0x3d6xpmr6f8wsyaxd9v36pytvp48zckswvv9',
// amount: '0xa',
// });
// const stakingTxn = StakingTransaction({
// directive: '0x2',
// stakeMsg: delegateMsg,
// nonce: '0x2',
// gasPrice: '0x',
// gasLimit: '0x64',
// chainId: 0,
// from: 'one1a0x3d6xpmr6f8wsyaxd9v36pytvp48zckswvv9',
// });
// stakingTxn
// .sendTransaction()
// .then((stakingTxn, res) => {
// console.log(res);
// })
// .catch((err) => {
// console.log(err);
// });

@ -0,0 +1,31 @@
const { Harmony } = require('@harmony-js/core');
const { ChainID, ChainType } = require('@harmony-js/utils');
const { encryptPhrase, decryptPhrase } = require('@harmony-js/crypto');
const harmony = new Harmony('http://localhost:9500', { chainId: 2, chainType: 'hmy' });
const myPhrase = harmony.wallet.newMnemonic();
const pwd = '1234';
async function encryptThePhrase(phrase, pass) {
const result = await encryptPhrase(phrase, pass);
return result;
}
async function decryptThePhrase(keystore, pass) {
const result = await decryptPhrase(keystore, pass);
return result;
}
async function phraseKeyStore() {
const keyStore = await encryptThePhrase(myPhrase, pwd);
const recoveredPhrase = await decryptThePhrase(JSON.parse(keyStore), pwd);
return { myPhrase, keyStore, recoveredPhrase };
}
phraseKeyStore().then((result) => {
const { myPhrase, keyStore, recoveredPhrase } = result;
harmony.wallet.addByMnemonic(myPhrase);
console.log({ myPhrase, keyStore, recoveredPhrase });
console.log(harmony.wallet);
});

@ -0,0 +1,40 @@
const { Harmony } = require('@harmony-js/core');
const { ChainID, ChainType } = require('@harmony-js/utils');
const {
randomBytes,
generatePrivateKey,
getAddress,
getAddressFromPrivateKey,
encryptPhrase,
decryptPhrase,
} = require('@harmony-js/crypto');
const harmony = new Harmony('http://localhost:9500', { chainId: 2, chainType: 'hmy' });
const myPhrase = harmony.wallet.newMnemonic();
const pwd = '1234';
async function encryptThePhrase(phrase, pass) {
const result = await encryptPhrase(phrase, pass);
return result;
}
async function decryptThePhrase(keystore, pass) {
const result = await decryptPhrase(keystore, pass);
return result;
}
async function phraseKeyStore() {
const keyStore = await encryptThePhrase(myPhrase, pwd);
const recoveredPhrase = await decryptThePhrase(JSON.parse(keyStore), pwd);
return { myPhrase, keyStore, recoveredPhrase };
}
phraseKeyStore().then((result) => {
const { myPhrase, keyStore, recoveredPhrase } = result;
const anotherPhrase = 'wall public vague under poem acid jaguar describe net scene sponsor neck';
harmony.wallet.addByMnemonic(myPhrase);
harmony.wallet.addByMnemonic(anotherPhrase);
console.log({ myPhrase, keyStore, recoveredPhrase });
console.log(harmony.wallet);
});

@ -0,0 +1,153 @@
// import or require Harmony class
const { Harmony } = require('@harmony-js/core');
// import or require settings
const { ChainID, ChainType } = require('@harmony-js/utils');
const URL_TESTNET = `https://api.s0.b.hmny.io`;
const URL_MAINNET = `https://api.s0.t.hmny.io`;
const URL_PANGAEA = 'https://api.s0.pga.hmny.io';
// 1. initialize the Harmony instance
const harmony = new Harmony(
// rpc url
URL_PANGAEA,
{
// chainType set to Harmony
chainType: ChainType.Harmony,
// chainType set to HmyLocal
chainId: ChainID.HmyPangaea,
},
);
// 2. get wallet ready
// one18n8e7472pg5fqvcfcr5hg0npquha24wsxmjheg
const phrase = 'genius cable radar memory high catch blossom correct middle wish gentle fiscal';
// const phrase =
// 'resemble rent deposit unique garment ripple burst negative else decorate menu theme';
// one1a2rhuaqjcvfu69met9sque2l3w5v9z6qcdcz65
// surge welcome lion goose gate consider taste injury health march debris kick
// add privateKey to wallet
const privateKey = '63e35b761e9df0d50ddcdaa8e33c235b60c991bfed22925a12768b0c08ef822f';
const sender = harmony.wallet.addByMnemonic(phrase);
const sender2 = harmony.wallet.addByPrivateKey(privateKey);
harmony.wallet.setSigner(sender2.address);
console.log('sender2Address is : ', sender2.bech32Address);
// 3. get sharding info
async function setSharding() {
// Harmony is a sharded blockchain, each endpoint have sharding structure,
// However sharding structure is different between mainnet, testnet and local testnet
// We need to get sharding info before doing cross-shard transaction
const res = await harmony.blockchain.getShardingStructure();
harmony.shardingStructures(res.result);
}
// 4. get transaction payload ready
async function transfer(receiver) {
// run set sharding first, if you want to make a cross-shard transaction
await setSharding();
//1e18
const txn = harmony.transactions.newTx({
// token send to
to: receiver,
// amount to send
value: '100000000',
// gas limit, you can use string
gasLimit: '210000',
// send token from shardID
shardID: 0,
// send token to toShardID
toShardID: 1,
// gas Price, you can use Unit class, and use Gwei, then remember to use toWei(), which will be transformed to BN
gasPrice: new harmony.utils.Unit('10').asGwei().toWei(),
});
// sign the transaction use wallet;
// This will happen at the chrome extension.
const signedTxn = await harmony.wallet.signTransaction(txn);
// Now you can use `Transaction.observed()` to listen events
// Frontend received back the signedTxn and do the followings to Send transaction.
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('');
});
// send the txn, get [Transaction, transactionHash] as result
const [sentTxn, txnHash] = await signedTxn.sendTransaction();
// to confirm the result if it is already there
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.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.harmony.one/#/tx/' + txnHash);
console.log('');
process.exit();
}
}
// sending from one18n8e7472pg5fqvcfcr5hg0npquha24wsxmjheg to one1a2rhuaqjcvfu69met9sque2l3w5v9z6qcdcz65
(async () => await transfer('one1pf75h0t4am90z8uv3y0dgunfqp4lj8wr3t5rsp'))();

@ -0,0 +1,151 @@
// import or require Harmony class
const { Harmony } = require('@harmony-js/core');
// import or require settings
const { ChainID, ChainType } = require('@harmony-js/utils');
// const URL_TESTNET = `https://api.s0.pga.hmny.io`;
const URL_MAINNET = `https://api.s0.t.hmny.io`;
// const LOCAL_TESTNET = `http://localhost:9500`;
const DEVNET = 'https://api.s0.pga.hmny.io';
// 1. initialize the Harmony instance
const harmony = new Harmony(
// rpc url
DEVNET,
{
// chainType set to Harmony
chainType: ChainType.Harmony,
// chainType set to HmyLocal
chainId: ChainID.HmyPangaea,
},
);
// 2. get wallet ready
// one18n8e7472pg5fqvcfcr5hg0npquha24wsxmjheg;
const phrase = 'genius cable radar memory high catch blossom correct middle wish gentle fiscal';
// one1a2rhuaqjcvfu69met9sque2l3w5v9z6qcdcz65
// surge welcome lion goose gate consider taste injury health march debris kick
// add privateKey to wallet
// const sender = harmony.wallet.addByMnemonic(phrase);
// add privateKey to wallet
const private = '63e35b761e9df0d50ddcdaa8e33c235b60c991bfed22925a12768b0c08ef822f';
// one1pdv9lrdwl0rg5vglh4xtyrv3wjk3wsqket7zxy
const sender = harmony.wallet.addByPrivateKey(private);
// const sender = harmony.wallet.addByPrivateKey(
// 'fd416cb87dcf8ed187e85545d7734a192fc8e976f5b540e9e21e896ec2bc25c3',
// );
// 3. get sharding info
async function setSharding() {
// Harmony is a sharded blockchain, each endpoint have sharding structure,
// However sharding structure is different between mainnet, testnet and local testnet
// We need to get sharding info before doing cross-shard transaction
const res = await harmony.blockchain.getShardingStructure();
harmony.shardingStructures(res.result);
}
// 4. get transaction payload ready
async function transfer(receiver) {
// run set sharding first, if you want to make a cross-shard transaction
await setSharding();
//1e18
const txn = harmony.transactions.newTx({
// token send to
to: receiver,
// amount to send
value: '100000000000000000',
// 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 harmony.utils.Unit('100').asGwei().toWei(),
});
// sign the transaction use wallet;
// This will happen at the chrome extension.
const signedTxn = await harmony.wallet.signTransaction(txn);
// Now you can use `Transaction.observed()` to listen events
// Frontend received back the signedTxn and do the followings to Send transaction.
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('');
});
// send the txn, get [Transaction, transactionHash] as result
const [sentTxn, txnHash] = await signedTxn.sendTransaction();
// to confirm the result if it is already there
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.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.harmony.one/#/tx/' + txnHash);
console.log('');
process.exit();
}
}
// sending from one18n8e7472pg5fqvcfcr5hg0npquha24wsxmjheg to one1a2rhuaqjcvfu69met9sque2l3w5v9z6qcdcz65
(async () => await transfer('one1pdv9lrdwl0rg5vglh4xtyrv3wjk3wsqket7zxy'))();

@ -0,0 +1,137 @@
// import or require Harmony class
const { Harmony } = require('@harmony-js/core');
// import or require settings
const { ChainID, ChainType } = require('@harmony-js/utils');
//const URL_TESTNET = `https://api.s0.b.hmny.io`;
const URL_TESTNET = `localhost:9500`;
const URL_MAINNET = `https://api.s0.t.hmny.io`;
// 1. initialize the Harmony instance
const harmony = new Harmony(
// rpc url
URL_TESTNET,
{
// chainType set to Harmony
chainType: ChainType.Harmony,
// chainType set to HmyLocal
chainId: ChainID.HmyTestnet,
},
);
// 2. get wallet ready
// one18n8e7472pg5fqvcfcr5hg0npquha24wsxmjheg
//const phrase = 'genius cable radar memory high catch blossom correct middle wish gentle fiscal';
// one1a2rhuaqjcvfu69met9sque2l3w5v9z6qcdcz65
// surge welcome lion goose gate consider taste injury health march debris kick
// add privateKey to wallet
//const sender = harmony.wallet.addByMnemonic(phrase);
// add privateKey to wallet
const private = 'fd416cb87dcf8ed187e85545d7734a192fc8e976f5b540e9e21e896ec2bc25c3';
const sender = harmony.wallet.addByPrivateKey(private);
// 3. get sharding info
async function setSharding() {
// Harmony is a sharded blockchain, each endpoint have sharding structure,
// However sharding structure is different between mainnet, testnet and local testnet
// We need to get sharding info before doing cross-shard transaction
const res = await harmony.blockchain.getShardingStructure();
harmony.shardingStructures(res.result);
}
// 4. get transaction payload ready
async function transfer(receiver) {
// run set sharding first, if you want to make a cross-shard transaction
await setSharding();
//1e18
const txn = harmony.transactions.newTx({
// token send to
to: receiver,
// amount to send
value: '100000000000000000',
// 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 harmony.utils.Unit('100').asGwei().toWei(),
});
// sign the transaction use wallet;
// This will happen at the chrome extension.
const signedTxn = await harmony.wallet.signTransaction(txn);
// Now you can use `Transaction.observed()` to listen events
// Frontend received back the signedTxn and do the followings to Send transaction.
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('');
});
// send the txn, get [Transaction, transactionHash] as result
const [sentTxn, txnHash] = await signedTxn.sendTransaction();
// to confirm the result if it is already there
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('');
process.exit();
}
}
if (confiremdTxn.isConfirmed() && confiremdTxn.isCxConfirmed()) {
console.log('--- Result ---');
console.log('');
console.log('Cross-Shard transaction');
console.log(`${txnHash} is confirmed`);
console.log('');
process.exit();
}
}
// sending from one18n8e7472pg5fqvcfcr5hg0npquha24wsxmjheg to one1a2rhuaqjcvfu69met9sque2l3w5v9z6qcdcz65
transfer('one1a2rhuaqjcvfu69met9sque2l3w5v9z6qcdcz65');

@ -4,14 +4,14 @@ const fs = require('fs');
const path = require('path');
const packages = [
'woop-core',
'woop-crypto',
'woop-account',
'woop-network',
'woop-contract',
'woop-utils',
'woop-transaction',
'woop-staking',
'harmony-core',
'harmony-crypto',
'harmony-account',
'harmony-network',
'harmony-contract',
'harmony-utils',
'harmony-transaction',
'harmony-staking',
];
task('cleanBrowser', async () => {

@ -2,5 +2,5 @@
"packages": ["packages/*"],
"npmClient": "yarn",
"useWorkspaces": true,
"version": "0.1.58"
"version": "0.1.53"
}

1081
log.txt

File diff suppressed because it is too large Load Diff

44661
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -1,5 +1,5 @@
{
"description": "Root repository for the woop-sdk-core",
"description": "Root repository for the harmony-sdk-core",
"private": true,
"license": "MIT",
"workspaces": [
@ -89,14 +89,14 @@
"dotenv": "^6.0.0",
"fancy-log": "^1.3.2",
"fbjs-scripts": "^0.8.3",
"ganache-cli": "^6.12.1",
"ganache-cli": "^6.4.3",
"glob": "^7.1.3",
"glob-parent": "^3.1.0",
"gulp": "^4.0.0",
"gulp-typedoc": "^2.2.2",
"husky": "^1.1.2",
"jest": "^23.4.2",
"jest-fetch-mock": "^3.0.3",
"jest-fetch-mock": "^1.6.6",
"jest-json-schema": "^2.0.1",
"jest-watch-typeahead": "^0.2.0",
"jsdoc": "^3.6.3",
@ -107,7 +107,7 @@
"pretty-quick": "^1.8.0",
"protobufjs": "^6.8.8",
"rimraf": "^2.6.2",
"rollup": "1.26.3",
"rollup": "^0.66.6",
"rollup-plugin-alias": "^1.4.0",
"rollup-plugin-babel": "^4.3.2",
"rollup-plugin-commonjs": "^9.2.0",
@ -117,19 +117,19 @@
"rollup-plugin-node-builtins": "^2.1.2",
"rollup-plugin-node-globals": "^1.4.0",
"rollup-plugin-node-resolve": "^3.4.0",
"rollup-plugin-typescript2": "^0.29.0",
"rollup-plugin-typescript2": "^0.17.1",
"solc": "^0.5.8",
"terser-webpack-plugin": "^2.1.2",
"ts-jest": "^23.1.3",
"ts-node": "^7.0.1",
"tslib": "^2.4.0",
"tslib": "^1.11.1",
"tslint": "^5.11.0",
"tslint-config-prettier": "^1.15.0",
"typedoc": "^0.17.0-3",
"typedoc-plugin-external-module-name": "^3.0.0",
"typedoc-plugin-no-inherit": "^1.1.10",
"typescript": "^3.8.3",
"typescript-json-schema": "^0.43.0",
"typescript-json-schema": "^0.36.0",
"webpack": "^4.20.2",
"webpack-command": "^0.4.1",
"webpack-node-externals": "^1.7.2",
@ -140,10 +140,10 @@
"pre-commit": "pretty-quick --staged"
}
},
"name": "woop-sdk-core",
"name": "harmony-sdk-core",
"dependencies": {
"@woop-js/core": "^0.1.36",
"tslib": "^2.4.0",
"@harmony-js/core": "^0.1.36",
"tslib": "^1.10.0",
"typedoc-plugin-internal-external": "^2.1.1"
}
}

@ -1,12 +1,10 @@
# Packages available are:
1. [@woop-js/core](https://github.com/woop-chain/sdk/tree/master/packages/woop-core)
2. [@woop-js/account](https://github.com/woop-chain/sdk/tree/master/packages/woop-account)
3. [@woop-js/crypto](https://github.com/woop-chain/sdk/tree/master/packages/woop-crypto)
4. [@woop-js/network](https://github.com/woop-chain/sdk/tree/master/packages/woop-network)
5. [@woop-js/utils](https://github.com/woop-chain/sdk/tree/master/packages/woop-utils)
6. [@woop-js/transaction](https://github.com/woop-chain/sdk/tree/master/packages/woop-transaction)
7. [@woop-js/contract](https://github.com/woop-chain/sdk/tree/master/packages/woop-contract)
8. [@woop-js/staking](https://github.com/woop-chain/sdk/tree/master/packages/woop-staking)
<mark>Package level documentation and examples are inside each package</mark>
1. [@harmony-js/core](https://github.com/harmony-one/sdk/tree/master/packages/harmony-core)
2. [@harmony-js/account](https://github.com/harmony-one/sdk/tree/master/packages/harmony-account)
3. [@harmony-js/crypto](https://github.com/harmony-one/sdk/tree/master/packages/harmony-crypto)
4. [@harmony-js/network](https://github.com/harmony-one/sdk/tree/master/packages/harmony-network)
5. [@harmony-js/utils](https://github.com/harmony-one/sdk/tree/master/packages/harmony-utils)
6. [@harmony-js/transaction](https://github.com/harmony-one/sdk/tree/master/packages/harmony-transaction)
7. [@harmony-js/contract](https://github.com/harmony-one/sdk/tree/master/packages/harmony-contract)
8. [@harmony-js/staking](https://github.com/harmony-one/sdk/tree/master/packages/harmony-staking)

@ -1,11 +1,11 @@
# @woop-js/account
# @harmony-js/account
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.
## Installation
```
npm install @woop-js/account
npm install @harmony-js/account
```
## Usage
@ -28,8 +28,8 @@ const account = new Account(
'45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e',
new Messenger(
new HttpProvider('https://api.s0.b.hmny.io'),
ChainType.Woop,
ChainID.WikiTestnet,
ChainType.Harmony,
ChainID.HmyTestnet,
),
);
```
@ -40,8 +40,8 @@ Creating account and setting custom messenger
const account = new Account();
const customMessenger = new Messenger(
new HttpProvider('https://api.s0.b.hmny.io'),
ChainType.Woop,
ChainID.WikiTestnet,
ChainType.Harmony,
ChainID.HmyTestnet,
);
account.setMessenger(customMessenger);
@ -72,8 +72,8 @@ const account = new Account(
'45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e',
new Messenger(
new HttpProvider('https://api.s0.b.hmny.io'),
ChainType.Woop,
ChainID.WikiTestnet,
ChainType.Harmony,
ChainID.HmyTestnet,
),
);
account.getBalance().then(response => {
@ -88,12 +88,12 @@ const account = new Account(
'45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e',
new Messenger(
new HttpProvider('https://api.s0.b.hmny.io'),
ChainType.Woop,
ChainID.WikiTestnet,
ChainType.Harmony,
ChainID.HmyTestnet,
),
);
const { TransactionFactory } = require('@woop-js/transaction');
const { Unit } = require('@woop-js/utils');
const { TransactionFactory } = require('@harmony-js/transaction');
const { Unit } = require('@harmony-js/utils');
const factory = new TransactionFactory();
const txn = factory.newTx({
@ -120,7 +120,7 @@ A wallet represents user wallet that can hold one or more user accounts.
Creating an empty wallet
```javascript
const { Wallet } = require('@woop-js/account')
const { Wallet } = require('@harmony-js/account')
const wallet = new Wallet();
```
@ -129,8 +129,8 @@ Setting a messenger to be used to send wallet transactions
wallet.setMessenger(
new Messenger(
new HttpProvider('https://api.s0.b.hmny.io'),
ChainType.Woop,
ChainID.WikiTestnet,
ChainType.Harmony,
ChainID.HmyTestnet,
),
);
```
@ -140,8 +140,8 @@ Create an empty wallet with messenger
const wallet = new Wallet(
new Messenger(
new HttpProvider('https://api.s0.b.hmny.io'),
ChainType.Woop,
ChainID.WikiTestnet,
ChainType.Harmony,
ChainID.HmyTestnet,
),
);
```
@ -168,7 +168,7 @@ wallet.addByKeyStore(keystore, passphrase).then(account => {
Creating a new account using passphrase
```javascript
const passphrase = 'woop-chain';
const passphrase = 'harmony-one';
wallet.createAccount(passphrase).then(account => {
console.log(account.bech32Address);
});

@ -0,0 +1,274 @@
/**
## About This Package
`@harmony-js/account` is dealing with account related features.
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.
## Usage of Account
### Dependencies
- @harmony-js/network
- @harmony-js/staking
- @harmony-js/transaction
- @harmony-js/utils
### Examples
Create a random account
```javascript
// import the Account class
import {Account} from '@harmony-js/account'
// 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
```typescript
// 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
```typescript
// import the Account class
import {Account} from '@harmony-js/account'
// suppose we have an account
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)
```
### Address format getter
```typescript
// import the Account class
import {Account} from '@harmony-js/account'
// suppose we have an account
const myPrivateKey = '0xe19d05c5452598e24caad4a0d85a49146f7be089515c905ae6a19e8a578a6930'
const myAccountWithMyPrivateKey = new Account(myPrivateKey)
// 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)
```
### Sign a transaction
```typescript
// import the Account class
import {Account} from '@harmony-js/account'
// 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);
async function signTheTxn() {
// Account.signTransaction(transaction: Transaction, updateNonce?: boolean, encodeMode?: string, blockNumber?: string): Promise<Transaction>
// If the 2nd parameter `updateNonce` is set to true, it will query and update account's nonce before it signs
const signedTxn = await myAccountWithMyPrivateKey.signTransaction(txn, false, 'rlp', 'latest');
// see if the transaction is signed
console.log(`\n see if transaction is signed: \n ${signedTxn.isSigned()} \n`);
// get the tranaction bytes
console.log(`\n the signed bytes is: \n ${signedTxn.getRawTransaction()} \n`);
return signTheTxn;
}
signTheTxn();
```
## Usage of Wallet
### Dependencies
- @harmony-js/crypto
- @harmony-js/network
- @harmony-js/staking
- @harmony-js/transaction
- @harmony-js/utils
```typescript
// constructor
const { Wallet } = require('@harmony-js/account');
const wallet = new Wallet(customMessenger);
// get signer
const wallet = new Wallet(customMessenger);
const key_1 = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e';
console.log(wallet.addByPrivateKey(key_1));
console.log(wallet.signer)
// createAccount
console.log(wallet.accounts);
wallet.createAccount();
wallet.createAccount();
console.log(wallet.accounts);
// encryptAccount
const key_1 = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e';
wallet.addByPrivateKey(key_1);
wallet.encryptAccount('one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7', '12345').then((value) => {
console.log(value);
})
// decrptAccount
const key_1 = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e';
wallet.addByPrivateKey(key_1);
wallet.encryptAccount('one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7', '12345').then(() => {
wallet.decryptAccount('one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7', '12345').then((value) => {
console.log(value);
})
});
```
*
* @packageDocumentation
* @module harmony-account
*/
/**@ignore */
export interface README {}

@ -1,7 +1,7 @@
{
"name": "@woop-js/account",
"version": "0.1.58",
"description": "account and wallet for woop",
"name": "@harmony-js/account",
"version": "0.1.53",
"description": "account and wallet for harmony",
"main": "dist/index.js",
"node": "dist/index.js",
"browser": "dist/index.js",
@ -18,12 +18,12 @@
"author": "neeboo@firestack.one",
"license": "MIT",
"dependencies": {
"@woop-js/core": "0.1.58",
"@woop-js/crypto": "0.1.58",
"@woop-js/network": "0.1.58",
"@woop-js/staking": "0.1.58",
"@woop-js/transaction": "0.1.58",
"@woop-js/utils": "0.1.58"
"@harmony-js/core": "0.1.53",
"@harmony-js/crypto": "0.1.48",
"@harmony-js/network": "0.1.51",
"@harmony-js/staking": "0.1.51",
"@harmony-js/transaction": "0.1.51",
"@harmony-js/utils": "0.1.48"
},
"gitHead": "56606e9365721729a490c27d6a294e0daf90fbdf"
}

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-account
* @module harmony-account
*
*/
@ -15,7 +15,7 @@ import {
Keystore,
Signature,
getAddress,
} from '@woop-js/crypto';
} from '@harmony-js/crypto';
import {
isPrivateKey,
@ -23,10 +23,10 @@ import {
hexToNumber,
AddressSuffix,
ChainType,
} from '@woop-js/utils';
import { Transaction, RLPSign } from '@woop-js/transaction';
import { StakingTransaction } from '@woop-js/staking';
import { Messenger, RPCMethod } from '@woop-js/network';
} from '@harmony-js/utils';
import { Transaction, RLPSign } from '@harmony-js/transaction';
import { StakingTransaction } from '@harmony-js/staking';
import { Messenger, RPCMethod } from '@harmony-js/network';
import { Shards } from './types';
import { defaultMessenger } from './utils';
@ -141,18 +141,18 @@ class Account {
* @example
* ```javascript
* // import the Account class
* const { Account } = require('@woop-js/account');
* const { Account } = require('@harmony-js/account');
*
* // Messenger is optional, by default, we have a defaultMessenger
* // If you like to change, you will import related package here.
* const { HttpProvider, Messenger } = require('@woop-js/network');
* const { ChainType, ChainID } = require('@woop-js/utils');
* const { HttpProvider, Messenger } = require('@harmony-js/network');
* const { ChainType, ChainID } = require('@harmony-js/utils');
*
* // create a custom messenger
* const customMessenger = new Messenger(
* new HttpProvider('http://localhost:9500'),
* ChainType.Woop, // if you are connected to Woop's blockchain
* ChainID.WikiLocal, // check if the chainId is correct
* ChainType.Harmony, // if you are connected to Harmony's blockchain
* ChainID.HmyLocal, // check if the chainId is correct
* )
*
* // setMessenger later
@ -299,18 +299,30 @@ class Account {
if (updateNonce) {
// await this.updateBalances(blockNumber);
const txShardID = transaction.txParams.shardID;
const shardNonce = await this.getShardNonce(
const shardBalanceObject = await this.getShardBalance(
typeof txShardID === 'string' ? Number.parseInt(txShardID, 10) : txShardID,
blockNumber,
);
transaction.setParams({
...transaction.txParams,
from:
this.messenger.chainPrefix === ChainType.Woop
? this.bech32Address
: this.checksumAddress || '0x',
nonce: shardNonce,
});
if (shardBalanceObject !== undefined) {
const shardNonce = shardBalanceObject.nonce;
transaction.setParams({
...transaction.txParams,
from:
this.messenger.chainPrefix === ChainType.Harmony
? this.bech32Address
: this.checksumAddress || '0x',
nonce: shardNonce,
});
} else {
transaction.setParams({
...transaction.txParams,
from:
this.messenger.chainPrefix === ChainType.Harmony
? this.bech32Address
: this.checksumAddress || '0x',
nonce: 0,
});
}
}
if (encodeMode === 'rlp') {
@ -324,7 +336,7 @@ class Account {
signature,
rawTransaction,
from:
this.messenger.chainPrefix === ChainType.Woop
this.messenger.chainPrefix === ChainType.Harmony
? this.bech32Address
: this.checksumAddress || '0x',
};
@ -358,16 +370,27 @@ class Account {
if (updateNonce) {
// await this.updateBalances(blockNumber);
const txShardID = shardID;
const shardNonce = await this.getShardNonce(
const shardBalanceObject = await this.getShardBalance(
typeof txShardID === 'string' ? Number.parseInt(txShardID, 10) : txShardID,
blockNumber,
);
staking.setFromAddress(
this.messenger.chainPrefix === ChainType.Woop
? this.bech32Address
: this.checksumAddress || '0x',
);
staking.setNonce(shardNonce);
if (shardBalanceObject !== undefined) {
const shardNonce = shardBalanceObject.nonce;
staking.setFromAddress(
this.messenger.chainPrefix === ChainType.Harmony
? this.bech32Address
: this.checksumAddress || '0x',
);
staking.setNonce(shardNonce);
} else {
staking.setFromAddress(
this.messenger.chainPrefix === ChainType.Harmony
? this.bech32Address
: this.checksumAddress || '0x',
);
staking.setNonce(0);
}
}
if (encodeMode === 'rlp') {
@ -375,7 +398,7 @@ class Account {
staking.setRawTransaction(rawTransaction);
staking.setSignature(signature);
staking.setFromAddress(
this.messenger.chainPrefix === ChainType.Woop
this.messenger.chainPrefix === ChainType.Harmony
? this.bech32Address
: this.checksumAddress || '0x',
);
@ -395,8 +418,8 @@ class Account {
* // create a custom messenger
* const customMessenger = new Messenger(
* new HttpProvider('http://localhost:9500'),
* ChainType.Woop, // if you are connected to Woop's blockchain
* ChainID.WikiLocal, // check if the chainId is correct
* 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
@ -487,32 +510,6 @@ class Account {
};
}
/**
* Get the specific shard's nonce
*
* @param shardID `shardID` is binding with the endpoint, IGNORE it!
* @param blockNumber by default, it's `latest`
*
* @example
* ```
* account.getShardNonce().then((value) => {
* console.log(value);
* });
* ```
*/
async getShardNonce(shardID: number, blockNumber: string = 'latest') {
const nonce = await this.messenger.send(
RPCMethod.GetAccountNonce,
[this.address, blockNumber],
this.messenger.chainPrefix,
shardID,
);
if (nonce.isError()) {
throw nonce.error.message;
}
return nonce.result;
}
/**
* @function _new private method create Account
* @return {Account} Account instance

@ -1,9 +1,9 @@
/**
* @packageDocumentation
* @module woop-account
* @module harmony-account
*/
import { bip39, hdkey, getAddress, BN, Signature } from '@woop-js/crypto';
import { bip39, hdkey, getAddress, BN, Signature } from '@harmony-js/crypto';
import {
HDPath,
// defineReadOnly,
@ -14,9 +14,9 @@ import {
Unit,
isHex,
hexToNumber,
} from '@woop-js/utils';
import { Messenger, HttpProvider, WSProvider, RPCMethod } from '@woop-js/network';
import { Transaction, TxStatus, TransasctionReceipt } from '@woop-js/transaction';
} from '@harmony-js/utils';
import { Messenger, HttpProvider, WSProvider } from '@harmony-js/network';
import { Transaction, TxStatus, TransasctionReceipt } from '@harmony-js/transaction';
import { Account } from './account';
/** @hidden */
@ -81,7 +81,7 @@ export class HDNode {
index: number = 0,
addressCount: number = 1,
shardID: number = 0,
chainType: ChainType = ChainType.Woop,
chainType: ChainType = ChainType.Harmony,
chainId: ChainID = ChainID.Default,
gasLimit = '1000000',
gasPrice = '2000000000',
@ -93,12 +93,10 @@ export class HDNode {
this.hdwallet = undefined;
this.addresses = [];
this.wallets = {};
this.path = chainType === ChainType.Woop ? HDPath : `m/44'/60'/0'/0/`;
this.path = chainType === ChainType.Harmony ? HDPath : `m/44'/60'/0'/0/`;
this.index = index;
this.addressCount = addressCount;
if (menmonic !== null && menmonic !== '') {
this.getHdWallet(menmonic || HDNode.generateMnemonic());
}
this.getHdWallet(menmonic || HDNode.generateMnemonic());
this.gasLimit = gasLimit;
this.gasPrice = gasPrice;
}
@ -153,7 +151,6 @@ export class HDNode {
}
return this.addresses;
}
// tslint:disable-next-line: ban-types
getPrivateKey(address: string, cb?: Function) {
if (!cb) {
@ -169,14 +166,13 @@ export class HDNode {
cb(null, this.wallets[address].privateKey);
}
}
// tslint:disable-next-line: ban-types
async signTransaction(txParams: any | Web3TxPrams) {
const from: string = txParams.from ? getAddress(txParams.from).checksum : '0x';
const accountNonce = await this.messenger.send(
RPCMethod.GetAccountNonce,
'hmy_getTransactionCount',
[from, 'latest'],
'wiki',
'hmy',
this.shardID,
);
@ -215,7 +211,7 @@ export class HDNode {
const nonce =
txParams.nonce !== undefined && isHex(txParams.nonce)
? Number.parseInt(hexToNumber(txParams.nonce), 10)
: accountNonce.result;
: Number.parseInt(hexToNumber(accountNonce.result), 10);
const data = txParams.data !== undefined && isHex(txParams.data) ? txParams.data : '0x';
const prv = this.wallets[from].privateKey;
@ -242,7 +238,6 @@ export class HDNode {
return signed.getRawTransaction();
}
getAddress(idx?: number) {
if (!idx) {
return this.addresses[0];
@ -250,11 +245,9 @@ export class HDNode {
return this.addresses[idx];
}
}
getAddresses() {
return this.addresses;
}
addByPrivateKey(privateKey: string) {
const account = new Account(privateKey);
const addr = account.checksumAddress;
@ -265,7 +258,7 @@ export class HDNode {
setSigner(address: string) {
const foundIndex = this.addresses.findIndex((value) => value === address);
this.addresses.splice(foundIndex, 1);
this.addresses.slice(foundIndex, foundIndex + 1);
this.addresses.unshift(address);
}
}

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-account
* @module harmony-account
* @ignore
*/

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-account
* @module harmony-account
* @hidden
*/

@ -0,0 +1,14 @@
/**
* @packageDocumentation
* @module harmony-account
* @hidden
*/
import { HttpProvider, Messenger } from '@harmony-js/network';
import { ChainType, ChainID } from '@harmony-js/utils';
export const defaultMessenger = new Messenger(
new HttpProvider('http://localhost:9500'),
ChainType.Harmony,
ChainID.HmyLocal,
);

@ -1,13 +1,13 @@
/**
* @packageDocumentation
* @module woop-account
* @module harmony-account
*/
import { bip39, hdkey, EncryptOptions, getAddress, generatePrivateKey } from '@woop-js/crypto';
import { Messenger } from '@woop-js/network';
import { isPrivateKey, isAddress, ChainType } from '@woop-js/utils';
import { Transaction } from '@woop-js/transaction';
import { StakingTransaction } from '@woop-js/staking';
import { bip39, hdkey, EncryptOptions, getAddress, generatePrivateKey } from '@harmony-js/crypto';
import { Messenger } from '@harmony-js/network';
import { isPrivateKey, isAddress, ChainType } from '@harmony-js/utils';
import { Transaction } from '@harmony-js/transaction';
import { StakingTransaction } from '@harmony-js/staking';
import { Account } from './account';
import { defaultMessenger } from './utils';
@ -70,15 +70,15 @@ class Wallet {
/**
* @example
* ```
* const { Wallet } = require('@woop-js/account');
* const { HttpProvider, Messenger } = require('@woop-js/network');
* const { ChainType, ChainID } = require('@woop-js/utils');
* const { Wallet } = require('@harmony-js/account');
* const { HttpProvider, Messenger } = require('@harmony-js/network');
* const { ChainType, ChainID } = require('@harmony-js/utils');
*
* // create a custom messenger
* const customMessenger = new Messenger(
* new HttpProvider('http://localhost:9500'),
* ChainType.Woop, // if you are connected to Woop's blockchain
* ChainID.WikiLocal, // check if the chainId is correct
* ChainType.Harmony, // if you are connected to Harmony's blockchain
* ChainID.HmyLocal, // check if the chainId is correct
* )
*
* const wallet = new Wallet(customMessenger);
@ -116,8 +116,8 @@ class Wallet {
}
const seed = bip39.mnemonicToSeed(phrase);
const hdKey = hdkey.fromMasterSeed(seed);
// TODO:hdkey should apply to Woop's settings
const path = this.messenger.chainType === ChainType.Woop ? '1023' : '60';
// TODO:hdkey should apply to Harmony's settings
const path = this.messenger.chainType === ChainType.Harmony ? '1023' : '60';
const childKey = hdKey.derive(`m/44'/${path}'/0'/0/${index}`);
const privateKey = childKey.privateKey.toString('hex');
return this.addByPrivateKey(privateKey);
@ -316,8 +316,8 @@ class Wallet {
* ```javascript
* const customMessenger = new Messenger(
* new HttpProvider('https://api.s0.b.hmny.io'),
* ChainType.Woop, // if you are connected to Woop's blockchain
* ChainID.WikiLocal, // check if the chainId is correct
* ChainType.Harmony, // if you are connected to Harmony's blockchain
* ChainID.HmyLocal, // check if the chainId is correct
* )
* const wallet = new Wallet();
* wallet.setMessenger(customMessenger);

@ -1,29 +1,18 @@
/**
* @packageDocumentation
* @module woop-account
* @module harmony-account
* @ignore
*/
import fetch from 'jest-fetch-mock';
import { Account } from '../src/account';
import { HttpProvider, Messenger } from '@woop-js/network';
import { ChainType, ChainID } from '@woop-js/utils';
import { HttpProvider, Messenger } from '@harmony-js/network';
import { ChainType, ChainID } from '@harmony-js/utils';
const provider = new HttpProvider('http://localhost:9500');
const messenger = new Messenger(provider, ChainType.Woop, ChainID.WikiLocal);
const messenger = new Messenger(provider, ChainType.Harmony, ChainID.HmyLocal);
describe('test account', () => {
it('test Account.getBalance returns object that implements Balance interface', () => {
fetch.mockResponses(
[
JSON.stringify({"jsonrpc": "2.0", "id": 1, "result": "0x166c690f33421e"}),
{ status: 200 }
],
[
JSON.stringify({"jsonrpc": "2.0", "id": 1, "result": "0x106"}),
{ status: 200 }
]
);
const acc = Account.new();
acc.setMessenger(messenger);
acc.getBalance().then((res) => {

@ -6,10 +6,10 @@
},
"include": ["src", "../../typings/**/*.d.ts", "aaa.ts"],
"references": [
{ "path": "../woop-crypto" },
{ "path": "../woop-utils" },
{ "path": "../woop-transaction" },
{ "path": "../woop-staking" },
{ "path": "../woop-network" }
{ "path": "../harmony-crypto" },
{ "path": "../harmony-utils" },
{ "path": "../harmony-transaction" },
{ "path": "../harmony-staking" },
{ "path": "../harmony-network" }
]
}

@ -61,15 +61,15 @@
"type": "function"
}
],
"metadata": "{\"compiler\":{\"version\":\"0.5.16+commit.9c3226ce\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"inc\",\"type\":\"address\"}],\"name\":\"DecrementedBy\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"inc\",\"type\":\"address\"}],\"name\":\"IncrementedBy\",\"type\":\"event\"},{\"constant\":false,\"inputs\":[],\"name\":\"decrementCounter\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"getCount\",\"outputs\":[{\"internalType\":\"int256\",\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"incrementCounter\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"methods\":{}},\"userdoc\":{\"methods\":{}}},\"settings\":{\"compilationTarget\":{\"/Users/gupadhyaya/go/src/github.com/woop-chain/counter/contracts/Counter.sol\":\"Counter\"},\"evmVersion\":\"istanbul\",\"libraries\":{},\"optimizer\":{\"enabled\":false,\"runs\":200},\"remappings\":[]},\"sources\":{\"/Users/gupadhyaya/go/src/github.com/woop-chain/counter/contracts/Counter.sol\":{\"keccak256\":\"0x082839c98df1285d97e56f9ccdb4cd52d6723ab394356acc6d618d96bbd7e60e\",\"urls\":[\"bzz-raw://fd2b8a231c2fadcd0e60787a92a6e9df1b962684329f2dd13560857572d36168\",\"dweb:/ipfs/QmRmp9NK2mZk5GGfkK5b33HsaY2jz8B6uWpUYij7K9RW3r\"]}},\"version\":1}",
"metadata": "{\"compiler\":{\"version\":\"0.5.16+commit.9c3226ce\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"inc\",\"type\":\"address\"}],\"name\":\"DecrementedBy\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"inc\",\"type\":\"address\"}],\"name\":\"IncrementedBy\",\"type\":\"event\"},{\"constant\":false,\"inputs\":[],\"name\":\"decrementCounter\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"getCount\",\"outputs\":[{\"internalType\":\"int256\",\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"incrementCounter\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"methods\":{}},\"userdoc\":{\"methods\":{}}},\"settings\":{\"compilationTarget\":{\"/Users/gupadhyaya/go/src/github.com/harmony-one/counter/contracts/Counter.sol\":\"Counter\"},\"evmVersion\":\"istanbul\",\"libraries\":{},\"optimizer\":{\"enabled\":false,\"runs\":200},\"remappings\":[]},\"sources\":{\"/Users/gupadhyaya/go/src/github.com/harmony-one/counter/contracts/Counter.sol\":{\"keccak256\":\"0x082839c98df1285d97e56f9ccdb4cd52d6723ab394356acc6d618d96bbd7e60e\",\"urls\":[\"bzz-raw://fd2b8a231c2fadcd0e60787a92a6e9df1b962684329f2dd13560857572d36168\",\"dweb:/ipfs/QmRmp9NK2mZk5GGfkK5b33HsaY2jz8B6uWpUYij7K9RW3r\"]}},\"version\":1}",
"bytecode": "0x60806040526000805534801561001457600080fd5b506101a0806100246000396000f3fe608060405234801561001057600080fd5b50600436106100415760003560e01c80635b34b96614610046578063a87d942c14610050578063f5c5ad831461006e575b600080fd5b61004e610078565b005b6100586100ed565b6040518082815260200191505060405180910390f35b6100766100f6565b005b600160008082825401925050819055507f064b1e66d8d787e36504c45aac3405f69335030ab8dc365a34919de13b61799c33604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a1565b60008054905090565b600160008082825403925050819055507f102d4e03b331a68eaffb991d44063c4452a0b6b650d8fb74b6932d8bd856f1c133604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a156fea265627a7a72315820963135863e1328fe0c11fedc623e29e097902650e6976e7650a1577c1086fc6a64736f6c63430005100032",
"deployedBytecode": "0x608060405234801561001057600080fd5b50600436106100415760003560e01c80635b34b96614610046578063a87d942c14610050578063f5c5ad831461006e575b600080fd5b61004e610078565b005b6100586100ed565b6040518082815260200191505060405180910390f35b6100766100f6565b005b600160008082825401925050819055507f064b1e66d8d787e36504c45aac3405f69335030ab8dc365a34919de13b61799c33604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a1565b60008054905090565b600160008082825403925050819055507f102d4e03b331a68eaffb991d44063c4452a0b6b650d8fb74b6932d8bd856f1c133604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a156fea265627a7a72315820963135863e1328fe0c11fedc623e29e097902650e6976e7650a1577c1086fc6a64736f6c63430005100032",
"sourceMap": "34:426:0:-;;;80:1;57:24;;34:426;8:9:-1;5:2;;;30:1;27;20:12;5:2;34:426:0;;;;;;;",
"deployedSourceMap": "34:426:0:-;;;;8:9:-1;5:2;;;30:1;27;20:12;5:2;34:426:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;164:102;;;:::i;:::-;;380:78;;;:::i;:::-;;;;;;;;;;;;;;;;;;;272:102;;;:::i;:::-;;164;218:1;209:5;;:10;;;;;;;;;;;234:25;248:10;234:25;;;;;;;;;;;;;;;;;;;;;;164:102::o;380:78::-;421:6;446:5;;439:12;;380:78;:::o;272:102::-;326:1;317:5;;:10;;;;;;;;;;;342:25;356:10;342:25;;;;;;;;;;;;;;;;;;;;;;272:102::o",
"source": "pragma solidity >=0.4.21 <0.6.0;\n\ncontract Counter {\n int256 private count = 0;\n event IncrementedBy(address inc);\n event DecrementedBy(address inc);\n\n function incrementCounter() public {\n count += 1;\n emit IncrementedBy(msg.sender);\n }\n\n function decrementCounter() public {\n count -= 1;\n emit DecrementedBy(msg.sender);\n }\n\n function getCount() public view returns (int256) {\n return count;\n }\n}\n",
"sourcePath": "/Users/gupadhyaya/go/src/github.com/woop-chain/counter/contracts/Counter.sol",
"sourcePath": "/Users/gupadhyaya/go/src/github.com/harmony-one/counter/contracts/Counter.sol",
"ast": {
"absolutePath": "/Users/gupadhyaya/go/src/github.com/woop-chain/counter/contracts/Counter.sol",
"absolutePath": "/Users/gupadhyaya/go/src/github.com/harmony-one/counter/contracts/Counter.sol",
"exportedSymbols": {
"Counter": [47]
},
@ -617,7 +617,7 @@
"src": "0:461:0"
},
"legacyAST": {
"absolutePath": "/Users/gupadhyaya/go/src/github.com/woop-chain/counter/contracts/Counter.sol",
"absolutePath": "/Users/gupadhyaya/go/src/github.com/harmony-one/counter/contracts/Counter.sol",
"exportedSymbols": {
"Counter": [47]
},

@ -1,27 +1,27 @@
# @woop-js/contract
# @harmony-js/contract
This package provides a collection of apis to create, deploy, and interact with smart contracts. In Woop, smart contracts all fully EVM compatible and the formats and terminologies match 1-to-1 with EVM smart contracts.
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.
## Installation
```
npm install @woop-js/contract
npm install @harmony-js/contract
```
## Usage
Deploying a contract using `contractConstructor`
```javascript
const { ContractFactory } = require('@woop-js/contract');
const { Wallet } = require('@woop-js/account');
const { Messenger, HttpProvider } = require('@woop-js/network');
const { ChainID, ChainType, hexToNumber } = require('@woop-js/utils');
const { ContractFactory } = require('@harmony-js/contract');
const { Wallet } = require('@harmony-js/account');
const { Messenger, HttpProvider } = require('@harmony-js/network');
const { ChainID, ChainType, hexToNumber } = require('@harmony-js/utils');
const wallet = new Wallet(
new Messenger(
new HttpProvider('https://api.s0.b.hmny.io'),
ChainType.Woop,
ChainID.WikiTestnet,
ChainType.Harmony,
ChainID.HmyTestnet,
),
);
const factory = new ContractFactory(wallet);
@ -47,31 +47,31 @@ Instead of `contract.methods.contractConstructor`, `contract.deploy` could be us
Loading a contract object using the contract json and contract address for interacting with it
```javascript
const { Woop } = require("@woop-js/core");
const { ChainID, ChainType } = require("@woop-js/utils");
const wiki = new Woop("https://api.s0.b.hmny.io", {
chainType: ChainType.Woop,
chainId: ChainID.WikiTestnet,
const { Harmony } = require("@harmony-js/core");
const { ChainID, ChainType } = require("@harmony-js/utils");
const hmy = new Harmony("https://api.s0.b.hmny.io", {
chainType: ChainType.Harmony,
chainId: ChainID.HmyTestnet,
});
const contractJson = require("./Counter.json");
const contractAddr = "0x19f64050e6b2d376e52AC426E366c49EEb0724B1";
const contract = wiki.contracts.createContract(contractJson.abi, contractAddr);
const contract = hmy.contracts.createContract(contractJson.abi, contractAddr);
console.log(contract.methods);
```
Directly loading contract using `ContractFactory`
```javascript
const { ContractFactory } = require('@woop-js/contract');
const { Wallet } = require('@woop-js/account');
const { Messenger, HttpProvider } = require('@woop-js/network');
const { ChainID, ChainType, hexToNumber } = require('@woop-js/utils');
const { ContractFactory } = require('@harmony-js/contract');
const { Wallet } = require('@harmony-js/account');
const { Messenger, HttpProvider } = require('@harmony-js/network');
const { ChainID, ChainType, hexToNumber } = require('@harmony-js/utils');
const wallet = new Wallet(new Messenger(
new HttpProvider('https://api.s0.b.hmny.io'),
ChainType.Woop,
ChainID.WikiTestnet,
ChainType.Harmony,
ChainID.HmyTestnet,
));
const factory = new ContractFactory(wallet);
const contract = factory.createContract(contractJson.abi, contractAddr);
@ -86,7 +86,7 @@ contract.methods.getCount().estimateGas(options1).then(gas => {
});
```
Call contract read-only methods. Woop uses 1 Gwei gas price and gas limit of 21000 by default. Use the estimate gas api to correctly set the gas limit.
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
const options1 = { gasPrice: '0x3B9ACA00' }; // gas price in hex corresponds to 1 Gwei or 1000000000
let options2 = { gasPrice: 1000000000, gasLimit: 21000 }; // setting the default gas limit, but changing later based on estimate gas
@ -118,17 +118,17 @@ 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('@woop-js/contract');
const { Wallet } = require('@woop-js/account');
const { Messenger, WSProvider } = require('@woop-js/network');
const { ChainID, ChainType, hexToNumber } = require('@woop-js/utils');
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.Woop,
ChainID.WikiTestnet,
ChainType.Harmony,
ChainID.HmyTestnet,
),
);
const factory = new ContractFactory(wallet);

@ -1,7 +1,7 @@
{
"name": "@woop-js/contract",
"version": "0.1.58",
"description": "contract libraries for woop",
"name": "@harmony-js/contract",
"version": "0.1.53",
"description": "contract libraries for harmony",
"main": "dist/index.js",
"node": "dist/index.js",
"browser": "dist/index.js",
@ -18,11 +18,11 @@
},
"license": "MIT",
"dependencies": {
"@woop-js/account": "0.1.58",
"@woop-js/crypto": "0.1.58",
"@woop-js/network": "0.1.58",
"@woop-js/transaction": "0.1.58",
"@woop-js/utils": "0.1.58"
"@harmony-js/account": "0.1.46",
"@harmony-js/crypto": "0.1.48",
"@harmony-js/network": "0.1.51",
"@harmony-js/transaction": "0.1.51",
"@harmony-js/utils": "0.1.48"
},
"gitHead": "56606e9365721729a490c27d6a294e0daf90fbdf"
}

@ -1,154 +1,113 @@
/**
# @woop-js/contract
This package provides a collection of apis to create, deploy, and interact with smart contracts. In Woop, smart contracts all fully EVM compatible and the formats and terminologies match 1-to-1 with EVM smart contracts.
## Installation
```
npm install @woop-js/contract
```
## Usage
Deploying a contract using `contractConstructor`
```javascript
const { ContractFactory } = require('@woop-js/contract');
const { Wallet } = require('@woop-js/account');
const { Messenger, HttpProvider } = require('@woop-js/network');
const { ChainID, ChainType, hexToNumber } = require('@woop-js/utils');
* const wallet = new Wallet(
* new Messenger(
* new HttpProvider('https://api.s0.b.hmny.io'),
* ChainType.Woop,
* ChainID.WikiTestnet,
* ),
* );
* const factory = new ContractFactory(wallet);
* const contractJson = require("./Counter.json");
* const contract = factory.createContract(contractJson.abi);
* const options1 = { gasPrice: '0x3B9ACA00' }; // gas price in hex corresponds to 1 Gwei or 1000000000
* let options2 = { gasPrice: 1000000000, gasLimit: 21000 }; // setting the default gas limit, but changing later based on estimate gas
* const options3 = { data: contractJson.bytecode }; // contractConstructor needs contract bytecode to deploy
* contract.wallet.addByPrivateKey('1f054c21a0f57ebc402c00e14bd1707ddf45542d4ed9989933dbefc4ea96ca68');
* 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);
* });
* });
```
Instead of `contract.methods.contractConstructor`, `contract.deploy` could be used and it will work.
Loading a contract object using the contract json and contract address for interacting with it
```javascript
* const { Woop } = require("@woop-js/core");
* const { ChainID, ChainType } = require("@woop-js/utils");
* const wiki = new Woop("https://api.s0.b.hmny.io", {
* chainType: ChainType.Woop,
* chainId: ChainID.WikiTestnet,
* });
const contractJson = require("./Counter.json");
const contractAddr = "0x19f64050e6b2d376e52AC426E366c49EEb0724B1";
const contract = wiki.contracts.createContract(contractJson.abi, contractAddr);
console.log(contract.methods);
```
Directly loading contract using `ContractFactory`
```javascript
const { ContractFactory } = require('@woop-js/contract');
const { Wallet } = require('@woop-js/account');
const { Messenger, HttpProvider } = require('@woop-js/network');
const { ChainID, ChainType, hexToNumber } = require('@woop-js/utils');
* const wallet = new Wallet(new Messenger(
* new HttpProvider('https://api.s0.b.hmny.io'),
* ChainType.Woop,
* ChainID.WikiTestnet,
* ));
const factory = new ContractFactory(wallet);
const contract = factory.createContract(contractJson.abi, contractAddr);
```
Estimate gas for contract methods
```javascript
* const options1 = { gasPrice: '0x3B9ACA00' }; // gas price in hex corresponds to 1 Gwei or 1000000000
* contract.methods.getCount().estimateGas(options1).then(gas => {
* console.log('gas required for getCount is ' + hexToNumber(gas));
* });
```
Call contract read-only methods. Woop uses 1 Gwei gas price and gas limit of 21000 by default. Use the estimate gas api to correctly set the gas limit.
```javascript
* const options1 = { gasPrice: '0x3B9ACA00' }; // gas price in hex corresponds to 1 Gwei or 1000000000
* let options2 = { gasPrice: 1000000000, gasLimit: 21000 }; // setting the default gas limit, but changing later based on estimate gas
* contract.methods.getCount().estimateGas(options1).then(gas => {
* options2 = {...options2, gasLimit: hexToNumber(gas)};
* contract.methods.getCount().call(options2).then(count => {
* console.log('counter value: ' + count);
* });
* });
```
Invoking contract modification methods using `send` api. Need to add a signing account to the contract wallet, otherwise `send` api will not work.
```javascript
* const options1 = { gasPrice: '0x3B9ACA00' }; // gas price in hex corresponds to 1 Gwei or 1000000000
* let options2 = { gasPrice: 1000000000, gasLimit: 21000 }; // setting the default gas limit, but changing later based on estimate gas
* 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('@woop-js/contract');
* const { Wallet } = require('@woop-js/account');
* const { Messenger, WSProvider } = require('@woop-js/network');
* const { ChainID, ChainType, hexToNumber } = require('@woop-js/utils');
* const ws = new WSProvider('wss://ws.s0.b.hmny.io');
* const wallet = new Wallet(
* new Messenger(
* ws,
* ChainType.Woop,
* ChainID.WikiTestnet,
* ),
* );
* 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);
```
* ## About this package
*
* `@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.
*
* ## How to use this package
*
* ### Deploy a contract to blockchain
* ```javascript
* // Step 1: Use Solidity to build a sample contract instance
* contract Inbox {
* string public message;
* constructor() public {
* message = "hello";
* }
* function setMessage(string memory newMessage) public {
* message = newMessage;
* }
* }
*
* // Step 2: Use truffle to compile the contract
* $ truffle compile
*
* // Step 3: Use truffle to deploy the contract (by truffle)
* $ truffle migrate --network local --reset
* $ 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)
*
* ### Interact with the contract
* ```javascript
* // Step 1: create a harmony instance
* const { Harmony } = require('@harmony-js/core');
* const { ChainID, ChainType } = require('@harmony-js/utils');
* const hmy = new Harmony(
* // let's assume we deploy smart contract to this end-point URL
* 'https://api.s0.b.hmny.io'
* {
* chainType: ChainType.Harmony,
* chainId: ChainID.HmyLocal,
* }
* )
*
* // Step 2: get a contract instance
* const getContractInstance = (hmy, artifact) => {
* return hmy.contracts.createContract(artifact.abi, address);
* }
* const inbox = getContractInstance(hmy, inboxJson)
*
* // Step 3: interact with the instance
* // Example 1: methods.myMethod.call()
* const message = await inbox.methods.message().call();
* console.log(message);
*
* // Example 2: methods.myMethod.send()
* inbox.methods.setMessage('666').send({
* gasLimit: '1000001',
* gasPrice: new hmy.utils.Unit('10').asGwei().toWei(),
* });
* ```
*
* ### Integrate MathWallet
* Using MathWallet to sign Transaction
* ```javascript
* // Step 0: set up MathWallet extension on Chrome
*
* // Step 1: Create a harmonyExtension instance
* const { Harmony, HarmonyExtension } = require('@harmony-js/core');
* let hmyEx, ExContract;
* export const initExtension = async() => {
* hmyEx = await new HarmonyExtension(window.harmony);
*
* exContract = hmyEx.contracts.createContract(abi, address);
* return exContract;
* };
*
* // Step 2: interact with hmyEx instance
* // wait for hmy inject into window
* async componentDidMount() {
* ...
* await waitForInjected()
* ...
* }
* // Example: methods.myMethod.send()
* onSubmit = async event => {
* const exContract = await initExtension()
* await exContract.methods.Mymethod().send({
* value: new hmy.utils.Unit('1').asOne().toWei(),
* })
* }
*
* // wait for injected
* export const waitForInjected = () => new Promise((resolve) => {
* const check = () => {
* if (!window.harmony) setTimeout(check, 250);
* else resolve(window.harmony);
* }
* check();
* });
* ```
*
* ## [More Examples: HRC repo](https://github.com/harmony-one/HRC/tree/master/examples)
* - Lottery
* - HRC 20
* - HRC 721
* - Node-dao
* - Node-faucet
*
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
*/
// this file is mainly ported from `ethers.js`, but done some fixes
@ -171,8 +130,8 @@ import {
Arrayish,
checkNew,
bytesPadRight,
} from '@woop-js/crypto';
import { hexToBN, defineReadOnly } from '@woop-js/utils';
} from '@harmony-js/crypto';
import { hexToBN, defineReadOnly } from '@harmony-js/utils';
/** @hidden */
const NegativeOne: BN = new BN(-1);
@ -724,12 +683,7 @@ class CoderNumber extends Coder {
encode(value: BN | number | string): Uint8Array {
let result;
try {
let v: BN;
if (typeof value == 'string' && value.startsWith('0x')) {
v = new BN(value.slice(2), 'hex');
} else {
v = new BN(value);
}
let v = new BN(value);
if (this.signed) {
let bounds = MaxUint256.maskn(this.size * 8 - 1);
if (v.gt(bounds)) {

@ -1,12 +1,12 @@
/**
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
* @hidden
*/
import { AbiCoder as ABICoder, ParamType, toUtf8Bytes } from './abiCoder';
import { isObject, isArray } from '@woop-js/utils';
import { keccak256, Arrayish } from '@woop-js/crypto';
import { isObject, isArray } from '@harmony-js/utils';
import { keccak256, Arrayish } from '@harmony-js/crypto';
import { jsonInterfaceMethodToString, bnToString } from './utils';
export class AbiCoderClass {

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
* @hidden
*/

@ -1,11 +1,11 @@
/**
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
* @hidden
*/
import { isObject, isArray } from '@woop-js/utils';
import { BN } from '@woop-js/crypto';
import { isObject, isArray } from '@harmony-js/utils';
import { BN } from '@harmony-js/crypto';
export const jsonInterfaceMethodToString = (json: any): string => {
if (isObject(json) && json.name && json.name.includes('(')) {

@ -1,12 +1,12 @@
/**
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
*
*/
import { Wallet } from '@woop-js/account';
import { Messenger } from '@woop-js/network';
import { Transaction } from '@woop-js/transaction';
import { Wallet } from '@harmony-js/account';
import { Messenger } from '@harmony-js/network';
import { Transaction } from '@harmony-js/transaction';
import { AbiCoder } from './abi/index';
import { abiMapper } from './utils/mapper';
import { ContractOptions } from './utils/options';
@ -20,9 +20,6 @@ import { ContractStatus } from './utils/status';
export class Contract {
methods: any;
events: any;
fallback: any = undefined;
receive: any = undefined;
abi: any = [];
abiModel: any | AbiModel;
abiCoder: AbiCoderClass;
options: ContractOptions | any;
@ -30,8 +27,6 @@ export class Contract {
transaction?: Transaction;
status: ContractStatus;
shardID: number;
errorFunc: string = 'Error(string)';
errorFuncSig: string;
constructor(
abi: any = [],
@ -41,7 +36,6 @@ export class Contract {
status: ContractStatus = ContractStatus.INITIALISED,
) {
// super();
this.abi = abi;
this.abiCoder = AbiCoder();
this.abiModel = abiMapper(abi, this.abiCoder);
this.options = options;
@ -53,7 +47,6 @@ export class Contract {
this.runMethodFactory();
this.runEventFactory();
this.status = status;
this.errorFuncSig = this.abiCoder.encodeFunctionSignature(this.errorFunc);
// tslint:disable-next-line: no-unused-expression
}
isInitialised() {
@ -118,7 +111,7 @@ export class Contract {
connect(wallet: Wallet): void {
this.wallet = wallet;
}
setMessenger(messenger: Messenger) {
setMessegner(messenger: Messenger) {
if (this.wallet instanceof Wallet) {
this.wallet.setMessenger(messenger);
} else {

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

@ -1,9 +1,9 @@
/**
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
*/
import { LogSub } from '@woop-js/network';
import { LogSub } from '@harmony-js/network';
import { AbiItemModel } from '../models/types';
import { Contract } from '../contract';
import { decode as eventLogDecoder } from '../utils/decoder';

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

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
* @hidden
*/

@ -1,18 +1,20 @@
/**
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
*/
import { Wallet } from '@woop-js/account';
import { TransactionFactory, Transaction, TxStatus } from '@woop-js/transaction';
import { RPCMethod, getResultForData, Emitter } from '@woop-js/network';
import { hexToBN, Unit } from '@woop-js/utils';
import { getAddress } from '@woop-js/crypto';
import { Wallet } from '@harmony-js/account';
import { TransactionFactory, Transaction, TxStatus } from '@harmony-js/transaction';
import { RPCMethod, getResultForData, Emitter } from '@harmony-js/network';
import { hexToNumber, hexToBN } from '@harmony-js/utils';
import { getAddress } from '@harmony-js/crypto';
import { AbiItemModel } from '../models/types';
import { Contract } from '../contract';
import { methodEncoder } from '../utils/encoder';
import { ContractStatus } from '../utils/status';
// todo: have to judge if it is contractConstructor
export class ContractMethod {
contract: Contract;
params: any;
@ -34,11 +36,8 @@ export class ContractMethod {
this.callResponse = undefined;
}
send(params: any): Emitter {
if (params && !params.gasLimit) {
params.gasLimit = params.gas;
}
try {
let gasLimit: any = params.gasLimit; // change by estimateGas
let gasLimit: any;
const signTxs = () => {
this.transaction = this.transaction.map((tx: any) => {
return { ...tx, ...params, gasLimit };
@ -46,30 +45,28 @@ export class ContractMethod {
const waitConfirm: boolean = params && params.waitConfirm === false ? false : true;
const updateNonce: boolean = params && params.nonce !== undefined ? false : true;
this.signTransaction(updateNonce)
.then((signed) => {
this.sendTransaction(signed).then((sent) => {
const [txn, id] = sent;
this.transaction = txn;
this.contract.transaction = this.transaction;
if (this.transaction.isRejected()) {
this.transaction.emitter.reject(id); // in this case, id is error message
} else if (waitConfirm) {
this.confirm(id).then(() => {
this.transaction.emitter.resolve(this.contract);
});
} else {
this.signTransaction(updateNonce).then((signed) => {
this.sendTransaction(signed).then((sent) => {
const [txn, id] = sent;
this.transaction = txn;
this.contract.transaction = this.transaction;
if (waitConfirm) {
this.confirm(id).then(() => {
this.transaction.emitter.resolve(this.contract);
}
});
})
.catch((error) => {
this.transaction.emitter.reject(error);
});
} else {
this.transaction.emitter.resolve(this.contract);
}
});
});
};
// tslint:disable-next-line: prefer-conditional-expression
if (params !== undefined) {
gasLimit = params.gas || params.gasLimit;
}
if (gasLimit === undefined) {
this.estimateGas(params).then((gas) => {
this.estimateGas().then((gas) => {
gasLimit = hexToBN(gas);
signTxs();
});
@ -82,20 +79,38 @@ export class ContractMethod {
}
}
async call(options: any, blockNumber: any = 'latest') {
if (options && !options.gasLimit) {
options.gasLimit = options.gas;
}
try {
options = { ...this.contract.options, ...options };
const shardID =
options !== undefined && options.shardID !== undefined
? options.shardID
: this.contract.shardID;
const nonce = '0x0';
let gasLimit: any;
// tslint:disable-next-line: prefer-conditional-expression
if (options !== undefined) {
gasLimit = options.gas || options.gasLimit;
} else {
gasLimit = '21000000';
}
let from: string;
// tslint:disable-next-line: prefer-conditional-expression
if (this.wallet.signer) {
from = options && options.from ? options.from : this.wallet.signer.address;
} else {
from =
options && options.from ? options.from : '0x0000000000000000000000000000000000000000';
}
this.transaction = this.transaction.map((tx: any) => {
return {
...tx,
...options,
nonce: 0,
from: from || tx.from,
gasPrice: options ? options.gasPrice : tx.gasPrice,
gasLimit: gasLimit || tx.gasLimit,
nonce: Number.parseInt(hexToNumber(nonce), 10),
};
});
const keys: string[] = Object.keys(this.transaction.txPayload);
@ -158,29 +173,36 @@ export class ContractMethod {
}
}
async estimateGas(options: any) {
async estimateGas(
params: {
from?: string;
to?: string;
gas?: string;
gasPrice?: string;
value?: string;
data?: string;
} = {},
) {
try {
interface Payload {
[key: string]: any;
if (params.from === undefined && this.contract.options.from !== undefined) {
params.from = this.contract.options.from;
}
const estPayload: Payload = {};
const txPayload: Payload = this.transaction.txPayload;
const keys: string[] = ['from', 'to', 'gasPrice', 'value', 'data'];
for (const key of keys) {
if (options && options[key]) {
estPayload[key] = options[key];
} else if (txPayload[key] !== '0x') {
estPayload[key] = txPayload[key];
}
if (params.to === undefined && this.transaction.txParams.to !== undefined) {
params.to = this.transaction.txParams.to;
}
if (params.data === undefined) {
params.data = this.transaction.txParams.data;
}
if (params.gasPrice === undefined && this.contract.options.gasPrice !== undefined) {
params.gasPrice = this.contract.options.gasPrice;
}
if (this.abiItem.isOfType('constructor')) {
delete estPayload.to;
if (this.methodKey === 'contractConstructor') {
delete params.to;
}
const result = getResultForData(
// tslint:disable-line
await (<Wallet>this.wallet).messenger.send(RPCMethod.EstimateGas, [estPayload]),
await (<Wallet>this.wallet).messenger.send(RPCMethod.EstimateGas, [params]),
);
if (result.responseType === 'error') {
@ -224,7 +246,7 @@ export class ContractMethod {
'rlp',
'latest', // 'pending',
);
if (this.abiItem.isOfType('constructor')) {
if (this.methodKey === 'contractConstructor') {
this.contract.address = TransactionFactory.getContractAddress(signed);
}
this.contract.setStatus(ContractStatus.SIGNED);
@ -252,7 +274,7 @@ export class ContractMethod {
);
if (result.receipt && result.txStatus === TxStatus.CONFIRMED) {
if (this.abiItem.isOfType('constructor')) {
if (this.methodKey === 'contractConstructor') {
this.contract.setStatus(ContractStatus.DEPLOYED);
} else {
this.contract.setStatus(ContractStatus.CALLED);
@ -267,7 +289,7 @@ export class ContractMethod {
protected createTransaction() {
if (this.wallet.messenger) {
if (this.abiItem.isOfType('constructor')) {
if (this.methodKey === 'contractConstructor') {
// tslint:disable-next-line: no-string-literal
this.contract.data = this.params[0]['data'] || '0x';
@ -277,19 +299,16 @@ export class ContractMethod {
} else {
this.abiItem.contractMethodParameters = this.params || [];
}
const defaultOptions = {
gasLimit: new Unit(21000000).asWei().toWei(),
gasPrice: new Unit(1).asGwei().toWei(),
};
const txObject = {
...defaultOptions,
...this.contract.options,
...this.params[0],
to: this.abiItem.isOfType('constructor')
? '0x'
: getAddress(this.contract.address).checksum,
to:
this.methodKey === 'contractConstructor'
? '0x'
: getAddress(this.contract.address).checksum,
data: this.encodeABI(),
};
// tslint:disable-line
const result = new TransactionFactory((<Wallet>this.wallet).messenger).newTx(txObject);
@ -300,32 +319,11 @@ export class ContractMethod {
}
protected afterCall(response: any) {
// length of `0x${methodSig}` is 2+4*2=10
if (response.length % 32 === 10 && response.startsWith(this.contract.errorFuncSig)) {
const errmsg = this.contract.abiCoder.decodeParameters(
[{ type: 'string' }],
'0x' + response.slice(10),
);
throw { revert: errmsg[0] };
}
if (
this.abiItem.isOfType('constructor') ||
this.abiItem.isOfType('fallback') ||
this.abiItem.isOfType('receive')
) {
return response;
if (!response || response === '0x') {
return null;
}
const outputs = this.abiItem.getOutputs();
if (outputs.length === 0) {
// if outputs is empty, we can't know the call is revert or not
return response;
}
if (!response || response === '0x') {
// if outputs isn't empty, treat it as revert
throw { revert: response };
}
if (outputs.length > 1) {
return this.contract.abiCoder.decodeParameters(outputs, response);
}

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
* @hidden
*/
@ -31,14 +31,6 @@ export class MethodFactory {
Object.assign(this.contract.methods, newObject);
});
if (this.abiModel.hasFallback()) {
this.contract.fallback = (calldata: string) =>
new ContractMethod('fallback', [calldata], this.abiModel.getFallback(), this.contract);
}
if (this.abiModel.hasReceive()) {
this.contract.receive = () =>
new ContractMethod('receive', [], this.abiModel.getReceive(), this.contract);
}
return this.contract;
}
/**

@ -1,10 +1,10 @@
/**
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
* @hidden
*/
import { isArray } from '@woop-js/utils';
import { isArray } from '@harmony-js/utils';
import { AbiItemModel, AbiOutput, AbiInput } from './types';
export class AbiItem {

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
* @hidden
*/
@ -33,20 +33,6 @@ export class AbiModel {
return false;
}
getFallback(): AbiItemModel | false {
if (this.hasFallback()) {
return this.abi.fallback;
}
return false;
}
getReceive(): AbiItemModel | false {
if (this.hasReceive()) {
return this.abi.receive;
}
return false;
}
getEvents(): AbiItemModel[] {
return this.abi.events;
}
@ -67,14 +53,6 @@ export class AbiModel {
return typeof this.abi.methods[name] !== 'undefined';
}
hasFallback(): boolean {
return typeof this.abi.fallback !== 'undefined';
}
hasReceive(): boolean {
return typeof this.abi.receive !== 'undefined';
}
hasEvent(name: string): boolean {
return typeof this.abi.events[name] !== 'undefined';
}

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
* @hidden
*/

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
* @hidden
*/

@ -1,10 +1,10 @@
/**
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
* @hidden
*/
import { isArray } from '@woop-js/utils';
import { isArray } from '@harmony-js/utils';
import { AbiItemModel } from '../models/types';
import { AbiCoderClass } from '../abi/api';
@ -13,15 +13,6 @@ export const methodEncoder = (
abiItemModel: AbiItemModel,
deployData: string,
) => {
if (abiItemModel.isOfType('receive')) {
return undefined;
}
if (abiItemModel.isOfType('fallback')) {
return abiItemModel.contractMethodParameters.length
? abiItemModel.contractMethodParameters[0]
: undefined;
}
let encodedParameters = abiCoder.encodeParameters(
abiItemModel.getInputs(),
abiItemModel.contractMethodParameters,

@ -1,10 +1,10 @@
/**
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
* @hidden
*/
import { hexlify, isHexString, keccak256, toChecksumAddress } from '@woop-js/crypto';
import { hexlify, isHexString, keccak256, toChecksumAddress } from '@harmony-js/crypto';
import {
numberToHex,
isArray,
@ -12,7 +12,7 @@ import {
isString,
isAddress,
hexToBN,
} from '@woop-js/utils';
} from '@harmony-js/utils';
import { toUtf8Bytes } from '../abi/abiCoder';
export const inputLogFormatter = (options: any) => {

@ -1,10 +1,10 @@
/**
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
* @hidden
*/
import { isArray } from '@woop-js/utils';
import { isArray } from '@harmony-js/utils';
import { AbiItem } from '../models/AbiItemModel';
import { AbiModel } from '../models/AbiModel';
import { AbiItemModel } from '../models/types';
@ -15,8 +15,6 @@ export const abiMapper = (abi: any[], abiCoder: AbiCoderClass): AbiModel => {
const mappedAbiItems: any = {
methods: {},
events: {},
fallback: undefined,
receive: undefined,
};
let hasConstructor = false;
@ -72,11 +70,6 @@ export const abiMapper = (abi: any[], abiCoder: AbiCoderClass): AbiModel => {
mappedAbiItems.events[abiItem.funcName] = abiItemModel;
}
if (abiItem.type === 'fallback' || abiItem.type === 'receive') {
abiItem.signature = abiItem.type;
mappedAbiItems[abiItem.type] = new AbiItem(abiItem);
}
if (abiItem.type === 'constructor') {
abiItem.signature = abiItem.type;
// tslint:disable-next-line: no-string-literal

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
* @hidden
*/

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-contract
* @module harmony-contract
* @hidden
*/

@ -4,8 +4,8 @@
*/
import { AbiCoder } from '../src/abi/abiCoder';
import { BN } from '@woop-js/crypto';
import { isArray } from '@woop-js/utils';
import { BN } from '@harmony-js/crypto';
import { isArray } from '@harmony-js/utils';
import { abis } from './fixtures/abiv2';
function getValues(object: any, format?: any, named?: any): any {

@ -6,10 +6,10 @@
},
"include": ["src", "../../typings/**/*.d.ts"],
"references": [
{"path": "../woop-account"},
{"path": "../woop-crypto"},
{"path": "../woop-utils"},
{"path": "../woop-transaction"},
{"path": "../woop-network"}
{"path": "../harmony-account"},
{"path": "../harmony-crypto"},
{"path": "../harmony-utils"},
{"path": "../harmony-transaction"},
{"path": "../harmony-network"}
]
}

@ -1,19 +1,19 @@
# @woop-js/core
# @harmony-js/core
This package provides a collection of apis to interact with Woop blockchain.
This package provides a collection of apis to interact with Harmony blockchain.
## Installation
```
npm install @woop-js/core
npm install @harmony-js/core
```
## Usage
Create a Woop instance connecting to testnet
Create a Harmony instance connecting to testnet
```javascript
const { Woop } = require('@woop-js/core');
const { Harmony } = require('@harmony-js/core');
const {
ChainID,
ChainType,
@ -22,20 +22,20 @@ const {
fromWei,
Units,
Unit,
} = require('@woop-js/utils');
} = require('@harmony-js/utils');
const wiki = new Woop(
const hmy = new Harmony(
'https://api.s0.b.hmny.io/',
{
chainType: ChainType.Woop,
chainId: ChainID.WikiTestnet,
chainType: ChainType.Harmony,
chainId: ChainID.HmyTestnet,
},
);
```
Getting balance of account `one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7`
```javascript
wiki.blockchain
hmy.blockchain
.getBalance({ address: 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7' })
.then((response) => {
console.log('balance in ONEs: ' + fromWei(hexToNumber(response.result), Units.one));
@ -44,14 +44,14 @@ wiki.blockchain
Getting the latest block number
```javascript
wiki.blockchain.getBlockNumber().then((response) => {
hmy.blockchain.getBlockNumber().then((response) => {
console.log('current block number: ' + hexToNumber(response.result));
});
```
Getting the block using block hash
```javascript
wiki.blockchain
hmy.blockchain
.getBlockByHash({
blockHash: '0x08c46ae7249362a7d1f602d44c5a81f33ebdab6a7dcb6068f99610b57911aafd',
})
@ -62,7 +62,7 @@ wiki.blockchain
Getting the block using block number
```javascript
wiki.blockchain
hmy.blockchain
.getBlockByNumber({
blockNumber: numberToHex(422635),
})
@ -73,7 +73,7 @@ wiki.blockchain
Getting the transaction using hash
```javascript
wiki.blockchain
hmy.blockchain
.getTransactionByHash({
txnHash: '0x56c73eb993b18dc04baacec5c2e9d1292a090f6a978a4a1c461db5255fcbc831',
})
@ -84,7 +84,7 @@ wiki.blockchain
Getting the transaction receipt
```javascript
wiki.blockchain
hmy.blockchain
.getTransactionReceipt({
txnHash: '0x56c73eb993b18dc04baacec5c2e9d1292a090f6a978a4a1c461db5255fcbc831',
})
@ -95,7 +95,7 @@ wiki.blockchain
Getting the cross-shard transaction receipt
```javascript
wiki.blockchain
hmy.blockchain
.getCxReceiptByHash({
txnHash: '0xcd36a90ff5d5373285c2896ba7bbcd3f5324263c0cb8ecfb7cad2f5fc2fbdbda',
shardID: 1,
@ -107,7 +107,7 @@ wiki.blockchain
Getting the deployed smart contract code
```javascript
wiki.blockchain
hmy.blockchain
.getCode({
address: '0x08AE1abFE01aEA60a47663bCe0794eCCD5763c19',
blockNumber: 'latest',
@ -119,7 +119,7 @@ wiki.blockchain
Getting the transaction count of an account
```javascript
wiki.blockchain
hmy.blockchain
.getTransactionCount({
address: 'one1pdv9lrdwl0rg5vglh4xtyrv3wjk3wsqket7zxy',
})
@ -130,7 +130,7 @@ wiki.blockchain
Getting the shard structure and details
```javascript
wiki.blockchain.getShardingStructure().then((response) => {
hmy.blockchain.getShardingStructure().then((response) => {
console.log(response.result);
});
```
@ -138,10 +138,10 @@ wiki.blockchain.getShardingStructure().then((response) => {
Transferring funds using `sendTransaction`
```javascript
// key corresponds to one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7, only has testnet balance
wiki.wallet.addByPrivateKey('45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e');
hmy.wallet.addByPrivateKey('45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e');
async function transfer() {
const txn = wiki.transactions.newTx({
const txn = hmy.transactions.newTx({
to: 'one166axnkjmghkf3df7xfvd0hn4dft8kemrza4cd2',
value: new Unit(1).asOne().toWei(),
// gas limit, you can use string
@ -151,12 +151,12 @@ async function transfer() {
// 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 wiki.utils.Unit('1').asGwei().toWei(),
gasPrice: new hmy.utils.Unit('1').asGwei().toWei(),
});
// sign the transaction use wallet;
const signedTxn = await wiki.wallet.signTransaction(txn);
const txnHash = await wiki.blockchain.sendTransaction(signedTxn);
const signedTxn = await hmy.wallet.signTransaction(txn);
const txnHash = await hmy.blockchain.sendTransaction(signedTxn);
console.log(txnHash.result);
}

@ -1,7 +1,7 @@
{
"name": "@woop-js/core",
"version": "0.1.58",
"description": "woop core package",
"name": "@harmony-js/core",
"version": "0.1.53",
"description": "harmony core package",
"main": "dist/index.js",
"node": "dist/index.js",
"browser": "dist/index.js",
@ -18,13 +18,13 @@
"author": "neeboo@firestack.one",
"license": "MIT",
"dependencies": {
"@woop-js/account": "0.1.58",
"@woop-js/contract": "0.1.58",
"@woop-js/crypto": "0.1.58",
"@woop-js/network": "0.1.58",
"@woop-js/staking": "0.1.58",
"@woop-js/transaction": "0.1.58",
"@woop-js/utils": "0.1.58"
"@harmony-js/account": "0.1.53",
"@harmony-js/contract": "0.1.53",
"@harmony-js/crypto": "0.1.48",
"@harmony-js/network": "0.1.51",
"@harmony-js/staking": "0.1.51",
"@harmony-js/transaction": "0.1.51",
"@harmony-js/utils": "0.1.48"
},
"gitHead": "56606e9365721729a490c27d6a294e0daf90fbdf"
}

@ -1,171 +1,86 @@
/**
# @woop-js/core
This package provides a collection of apis to interact with Woop blockchain.
## Installation
```
npm install @woop-js/core
```
## Usage
Create a Woop instance connecting to testnet
```javascript
* const { Woop } = require('@woop-js/core');
* const {
* ChainID,
* ChainType,
* hexToNumber,
* numberToHex,
* fromWei,
* Units,
* Unit,
* } = require('@woop-js/utils');
* const wiki = new Woop(
* 'https://api.s0.b.hmny.io/',
* {
* chainType: ChainType.Woop,
* chainId: ChainID.WikiTestnet,
* },
* );
```
Getting balance of account `one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7`
```javascript
* wiki.blockchain
* .getBalance({ address: 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7' })
* .then((response) => {
* console.log('balance in ONEs: ' + fromWei(hexToNumber(response.result), Units.one));
* });
```
Getting the latest block number
```javascript
* wiki.blockchain.getBlockNumber().then((response) => {
* console.log('current block number: ' + hexToNumber(response.result));
* });
```
Getting the block using block hash
```javascript
* wiki.blockchain
* .getBlockByHash({
* blockHash: '0x08c46ae7249362a7d1f602d44c5a81f33ebdab6a7dcb6068f99610b57911aafd',
* })
* .then((response) => {
* console.log(response.result);
* });
```
Getting the block using block number
```javascript
* wiki.blockchain
* .getBlockByNumber({
* blockNumber: numberToHex(422635),
* })
* .then((response) => {
* console.log(response.result);
* });
```
Getting the transaction using hash
```javascript
* wiki.blockchain
* .getTransactionByHash({
* txnHash: '0x56c73eb993b18dc04baacec5c2e9d1292a090f6a978a4a1c461db5255fcbc831',
* })
* .then((response) => {
* console.log(response.result);
* });
```
Getting the transaction receipt
```javascript
* wiki.blockchain
* .getTransactionReceipt({
* txnHash: '0x56c73eb993b18dc04baacec5c2e9d1292a090f6a978a4a1c461db5255fcbc831',
* })
* .then((response) => {
* console.log(response.result);
* });
```
Getting the cross-shard transaction receipt
```javascript
* wiki.blockchain
* .getCxReceiptByHash({
* txnHash: '0xcd36a90ff5d5373285c2896ba7bbcd3f5324263c0cb8ecfb7cad2f5fc2fbdbda',
* shardID: 1,
* })
* .then((value) => {
* console.log(value.result);
* });
```
Getting the deployed smart contract code
```javascript
* wiki.blockchain
* .getCode({
* address: '0x08AE1abFE01aEA60a47663bCe0794eCCD5763c19',
* blockNumber: 'latest',
* })
* .then((response) => {
* console.log(response.result);
* });
```
Getting the transaction count of an account
```javascript
* wiki.blockchain
* .getTransactionCount({
* address: 'one1pdv9lrdwl0rg5vglh4xtyrv3wjk3wsqket7zxy',
* })
* .then((response) => {
* console.log(hexToNumber(response.result));
* });
```
Getting the shard structure and details
```javascript
* wiki.blockchain.getShardingStructure().then((response) => {
* console.log(response.result);
* });
```
Transferring funds using `sendTransaction`
```javascript
// key corresponds to one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7, only has testnet balance
* wiki.wallet.addByPrivateKey('45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e');
* async function transfer() {
* const txn = wiki.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 wiki.utils.Unit('1').asGwei().toWei(),
* });
* // sign the transaction use wallet;
* const signedTxn = await wiki.wallet.signTransaction(txn);
* const txnHash = await wiki.blockchain.sendTransaction(signedTxn);
* console.log(txnHash.result);
* }
* transfer();
```
* ## 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
* 'https://api.s0.b.hmny.io/',
* {
* // chainType set to Harmony
* chainType: ChainType.Harmony,
* // chainType set to HmyLocal
* chainId: ChainID.HmyLocal,
* },
* );
* ```
*
* ### 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 woop-core
* @module harmony-core
*/
import {
@ -177,19 +92,19 @@ import {
NewHeaders,
LogSub,
Syncing,
} from '@woop-js/network';
} from '@harmony-js/network';
import {
assertObject,
AssertType,
// WoopCore,
// HarmonyCore,
DefaultBlockParams,
} from '@woop-js/utils';
} from '@harmony-js/utils';
import { getAddress } from '@woop-js/crypto';
import { getAddress } from '@harmony-js/crypto';
import { Transaction } from '@woop-js/transaction';
import { StakingTransaction } from '@woop-js/staking';
import { Transaction } from '@harmony-js/transaction';
import { StakingTransaction } from '@harmony-js/staking';
class Blockchain {
/**
@ -241,7 +156,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.getBalance({
* hmy.blockchain.getBalance({
* address: 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7',
* blockNumber: 'latest'
* }).then(value => {
@ -287,7 +202,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.getBlockNumber().then((value) => {
* hmy.blockchain.getBlockNumber().then((value) => {
* console.log(value.result);
* });
* ```
@ -312,7 +227,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.getBlockByHash({
* hmy.blockchain.getBlockByHash({
* blockHash: '0x9cd821b576efdff61280e8857ef218fb2cff8db0cf0fb27dfceef7237042b79e',
* }).then((value) => {
* console.log(value);
@ -352,7 +267,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.getBlockByNumber({
* hmy.blockchain.getBlockByNumber({
* blockNumber: '0x89',
* }).then((value) => {
* console.log(value);
@ -382,57 +297,6 @@ class Blockchain {
return this.getRpcResult(result);
}
/**
* Returns blocks in range [from; to]
*
* @param from starting block number in 0x format
* @param to ending block number in 0x format
* @param blockArgs optional args struct in json format (should be used just with { })
* @param shardID `shardID` is binding with the endpoint, IGNORE it!
* @returns `Promise` - An array of block objects
*
* @example
* ```javascript
* wiki.blockchain.getBlocks({
* from: '0x89',
* to: '0x89',
* }).then((value) => {
* console.log(value);
* });
* ```
*/
@assertObject({
from: ['isBlockNumber', AssertType.required],
to: ['isBlockNumber', AssertType.required],
blockArgs: ['isObject', AssertType.optional],
shardID: ['isNumber', AssertType.optional],
})
async getBlocks({
from,
to,
blockArgs = {
fullTx: false,
withSigners: false,
},
shardID = this.messenger.currentShard,
}: {
from: string;
to: string;
blockArgs?: {
fullTx: boolean;
withSigners: boolean;
};
shardID?: number;
}) {
const result = await this.messenger.send(
RPCMethod.GetBlocks,
[from, to, blockArgs],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
/**
* Returns the number of transaction in a given block.
*
@ -442,7 +306,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.getBlockTransactionCountByHash({
* hmy.blockchain.getBlockTransactionCountByHash({
* blockHash: '0x4142514a238157e7fe57b9d54abedb33943507fa15b3799954c273a12705ced1'
* }).then((value) => {
* console.log(value):
@ -478,7 +342,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.getBlockTransactionCountByNumber({
* hmy.blockchain.getBlockTransactionCountByNumber({
* blockNumber: '0x2403C'
* }).then((value) => {
* console.log(value);
@ -515,7 +379,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.getTransactionByBlockHashAndIndex({
* hmy.blockchain.getTransactionByBlockHashAndIndex({
* blockHash: '0x4142514a238157e7fe57b9d54abedb33943507fa15b3799954c273a12705ced1',
* index: '0x0'
* }).then((value) => {
@ -556,7 +420,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.getTransactionByBlockNumberAndIndex({
* hmy.blockchain.getTransactionByBlockNumberAndIndex({
* blockNumber: '0x2403C',
* index: '0x0'
* }).then((value) => {
@ -596,7 +460,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.getTransactionByHash({
* hmy.blockchain.getTransactionByHash({
* txnHash: '0x146a0cf7e8da45b44194207c4e7785564527059483b765f9a04424554443b224'
* }).then((value) => {
* console.log(value);
@ -632,7 +496,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.getTransactionReceipt({
* hmy.blockchain.getTransactionReceipt({
* txnHash: '0x146a0cf7e8da45b44194207c4e7785564527059483b765f9a04424554443b224'
* }).then((value) => {
* console.log(value);
@ -669,7 +533,7 @@ class Blockchain {
* @example
* ```javascript
* // This transaction sends from shard 0 to shard 1
* wiki.blockchain.getCxReceiptByHash({
* hmy.blockchain.getCxReceiptByHash({
* txnHash: '0x7fae9252fbda68d718e610bc10cf2b5c6a9cafb42d4a6b9d6e392c77d587b9ea',
* shardID: 1,
* }).then((value) => {
@ -701,7 +565,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.getCode({
* hmy.blockchain.getCode({
* address: '0x08AE1abFE01aEA60a47663bCe0794eCCD5763c19',
* blockNumber: 'latest'
* }).then((value) => {
@ -740,7 +604,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.net_peerCount().then((value) => {
* hmy.blockchain.net_peerCount().then((value) => {
* console.log(value.result);
* });
* ```
@ -759,7 +623,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.net_version().then((value) => {
* hmy.blockchain.net_version().then((value) => {
* console.log(value.result);
* });
* ```
@ -778,7 +642,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.getProtocolVersion().then((value) => {
* hmy.blockchain.getProtocolVersion().then((value) => {
* console.log(value.result);
* });
* ```
@ -803,7 +667,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.getStorageAt({
* hmy.blockchain.getStorageAt({
* address: 'one1d0kw95t6kkljmkk9vu0zv25jraut8ngv5vrs5g',
* position: '0x0'
* }).then((value) => {
@ -847,7 +711,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.getTransactionCount({
* hmy.blockchain.getTransactionCount({
* address: "one1d0kw95t6kkljmkk9vu0zv25jraut8ngv5vrs5g"
* }).then((value) => {
* console.log(value.result);
@ -884,7 +748,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.getShardingStructure().then((value) => {
* hmy.blockchain.getShardingStructure().then((value) => {
* console.log(value);
* });
* ```
@ -908,10 +772,10 @@ class Blockchain {
* ```javascript
* // add privateKey to wallet
* const privateKey = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e';
* wiki.wallet.addByPrivateKey(privateKey);
* hmy.wallet.addByPrivateKey(privateKey);
*
* async function transfer() {
* const txn = wiki.transactions.newTx({
* const txn = hmy.transactions.newTx({
* // token send to
* to: 'one166axnkjmghkf3df7xfvd0hn4dft8kemrza4cd2',
* // amount to send
@ -923,12 +787,12 @@ class Blockchain {
* // 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 wiki.utils.Unit('100').asGwei().toWei(),
* gasPrice: new hmy.utils.Unit('100').asGwei().toWei(),
* });
*
* // sign the transaction use wallet;
* const signedTxn = await wiki.wallet.signTransaction(txn);
* const txnHash = await wiki.blockchain.sendTransaction(signedTxn);
* const signedTxn = await hmy.wallet.signTransaction(txn);
* const txnHash = await hmy.blockchain.sendTransaction(signedTxn);
* console.log(txnHash.result);
* }
*
@ -960,10 +824,10 @@ class Blockchain {
* ```javascript
* // add privateKey to wallet
* const privateKey = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e';
* wiki.wallet.addByPrivateKey(privateKey);
* hmy.wallet.addByPrivateKey(privateKey);
*
* async function transfer() {
* const txn = wiki.transactions.newTx({
* const txn = hmy.transactions.newTx({
* // token send to
* to: 'one166axnkjmghkf3df7xfvd0hn4dft8kemrza4cd2',
* // amount to send
@ -975,14 +839,14 @@ class Blockchain {
* // 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 wiki.utils.Unit('100').asGwei().toWei(),
* gasPrice: new hmy.utils.Unit('100').asGwei().toWei(),
* });
*
* // sign the transaction use wallet;
* const signedTxn = await wiki.wallet.signTransaction(txn);
* const signedTxn = await hmy.wallet.signTransaction(txn);
* recovered = signedTxn.recover(signedTxn.rawTransaction);
*
* const txnHash = await wiki.blockchain.sendRawTransaction(recovered);
* const txnHash = await hmy.blockchain.sendRawTransaction(recovered);
* console.log(txnHash);
* }
*
@ -1009,10 +873,10 @@ class Blockchain {
* ```javascript
* // add privateKey to wallet
* const privateKey = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e';
* wiki.wallet.addByPrivateKey(privateKey);
* hmy.wallet.addByPrivateKey(privateKey);
*
* async function transfer() {
* const txn = wiki.transactions.newTx({
* const txn = hmy.transactions.newTx({
* // token send to
* to: 'one166axnkjmghkf3df7xfvd0hn4dft8kemrza4cd2',
* // amount to send
@ -1024,12 +888,12 @@ class Blockchain {
* // 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 wiki.utils.Unit('100').asGwei().toWei(),
* gasPrice: new hmy.utils.Unit('100').asGwei().toWei(),
* });
*
* // sign the transaction use wallet;
* const signedTxn = await wiki.wallet.signTransaction(txn);
* const txnHash = await wiki.blockchain.createObservedTransaction(signedTxn);
* const signedTxn = await hmy.wallet.signTransaction(txn);
* const txnHash = await hmy.blockchain.createObservedTransaction(signedTxn);
* console.log(txnHash);
* }
*
@ -1108,12 +972,12 @@ class Blockchain {
*
* @warning
* ```
* At present, this function wiki_estimateGas is not implement yet, will Coming soon!!!
* At present, this function hmy_estimateGas is not implement yet, will Coming soon!!!
* ```
*
* @example
* ```javascript
* wiki.blockchain.estimateGas({
* hmy.blockchain.estimateGas({
* to: 'one1d0kw95t6kkljmkk9vu0zv25jraut8ngv5vrs5g',
* data: '0xc6888fa10000000000000000000000000000000000000000000000000000000000000003'
* }).then((value) => {
@ -1152,7 +1016,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.gasPrice().then((value) => {
* hmy.blockchain.gasPrice().then((value) => {
* console.log(value);
* });
* ```
@ -1177,7 +1041,7 @@ class Blockchain {
*
* @example
* ```javascript
* wiki.blockchain.call({
* hmy.blockchain.call({
* to: "0x08AE1abFE01aEA60a47663bCe0794eCCD5763c19",
* }).then((value) => {
* console.log(value);
@ -1209,18 +1073,18 @@ class Blockchain {
*
* @example
* ```javascript
* const wiki = new Woop(
* const hmy = new Harmony(
* // rpc url
* 'ws://api.s0.b.hmny.io/',
* {
* // chainType set to Woop
* chainType: ChainType.Woop,
* // chainType set to WikiLocal
* chainId: ChainID.WikiLocal,
* // chainType set to Harmony
* chainType: ChainType.Harmony,
* // chainType set to HmyLocal
* chainId: ChainID.HmyLocal,
* },
* );
*
* const tmp = wiki.blockchain.newPendingTransactions();
* const tmp = hmy.blockchain.newPendingTransactions();
* console.log(tmp)
* ```
*/
@ -1238,18 +1102,18 @@ class Blockchain {
*
* @example
* ```javascript
* const wiki = new Woop(
* const hmy = new Harmony(
* // rpc url
* 'ws://api.s0.b.hmny.io/',
* {
* // chainType set to Woop
* chainType: ChainType.Woop,
* // chainType set to WikiLocal
* chainId: ChainID.WikiLocal,
* // chainType set to Harmony
* chainType: ChainType.Harmony,
* // chainType set to HmyLocal
* chainId: ChainID.HmyLocal,
* },
* );
*
* const tmp = wiki.blockchain.newBlockHeaders();
* const tmp = hmy.blockchain.newBlockHeaders();
* console.log(tmp)
* ```
*/
@ -1267,18 +1131,18 @@ class Blockchain {
*
* @example
* ```javascript
* const wiki = new Woop(
* const hmy = new Harmony(
* // rpc url
* 'ws://api.s0.b.hmny.io/',
* {
* // chainType set to Woop
* chainType: ChainType.Woop,
* // chainType set to WikiLocal
* chainId: ChainID.WikiLocal,
* // chainType set to Harmony
* chainType: ChainType.Harmony,
* // chainType set to HmyLocal
* chainId: ChainID.HmyLocal,
* },
* );
*
* const tmp = wiki.blockchain.syncing();
* const tmp = hmy.blockchain.syncing();
* console.log(tmp)
* ```
*/
@ -1296,18 +1160,18 @@ class Blockchain {
*
* @example
* ```javascript
* const wiki = new Woop(
* const hmy = new Harmony(
* // rpc url
* 'ws://api.s0.b.hmny.io/',
* {
* // chainType set to Woop
* chainType: ChainType.Woop,
* // chainType set to WikiLocal
* chainId: ChainID.WikiLocal,
* // chainType set to Harmony
* chainType: ChainType.Harmony,
* // chainType set to HmyLocal
* chainId: ChainID.HmyLocal,
* },
* );
*
* const tmp = wiki.blockchain.logs({
* const tmp = hmy.blockchain.logs({
* from: '0x12'
* });
* console.log(tmp)

@ -1,20 +1,20 @@
/**
* @packageDocumentation
* @module woop-core
* @module harmony-core
*/
import * as crypto from '@woop-js/crypto';
import * as utils from '@woop-js/utils';
import * as crypto from '@harmony-js/crypto';
import * as utils from '@harmony-js/utils';
import { Provider, HttpProvider, Messenger, WSProvider, ShardingItem } from '@woop-js/network';
import { TransactionFactory, Transaction } from '@woop-js/transaction';
import { StakingTransaction, StakingFactory } from '@woop-js/staking';
import { ContractFactory, Contract } from '@woop-js/contract';
import { Wallet, Account } from '@woop-js/account';
import { Provider, HttpProvider, Messenger, WSProvider, ShardingItem } from '@harmony-js/network';
import { TransactionFactory, Transaction } from '@harmony-js/transaction';
import { StakingTransaction, StakingFactory } from '@harmony-js/staking';
import { ContractFactory, Contract } from '@harmony-js/contract';
import { Wallet, Account } from '@harmony-js/account';
import { Blockchain } from './blockchain';
import { WoopConfig } from './util';
import { HarmonyConfig } from './util';
export class Woop extends utils.WoopCore {
export class Harmony extends utils.HarmonyCore {
/**@ignore*/
Modules = {
HttpProvider,
@ -51,38 +51,38 @@ export class Woop extends utils.WoopCore {
private provider: HttpProvider | WSProvider;
/**
* Create a woop instance
* Create a harmony instance
*
* @param url The end-points of the wiki blockchain
* @param url The end-points of the hmy blockchain
* @param config set up `ChainID` and `ChainType`, typically we can use the default values
*
* @example
* ```
* // import or require Woop class
* const { Woop } = require('@woop-js/core');
* // import or require Harmony class
* const { Harmony } = require('@harmony-js/core');
*
* // import or require settings
* const { ChainID, ChainType } = require('@woop-js/utils');
* const { ChainID, ChainType } = require('@harmony-js/utils');
*
* // Initialize the Woop instance
* const wiki = new Woop(
* // Initialize the Harmony instance
* const hmy = new Harmony(
* // rpc url:
* // local: http://localhost:9500
* // testnet: https://api.s0.b.hmny.io/
* // mainnet: https://api.s0.t.hmny.io/
* 'http://localhost:9500',
* {
* // chainType set to Woop
* chainType: ChainType.Woop,
* // chainType set to WikiLocal
* chainId: ChainID.WikiLocal,
* // chainType set to Harmony
* chainType: ChainType.Harmony,
* // chainType set to HmyLocal
* chainId: ChainID.HmyLocal,
* },
* );
* ```
*/
constructor(
url: string,
config: WoopConfig = {
config: HarmonyConfig = {
chainId: utils.defaultConfig.Default.Chain_ID,
chainType: utils.defaultConfig.Default.Chain_Type,
},
@ -113,7 +113,7 @@ export class Woop extends utils.WoopCore {
*
* @example
* ```javascript
* const tmp = wiki.setProvider('http://localhost:9500');
* const tmp = hmy.setProvider('http://localhost:9500');
* ```
*/
public setProvider(provider: string | HttpProvider | WSProvider): void {
@ -139,16 +139,16 @@ export class Woop extends utils.WoopCore {
EtcTestnet = 62,
Geth = 1337,
Ganache = 0,
WikiMainnet = 1,
WikiTestnet = 2,
WikiLocal = 2,
WikiPangaea = 3
HmyMainnet = 1,
HmyTestnet = 2,
HmyLocal = 2,
HmyPangaea = 3
* ```
* @param chainId
*
* @example
* ```
* wiki.setChainId(2);
* hmy.setChainId(2);
* ```
*/
public setChainId(chainId: utils.ChainID) {
@ -162,7 +162,7 @@ export class Woop extends utils.WoopCore {
*
* @example
* ```
* wiki.setShardID(2);
* hmy.setShardID(2);
* ```
*/
public setShardID(shardID: number) {
@ -174,14 +174,14 @@ export class Woop extends utils.WoopCore {
/**
* set the chainType
*
* @param chainType `wiki` or `eth`
* @param chainType `hmy` or `eth`
*
* @example
* ```
* // set chainType to wiki
* wiki.setChainType('wiki');
* // set chainType to hmy
* hmy.setChainType('hmy');
* // set chainType to eth
* wiki.setChainType('eth');
* hmy.setChainType('eth');
* ```
*/
public setChainType(chainType: utils.ChainType) {
@ -197,7 +197,7 @@ export class Woop extends utils.WoopCore {
*
* @example
* ```javascript
* wiki.shardingStructures([
* hmy.shardingStructures([
* {"current":true,"http":"http://127.0.0.1:9500",
* "shardID":0,"ws":"ws://127.0.0.1:9800"},
* {"current":false,"http":"http://127.0.0.1:9501",

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-core
* @module harmony-core
*/
import {
@ -10,15 +10,15 @@ import {
Provider,
RPCMethod,
ShardingItem,
} from '@woop-js/network';
} from '@harmony-js/network';
import * as crypto from '@woop-js/crypto';
import * as utils from '@woop-js/utils';
import * as crypto from '@harmony-js/crypto';
import * as utils from '@harmony-js/utils';
import { Transaction, TransactionFactory } from '@woop-js/transaction';
import { Transaction, TransactionFactory } from '@harmony-js/transaction';
import { Blockchain } from './blockchain';
import { ContractFactory } from '@woop-js/contract';
import { WoopConfig } from './util';
import { ContractFactory } from '@harmony-js/contract';
import { HarmonyConfig } from './util';
/** @hidden */
export enum ExtensionType {
@ -55,7 +55,7 @@ export interface ExtensionInterface {
network: ExtensionNetwork;
}
export class WoopExtension {
export class HarmonyExtension {
/**@ignore*/
extensionType: ExtensionType | null;
/**@ignore*/
@ -87,17 +87,17 @@ export class WoopExtension {
* ```javascript
* // Using Mathwallet instance
* export const initEx = async() => {
* wikiEx = new WoopExtension(window.woop);
* hmyEx = new HarmonyExtension(window.harmony);
* }
* // Using OneWallet instance
* export const initEx = async() => {
* wikiEx = new WoopExtension(window.onewallet);
* hmyEx = new HarmonyExtension(window.onewallet);
* }
* ```
*/
constructor(
wallet: ExtensionInterface,
config: WoopConfig = {
config: HarmonyConfig = {
chainId: utils.defaultConfig.Default.Chain_ID,
chainType: utils.defaultConfig.Default.Chain_Type,
},
@ -129,7 +129,7 @@ export class WoopExtension {
*
* @example
* ```javascript
* const tmp = wikiEx.setProvider('http://localhost:9500');
* const tmp = hmyEx.setProvider('http://localhost:9500');
* ```
*/
public setProvider(provider: string | HttpProvider | WSProvider): void {
@ -143,7 +143,7 @@ export class WoopExtension {
*
* @example
* ```
* wikiEx.setShardID(2);
* hmyEx.setShardID(2);
* ```
*/
public setShardID(shardID: number) {
@ -172,7 +172,7 @@ export class WoopExtension {
if (updateNonce) {
const nonce = await this.messenger.send(
RPCMethod.GetAccountNonce,
RPCMethod.GetTransactionCount,
[crypto.getAddress(extensionAccount.address).checksum, blockNumber],
this.messenger.chainPrefix,
typeof transaction.txParams.shardID === 'string'
@ -182,7 +182,7 @@ export class WoopExtension {
transaction.setParams({
...transaction.txParams,
from: crypto.getAddress(extensionAccount.address).bech32,
nonce: Number.parseInt(utils.isHex(nonce.result.toString()) ? utils.hexToNumber(nonce.result.toString()) : nonce.result.toString(), 10),
nonce: Number.parseInt(utils.hexToNumber(nonce.result), 10),
});
} else {
transaction.setParams({
@ -205,7 +205,7 @@ export class WoopExtension {
*
* @example
* ```javascript
* const account = wikiEx.login();
* const account = hmyEx.login();
* console.log(account);
* ```
*/
@ -220,7 +220,7 @@ export class WoopExtension {
*
* @example
* ```javascript
* wikiEx.logout();
* hmyEx.logout();
* ```
*/
public async logout() {
@ -234,7 +234,7 @@ export class WoopExtension {
*
* @example
* ```javascript
* wikiEx.shardingStructures([
* hmyEx.shardingStructures([
* {"current":true,"http":"http://127.0.0.1:9500",
* "shardID":0,"ws":"ws://127.0.0.1:9800"},
* {"current":false,"http":"http://127.0.0.1:9501",

@ -1,11 +1,11 @@
/**
* @packageDocumentation
* @module woop-core
* @module harmony-core
* @hidden
*/
export * from './woop';
export * from './harmony';
export * from './blockchain';
export * from './truffleProvider';
export * from './woopExtension';
export * from './harmonyExtension';
export * from './types';

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-core
* @module harmony-core
* @hidden
*/
@ -9,11 +9,11 @@ import {
WSProvider,
RPCRequestPayload,
ResponseMiddleware,
} from '@woop-js/network';
} from '@harmony-js/network';
import { ChainID, ChainType, Unit, isBech32Address } from '@woop-js/utils';
import { HDNode } from '@woop-js/account';
import { fromBech32, HRP } from '@woop-js/crypto';
import { ChainID, ChainType, Unit, isBech32Address } from '@harmony-js/utils';
import { HDNode } from '@harmony-js/account';
import { fromBech32, HRP } from '@harmony-js/crypto';
const packageInfo = { version: '1.0.0' };
@ -52,8 +52,8 @@ export class TruffleProvider extends HDNode {
},
chainOptions: ChainOptions = {
shardID: 0,
chainType: ChainType.Woop,
chainId: ChainID.WikiLocal,
chainType: ChainType.Harmony,
chainId: ChainID.HmyLocal,
},
transactionOptions: TransactionOptions = {
gasLimit: '10000000',
@ -76,7 +76,7 @@ export class TruffleProvider extends HDNode {
const { newArgs, id, params, newMethod, callback } = this.resolveArgs(...args);
switch (newMethod) {
case 'wiki_accounts': {
case 'hmy_accounts': {
const accounts = this.getAccounts();
callback(null, {
result: accounts,
@ -90,13 +90,13 @@ export class TruffleProvider extends HDNode {
};
// break;
}
case 'wiki_sendTransaction': {
case 'hmy_sendTransaction': {
const txObj = params[0];
const rawTxn = await this.signTransaction(txObj);
const result = await this.provider.send(
{
id,
method: 'wiki_sendRawTransaction',
method: 'hmy_sendRawTransaction',
params: [rawTxn],
jsonrpc: '2.0',
},
@ -106,11 +106,11 @@ export class TruffleProvider extends HDNode {
// break;
}
case 'wiki_getTransactionReceipt': {
case 'hmy_getTransactionReceipt': {
const result = await this.provider.send(
{
id,
method: 'wiki_getTransactionReceipt',
method: 'hmy_getTransactionReceipt',
params: [params[0]],
jsonrpc: '2.0',
},
@ -146,27 +146,23 @@ export class TruffleProvider extends HDNode {
}
case 'web3_clientVersion': {
callback(null, {
result: `Woop/${packageInfo.version}/@woop-js`,
result: `Harmony/${packageInfo.version}/@harmony-js`,
id,
jsonrpc: '2.0',
});
return {
result: `Woop/${packageInfo.version}/@woop-js`,
result: `Harmony/${packageInfo.version}/@harmony-js`,
id,
jsonrpc: '2.0',
};
}
case 'wiki_getBlockByNumber': {
case 'hmy_getBlockByNumber': {
const result = await this.provider.send(newArgs, (err: any, res: any) => {
try {
if (err) {
callback(err);
}
const response = this.resolveResult(res);
if (response.error) {
callback(response.error);
return;
}
if (
new Unit(response.result.gasLimit)
@ -191,7 +187,7 @@ export class TruffleProvider extends HDNode {
}
default: {
// wiki_getBlockByNumber
// hmy_getBlockByNumber
const result = await this.provider.send(
newArgs,
@ -213,7 +209,7 @@ export class TruffleProvider extends HDNode {
const params = args[0].params;
let newMethod: string = method;
if (method.startsWith('eth')) {
newMethod = method.replace('eth', 'wiki');
newMethod = method.replace('eth', 'hmy');
}
args[0].method = newMethod;

@ -0,0 +1,31 @@
/**
* @packageDocumentation
* @module harmony-core
* @hidden
*/
import { HttpProvider, Messenger } from '@harmony-js/network';
import { TransactionFactory, Transaction } from '@harmony-js/transaction';
import { Wallet, Account } from '@harmony-js/account';
import { ChainType, ChainID } from '@harmony-js/utils';
import { Blockchain } from './blockchain';
export interface HarmonyModule {
HttpProvider: HttpProvider;
Messenger: Messenger;
Blockchain: Blockchain;
TransactionFactory: TransactionFactory;
Wallet: Wallet;
Transaction: Transaction;
Account: Account;
}
export const enum UrlType {
http,
ws,
}
export interface HarmonySetting<T extends ChainType, I extends ChainID> {
type: T;
id: I;
}

@ -1,13 +1,13 @@
/**
* @packageDocumentation
* @module woop-core
* @module harmony-core
* @hidden
*/
import { ChainType, ChainID, defaultConfig } from '@woop-js/utils';
import { Woop } from './woop';
import { ChainType, ChainID, defaultConfig } from '@harmony-js/utils';
import { Harmony } from './harmony';
export interface WoopConfig {
export interface HarmonyConfig {
chainUrl?: string;
chainType: ChainType;
chainId: ChainID;
@ -17,18 +17,18 @@ export interface WoopConfig {
// tslint:disable-next-line: variable-name
export function createWeb3(_web3: any) {
const url: string = _web3.currentProvider.url;
const woop = new Woop(url, {
const harmony = new Harmony(url, {
chainId: defaultConfig.Default.Chain_ID,
chainType: defaultConfig.Default.Chain_Type,
chainUrl: defaultConfig.Default.Chain_URL,
});
_web3.setProvider(woop.messenger.provider);
_web3.messenger = woop.messenger;
_web3.eth.getRpcResult = woop.blockchain.getRpcResult;
_web3.setProvider(harmony.messenger.provider);
_web3.messenger = harmony.messenger;
_web3.eth.getRpcResult = harmony.blockchain.getRpcResult;
// map blockchain to eth
const { blockchain } = woop;
const { blockchain } = harmony;
_web3.eth.getBlockNumber = () => blockchain.getBlockByNumber;
_web3.eth.getBalance = (address: string, blockNumber?: string) =>
blockchain.getBalance({ address, blockNumber });
@ -67,31 +67,31 @@ export function createWeb3(_web3: any) {
_web3.eth.logs = (options: any) => blockchain.logs(options);
// map subscribe to _web3
_web3.eth.subscribe = woop.messenger.subscribe;
_web3.eth.subscribe = harmony.messenger.subscribe;
// map accounts to _web3
_web3.accounts = woop.wallet.accounts;
_web3.eth.accounts.create = woop.wallet.createAccount;
_web3.eth.accounts.privateKeyToAccount = woop.wallet.addByPrivateKey;
_web3.accounts = harmony.wallet.accounts;
_web3.eth.accounts.create = harmony.wallet.createAccount;
_web3.eth.accounts.privateKeyToAccount = harmony.wallet.addByPrivateKey;
_web3.eth.accounts.encrypt = async (privateKey: string, password: string) => {
const newAcc = new woop.Modules.Account(privateKey, woop.messenger);
const newAcc = new harmony.Modules.Account(privateKey, harmony.messenger);
const result = await newAcc.toFile(password);
return result;
};
_web3.eth.accounts.decrypt = async (keystoreJsonV3: any, password: string) => {
const newAcc = new woop.Modules.Account();
const newAcc = new harmony.Modules.Account();
const result = await newAcc.fromFile(JSON.stringify(keystoreJsonV3), password);
return result;
};
_web3.eth.accounts.signTransaction = woop.wallet.signTransaction;
_web3.eth.accounts.signTransaction = harmony.wallet.signTransaction;
// map transaction to web3
_web3.eth.recoverTransaction = woop.transactions.recover;
_web3.eth.recoverTransaction = harmony.transactions.recover;
// map contract to web3
_web3.eth.Contract = woop.contracts.createContract;
_web3.eth.Contract = harmony.contracts.createContract;
_web3.utils = { ..._web3.utils, ...woop.utils, ...woop.crypto };
_web3.utils = { ..._web3.utils, ...harmony.utils, ...harmony.crypto };
}

@ -6,18 +6,18 @@
// tslint:disable-next-line: no-implicit-dependencies
import fetch from 'jest-fetch-mock';
import { Blockchain } from '../src/blockchain';
import { HttpProvider, Messenger } from '@woop-js/network';
import { HttpProvider, Messenger } from '@harmony-js/network';
const provider = new HttpProvider('https://mock.com');
const messenger = new Messenger(provider);
function runMocks(mockRpcResponse: any, repeat: number): void {
const mocks: any = [];
const mocks = [];
for (let i = 0; i < 5; i++) {
mocks.push(mockRpcResponse);
}
// tslint:disable-next-line: no-shadowed-variable
const responses = mocks.map((res: any) => [JSON.stringify(res), {status: 200}]);
const responses = mocks.map((res) => [JSON.stringify(res)]);
fetch.mockResponses(...responses);
}

@ -0,0 +1,16 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "dist"
},
"include": ["src", "../../typings/**/*.d.ts", "../harmony-utils/src/core.ts"],
"references": [
{"path": "../harmony-account"},
{"path": "../harmony-crypto"},
{"path": "../harmony-utils"},
{"path": "../harmony-network"},
{"path": "../harmony-transaction"},
{"path": "../harmony-contract"}
]
}

@ -1,11 +1,11 @@
# @woop-js/crypto
# @harmony-js/crypto
This package provides a collection of apis related to address management, kestore, encoding, and encrypt/decrypt.
## Installation
```
npm install @woop-js/crypto
npm install @harmony-js/crypto
```
## Usage
@ -17,26 +17,26 @@ const {
randomBytes,
toBech32,
fromBech32,
WoopAddress,
HarmonyAddress,
generatePrivateKey,
getPubkeyFromPrivateKey,
getAddressFromPublicKey,
getAddressFromPrivateKey,
encryptPhrase,
decryptPhrase
} = require('@woop-js/crypto');
const { isPrivateKey, isAddress, isPublicKey } = require('@woop-js/utils');
} = require('@harmony-js/crypto');
const { isPrivateKey, isAddress, isPublicKey } = require('@harmony-js/utils');
```
Address apis
```javascript
const bytes = randomBytes(20);
const addr = new WoopAddress(bytes);
const addr = new HarmonyAddress(bytes);
console.log(addr.checksum);
console.log(addr.bech32);
console.log(WoopAddress.isValidBech32(addr.bech32));
console.log(HarmonyAddress.isValidBech32(addr.bech32));
```
RLP apis
@ -61,7 +61,7 @@ console.log(isAddress(addrPrv));
Encrypt/decrypt apis
```javascript
const { Wallet } = require('@woop-js/account');
const { Wallet } = require('@harmony-js/account');
const myPhrase = new Wallet().newMnemonic();
console.log(myPhrase);

@ -1,7 +1,7 @@
{
"name": "@woop-js/crypto",
"version": "0.1.58",
"description": "crypto libraries for woop",
"name": "@harmony-js/crypto",
"version": "0.1.48",
"description": "crypto libraries for harmony",
"main": "dist/index.js",
"node": "dist/index.js",
"browser": "dist/index.js",
@ -18,7 +18,7 @@
},
"license": "MIT",
"dependencies": {
"@woop-js/utils": "0.1.58",
"@harmony-js/utils": "0.1.48",
"aes-js": "^3.1.2",
"bip39": "^2.5.0",
"bn.js": "^4.11.8",
@ -27,7 +27,7 @@
"hmac-drbg": "^1.0.1",
"js-sha3": "^0.8.0",
"pbkdf2": "^3.0.17",
"scrypt.js": "^0.3.0",
"scrypt-shim": "github:web3-js/scrypt-shim",
"uuid": "^3.3.2"
},
"gitHead": "56606e9365721729a490c27d6a294e0daf90fbdf"

@ -1,9 +1,9 @@
/**
* @packageDocumentation
* @module woop-crypto
* @module harmony-crypto
*/
import { isAddress, isBech32Address, isBech32TestNetAddress } from '@woop-js/utils';
import { isAddress, isBech32Address, isBech32TestNetAddress } from '@harmony-js/utils';
import { toChecksumAddress } from './keyTool';
import { fromBech32, toBech32, HRP, tHRP } from './bech32';
@ -13,25 +13,25 @@ import { fromBech32, toBech32, HRP, tHRP } from './bech32';
*
* ```
* // Step 1: import the class
* const { WoopAddress } = require('@woop-js/crypto');
* const { HarmonyAddress } = require('@harmony-js/crypto');
*
* // Step 2: call functions
* const addr = 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7'
* const res = WoopAddress.isValidBech32(addr);
* const res = HarmonyAddress.isValidBech32(addr);
* console.log(res);
* ```
*/
export class WoopAddress {
export class HarmonyAddress {
/**
* @example
* ```
* const addr = 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7'
* const res = WoopAddress.isValidBech32(addr);
* const res = HarmonyAddress.isValidBech32(addr);
* console.log(res);
* ```
*/
static isValidBasic(str: string) {
const toTest = new WoopAddress(str);
const toTest = new HarmonyAddress(str);
return toTest.raw === toTest.basic;
}
@ -39,12 +39,12 @@ export class WoopAddress {
* @example
* ```
* const addr = 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7'
* const res = WoopAddress.isValidChecksum(addr);
* const res = HarmonyAddress.isValidChecksum(addr);
* console.log(res);
* ```
*/
static isValidChecksum(str: string) {
const toTest = new WoopAddress(str);
const toTest = new HarmonyAddress(str);
return toTest.raw === toTest.checksum;
}
@ -52,12 +52,12 @@ export class WoopAddress {
* @example
* ```
* const addr = 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7'
* const res = WoopAddress.isValidBech32(addr);
* const res = HarmonyAddress.isValidBech32(addr);
* console.log(res);
* ```
*/
static isValidBech32(str: string) {
const toTest = new WoopAddress(str);
const toTest = new HarmonyAddress(str);
return toTest.raw === toTest.bech32;
}
@ -65,12 +65,12 @@ export class WoopAddress {
* @example
* ```
* const addr = 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7'
* const res = WoopAddress.isValidBech32TestNet(addr);
* const res = HarmonyAddress.isValidBech32TestNet(addr);
* console.log(res);
* ```
*/
static isValidBech32TestNet(str: string) {
const toTest = new WoopAddress(str);
const toTest = new HarmonyAddress(str);
return toTest.raw === toTest.bech32TestNet;
}
@ -83,7 +83,7 @@ export class WoopAddress {
* @example
* ```
* const addr = 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7'
* const instance = new WoopAddress(addr);
* const instance = new HarmonyAddress(addr);
* console.log(instance.basicHex);
* ```
*/
@ -95,7 +95,7 @@ export class WoopAddress {
* @example
* ```
* const addr = 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7'
* const instance = new WoopAddress(addr);
* const instance = new HarmonyAddress(addr);
* console.log(instance.checksum);
* ```
*/
@ -107,7 +107,7 @@ export class WoopAddress {
* @example
* ```
* const addr = 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7'
* const instance = new WoopAddress(addr);
* const instance = new HarmonyAddress(addr);
* console.log(instance.bech32);
* ```
*/
@ -119,7 +119,7 @@ export class WoopAddress {
* @example
* ```
* const addr = 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7'
* const instance = new WoopAddress(addr);
* const instance = new HarmonyAddress(addr);
* console.log(instance.bech32TestNet);
* ```
*/
@ -140,7 +140,7 @@ export class WoopAddress {
* @example
* ```
* const addr = 'one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7'
* const instance = new WoopAddress(addr);
* const instance = new HarmonyAddress(addr);
* const res = instance.getBasic(addr);
* console.log(res)
* ```
@ -169,32 +169,32 @@ export class WoopAddress {
}
/**
* Using this function to get Woop format address
* Using this function to get Harmony format address
*
* @param address
*
* @example
* ```javascript
* const { Woop } = require('@woop-js/core');
* const { ChainID, ChainType } = require('@woop-js/utils');
* const { randomBytes } = require('@woop-js/crypto')
* const { Harmony } = require('@harmony-js/core');
* const { ChainID, ChainType } = require('@harmony-js/utils');
* const { randomBytes } = require('@harmony-js/crypto')
*
* const wiki = new Woop(
* const hmy = new Harmony(
* 'http://localhost:9500',
* {
* chainType: ChainType.Woop,
* chainId: ChainID.WikiLocal,
* chainType: ChainType.Harmony,
* chainId: ChainID.HmyLocal,
* },
* );
*
* const bytes = randomBytes(20);
* const hAddress = wiki.crypto.getAddress(bytes);
* const hAddress = hmy.crypto.getAddress(bytes);
* console.log(hAddress)
* ```
*/
export function getAddress(address: string) {
try {
return new WoopAddress(address);
return new HarmonyAddress(address);
} catch (error) {
throw error;
}

@ -1,10 +1,10 @@
/**
* @packageDocumentation
* @module woop-crypto
* @module harmony-crypto
* @hidden
*/
import { isAddress } from '@woop-js/utils';
import { isAddress } from '@harmony-js/utils';
import { toChecksumAddress } from './keyTool';
// This code is taken from https://github.com/sipa/bech32/tree/bdc264f84014c234e908d72026b7b780122be11f/ref/javascript
@ -127,7 +127,7 @@ export const bech32Decode = (bechString: string) => {
return { hrp, data: Buffer.from(data.slice(0, data.length - 6)) };
};
// HRP is the human-readable part of Woop bech32 addresses
// HRP is the human-readable part of Harmony bech32 addresses
export const HRP = 'one';
export const tHRP = 'tone';
@ -184,14 +184,14 @@ export const convertBits = (
/**
* toBech32Address
*
* bech32Encodes a canonical 20-byte Ethereum-style address as a bech32 Woop
* bech32Encodes a canonical 20-byte Ethereum-style address as a bech32 Harmony
* address.
*
* The expected format is one1<address><checksum> where address and checksum
* are the result of bech32 encoding a Buffer containing the address bytes.
*
* @param {string} 20 byte canonical address
* @returns {string} 38 char bech32 bech32Encoded Woop address
* @returns {string} 38 char bech32 bech32Encoded Harmony address
*/
export const toBech32 = (address: string, useHRP: string = HRP): string => {
if (!isAddress(address)) {
@ -210,7 +210,7 @@ export const toBech32 = (address: string, useHRP: string = HRP): string => {
/**
* fromBech32Address
*
* @param {string} address - a valid Woop bech32 address
* @param {string} address - a valid Harmony bech32 address
* @returns {string} a canonical 20-byte Ethereum-style address
*/
export const fromBech32 = (address: string, useHRP: string = HRP): string => {

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-crypto
* @module harmony-crypto
* @hidden
*/

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

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-crypto
* @module harmony-crypto
* @ignore
*/

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-crypto
* @module harmony-crypto
* @ignore
*/

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-crypto
* @module harmony-crypto
*/
import elliptic from 'elliptic';
@ -9,8 +9,7 @@ import * as errors from './errors';
import { keccak256 } from './keccak256';
import { randomBytes } from './random';
import { isPrivateKey, strip0x, isAddress, isBech32Address } from '@woop-js/utils';
import { fromBech32 } from './bech32';
import { isPrivateKey, strip0x, isAddress } from '@harmony-js/utils';
import { encode } from './rlp';
const secp256k1 = elliptic.ec('secp256k1');
@ -82,9 +81,6 @@ export const getAddressFromPublicKey = (publicKey: string): string => {
* @return {string} checksumed address
*/
export const toChecksumAddress = (address: string): string => {
if (typeof address === 'string' && isBech32Address(address)) {
address = fromBech32(address);
}
if (typeof address !== 'string' || !address.match(/^0x[0-9A-Fa-f]{40}$/)) {
errors.throwError('invalid address', errors.INVALID_ARGUMENT, {
arg: 'address',

@ -1,13 +1,14 @@
/**
* @packageDocumentation
* @module woop-crypto
* @module harmony-crypto
*/
import aes from 'aes-js';
import scrypt from 'scrypt.js';
// import scrypt from 'scrypt.js';
import scrypt from 'scrypt-shim';
import { pbkdf2Sync } from 'pbkdf2';
import uuid from 'uuid';
import { isPrivateKey } from '@woop-js/utils';
import { isPrivateKey } from '@harmony-js/utils';
import { randomBytes } from './random';
import { getAddressFromPrivateKey } from './keyTool';
import { concat, hexToIntArray } from './bytes';

@ -1,6 +1,6 @@
/**
* @packageDocumentation
* @module woop-crypto
* @module harmony-crypto
*/
/**

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

Loading…
Cancel
Save