Compare commits

..

No commits in common. 'master' and 'datastructure-update' have entirely different histories.

  1. 5
      .env.example
  2. 9
      .gitignore
  3. 6
      .travis.yml
  4. 203
      README.md
  5. 70
      RELEASE.md
  6. 100
      TYPEDOC.md
  7. 0
      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. 16
      gulpfile.js
  16. 2
      lerna.json
  17. 1081
      log.txt
  18. 44661
      package-lock.json
  19. 31
      package.json
  20. 12
      packages/README.md
  21. 0
      packages/harmony-account/LICENSE
  22. 9
      packages/harmony-account/README.md
  23. 20
      packages/harmony-account/package.json
  24. 294
      packages/harmony-account/src/account.ts
  25. 46
      packages/harmony-account/src/hdnode.ts
  26. 6
      packages/harmony-account/src/index.ts
  27. 6
      packages/harmony-account/src/types.ts
  28. 8
      packages/harmony-account/src/utils.ts
  29. 176
      packages/harmony-account/src/wallet.ts
  30. 15
      packages/harmony-account/tsconfig.json
  31. 0
      packages/harmony-account/tsconfig.test.json
  32. 0
      packages/harmony-contract/LICENSE
  33. 0
      packages/harmony-contract/README.md
  34. 18
      packages/harmony-contract/package.json
  35. 353
      packages/harmony-contract/src/abi/abiCoder.ts
  36. 14
      packages/harmony-contract/src/abi/api.ts
  37. 6
      packages/harmony-contract/src/abi/index.ts
  38. 14
      packages/harmony-contract/src/abi/utils.ts
  39. 21
      packages/harmony-contract/src/contract.ts
  40. 7
      packages/harmony-contract/src/contractFactory.ts
  41. 7
      packages/harmony-contract/src/events/event.ts
  42. 10
      packages/harmony-contract/src/events/eventFactory.ts
  43. 10
      packages/harmony-contract/src/index.ts
  44. 174
      packages/harmony-contract/src/methods/method.ts
  45. 21
      packages/harmony-contract/src/methods/methodFactory.ts
  46. 8
      packages/harmony-contract/src/models/AbiItemModel.ts
  47. 28
      packages/harmony-contract/src/models/AbiModel.ts
  48. 6
      packages/harmony-contract/src/models/types.ts
  49. 12
      packages/harmony-contract/src/utils/decoder.ts
  50. 17
      packages/harmony-contract/src/utils/encoder.ts
  51. 27
      packages/harmony-contract/src/utils/formatter.ts
  52. 19
      packages/harmony-contract/src/utils/mapper.ts
  53. 6
      packages/harmony-contract/src/utils/options.ts
  54. 6
      packages/harmony-contract/src/utils/status.ts
  55. 9
      packages/harmony-contract/test/abiCoder.test.ts
  56. 20683
      packages/harmony-contract/test/fixtures/abiv2.ts
  57. 10
      packages/harmony-contract/tsconfig.json
  58. 0
      packages/harmony-contract/tsconfig.test.json
  59. 0
      packages/harmony-core/LICENSE
  60. 0
      packages/harmony-core/README.md
  61. 22
      packages/harmony-core/package.json
  62. 526
      packages/harmony-core/src/blockchain.ts
  63. 99
      packages/harmony-core/src/harmony.ts
  64. 127
      packages/harmony-core/src/harmonyExtension.ts
  65. 5
      packages/harmony-core/src/index.ts
  66. 56
      packages/harmony-core/src/truffleProvider.ts
  67. 25
      packages/harmony-core/src/types.ts
  68. 42
      packages/harmony-core/src/util.ts
  69. 53
      packages/harmony-core/test/blockchain.test.ts
  70. 16
      packages/harmony-core/tsconfig.json
  71. 0
      packages/harmony-core/tsconfig.test.json
  72. 0
      packages/harmony-crypto/LICENSE
  73. 0
      packages/harmony-crypto/README.md
  74. 12
      packages/harmony-crypto/package.json
  75. 80
      packages/harmony-crypto/src/address.ts
  76. 22
      packages/harmony-crypto/src/bech32.ts
  77. 70
      packages/harmony-crypto/src/bytes.ts
  78. 132
      packages/harmony-crypto/src/errors.ts
  79. 6
      packages/harmony-crypto/src/index.ts
  80. 6
      packages/harmony-crypto/src/keccak256.ts
  81. 11
      packages/harmony-crypto/src/keyTool.ts
  82. 37
      packages/harmony-crypto/src/keystore.ts
  83. 17
      packages/harmony-crypto/src/random.ts
  84. 24
      packages/harmony-crypto/src/rlp.ts
  85. 5
      packages/harmony-crypto/src/signature.ts
  86. 8
      packages/harmony-crypto/src/types.ts
  87. 17
      packages/harmony-crypto/test/address.test.ts
  88. 5
      packages/harmony-crypto/test/bytes.test.ts
  89. 0
      packages/harmony-crypto/test/fixtures/hashes.json
  90. 0
      packages/harmony-crypto/test/fixtures/rlpcoder.json
  91. 5
      packages/harmony-crypto/test/keccak256.test.ts
  92. 7
      packages/harmony-crypto/test/keyTool.test.ts
  93. 5
      packages/harmony-crypto/test/rlp.test.ts
  94. 0
      packages/harmony-crypto/test/tsconfig.json
  95. 2
      packages/harmony-crypto/tsconfig.json
  96. 0
      packages/harmony-crypto/tsconfig.test.json
  97. 0
      packages/harmony-network/LICENSE
  98. 0
      packages/harmony-network/README.md
  99. 12
      packages/harmony-network/package.json
  100. 6
      packages/harmony-network/src/index.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

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,12 +2,11 @@ language: node_js
sudo: true
dist: trusty
node_js:
- 16
- 10
branches:
except:
- /^v[0-9]/
install:
- yarn
- yarn bootstrap
script:
- yarn test:src
@ -21,5 +20,4 @@ deploy:
github-token: $GITHUB_TOKEN # Set in the settings page of your repository, as a secure variable
keep-history: true
on:
branch: master
branch: master

@ -1,25 +1,38 @@
# Woop JavaScript SDK
[![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)
[![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)
This is the Woop Javascript SDK which provides an easier way to interact with Woop blockchain.
1. [About this SDK](#about-this-sdk)
2. [How to Install](#how-to-install)
1. [Enviorment requirement](#enviorment-requirement)
2. [Install from npm/yarn](#install-from-npmyarn)
3. [Quick start](#quick-start)
3. [Build from source files](#build-from-source-files)
1. [Install `lerna` and `typescript` globally](#install-lerna-and-typescript-globally)
2. [Bootstrap and build](#bootstrap-and-build)
3. [Bundle](#bundle)
4. [Tests](#tests)
1. [Unit tests](#unit-tests)
2. [e2e tests](#e2e-tests)
5. [More examples](#more-examples)
Please read the [documentation](https://jssdk.doc.hmny.io/) for full API doc.
# About this SDK
The SDK includes following packages with package-level documentation and examples inside each package.
A Harmony's blockchain javascript library, which provides an easier way to interact with Harmony's blockchain.
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
# How to Install
This library works on both nodejs and browser. Please use it according to your use case.
@ -35,10 +48,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
@ -46,7 +59,141 @@ yarn add tslib
```
# Building from source files
## 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();
```
# Build from source files
## Install `lerna` and `typescript` globally
@ -61,7 +208,7 @@ yarn bootstrap
## Bundle
Build `umd` and `esm` version javascript for each sub-packages, which can be accessed by `import` or `require`
build `umd` and `esm` version javascript for each sub-packages, which can be accessed by `import` or `require`
```bash
yarn dist
@ -69,20 +216,30 @@ yarn dist
All files are exported in `packages/dist` folder, use `**.esm.js` or `**.umd.js` format
# Running Tests
# Tests
## Unit tests
```bash
yarn test:src
```
## e2e tests
**Contantly updating now, please get back later**
1. edit `.env` file if you have custom setting
2. run harmony node locally, follow this instruction : https://github.com/harmony-one/harmony)
3. wait for 1-2 mins, and run this:
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:
```bash
yarn build && yarn test:e2e
```
# More examples
* [dapp-examples](https://github.com/harmony-one/dapp-examples)

@ -1,70 +0,0 @@
# Release Guidelines
## Before Release
1. Build source first
```bash
yarn build:ts
```
2. Run unit tests
```bash
yarn test:src
```
3. Run e2e tests
```bash
yarn test:e2e
```
4. Clean and build bundle
```bash
yarn dist
```
## Publish to npm using `dev:publish`
The packages is to be published to npm, using `@next` tag using script in `package.json`
Follow steps below to publish a npm verion using `@next` tag
1. Commit all changes to github master
2. Run publish script
```bash
yarn dev:publish
```
3. Select version and confirm all prompts with `Y`
4. See version changes in `npmjs.com`
This will not change the release version of current npm packages(currently 0.0.7), developers have to use `@next` to install from npm.
For example.
```bash
npm install @woop-js/core@next
```
## Publish to npm with `lerna`
Follow steps below to publish a npm verion with latest version
1. Commit all changes to github master
2. Run `lerna publish`, `lerna` is required globally.
```bash
lerna publish
```
3. Select version and confirm all prompts with `Y`
4. See version changes in `npmjs.com`
This will change the release version of current npm packages to the latest version, developers can install from npm directly
For example.
```bash
npm install @woop-js/core
```

@ -1,100 +0,0 @@
# Woop JS-SDK Documentation
## [CLICK ME!!](https://woop-js-sdk-doc.s3-us-west-1.amazonaws.com/index.html) to see the documentation
# metaDocumentation
## Summary
The following content demonstrate how to generate our documentation!
## Step 1: Generate Documentation
### Introduction of TypeDoc
[TypeDoc is used to generate HTML](https://typedoc.org/api/index.html)
> See [TypeDoc command line arguments](https://typedoc.org/guides/options/), to understand how to use them.
> Using `typedoc --help` to see them
>
> **For example:**
> `typedoc --name <Name>` to set the name of header
> `typedoc --theme <default | minimal | path/to/theme>` to set the theme of documation
> `typedoc --readme <path/to/readme | none>` path to readme file that should be displayed on the index page.
> `typedoc --ignoreCompilerErrors` Should TypeDoc generate documentation pages even after the compiler has returned errors?
### Install TypeDoc
Local installation (prefered)
```
$ npm install typedoc --save-dev
```
Golbal CLI installation
```
$ npm install --global typedoc
```
### Install Environemnt
```
$ npm install
```
### Generate HTML
```
$ cd docs
$ npx typedoc --out ./build ../packages/ --ignoreCompilerErrors --theme default --name Woop_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!)
### Create an AWS s3 bucket
Actually, there are just two points needed!
1. Create an AWS S3 bucket, **UNCHECK** `Block all public access`
2. Put the files into the bucket, and set the **public permission** to `Grant public read access to this object(s)`
### Method 1: Use Console
[Here](https://docs.aws.amazon.com/AmazonS3/latest/gsg/CreatingABucket.html) is the documentation of AWS, just follow it!
>Don't forget the two points mentioned above
### Method 2: Use AWS CLI
Reference: [AWS CLI documentation](https://docs.aws.amazon.com/cli/latest/userguide/cli-services-s3-commands.html)
If you have never used AWS CLI, you need follow these to set up your environment first!
- [Install the AWS CLI version 1](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv1.html)
- [Configuring the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)
After that, use AWS CLI to do following
1. Create a Bucket
```
aws s3 mb s3://woop-js-sdk-doc
```
2. List all buckets you have created
```
aws s3 ls
```
3. Uploade the files into bucket
```
$ cd build
$ aws s3 cp ./ s3://your-bucket-name --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers --recursive
```
Here is some explanations
> **./account**
> the path of folder which we want to upload
>
> **s3://woop-js-sdk-doc**
> the bucket name on AWS S3
>
> **--grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers**
> Grant read access to all user
>
> **--recursive**
> Command is performed on all files or objects under the specified directory or prefix.
4. Open the folder in S3 bucket and find `index.html`, get the
`Object URL`, then make it public!

@ -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" }
]
}

@ -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.32"
}

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": [
@ -8,7 +8,7 @@
"scripts": {
"bootstrap": "lerna bootstrap && yarn build",
"watch": "yarn build:ts -w",
"build": "yarn packages:clean && lerna clean -y && lerna link && yarn build:ts",
"build": "yarn packages:clean && lerna clean -y && yarn build:ts",
"build:ts": "tsc -b tsconfig.json",
"build:test": "tsc -b tsconfig.test.json",
"build:e2e": "tsc -b tsconfig.e2e.json",
@ -89,25 +89,25 @@
"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",
"lerna": "^3.20.2",
"lerna": "^3.2.1",
"mkdirp": "^0.5.1",
"prettier": "^1.18.2",
"prettier-plugin-solidity": "^1.0.0-alpha.22",
"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,17 @@
"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",
"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",
"typedoc": "^0.15.0",
"typedoc-plugin-markdown": "^2.1.0",
"typescript": "^3.2",
"typescript-json-schema": "^0.36.0",
"webpack": "^4.20.2",
"webpack-command": "^0.4.1",
"webpack-node-externals": "^1.7.2",
@ -140,10 +138,5 @@
"pre-commit": "pretty-quick --staged"
}
},
"name": "woop-sdk-core",
"dependencies": {
"@woop-js/core": "^0.1.36",
"tslib": "^2.4.0",
"typedoc-plugin-internal-external": "^2.1.1"
}
"name": "harmony-sdk-core"
}

@ -1,12 +0,0 @@
# 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>

@ -0,0 +1,9 @@
# Usage
```typescript
import {Wallet} from '@harmony-js/account'
const wallet=new Wallet()
```

@ -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.32",
"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.32",
"@harmony-js/crypto": "0.1.32",
"@harmony-js/network": "0.1.31",
"@harmony-js/staking": "0.1.32",
"@harmony-js/transaction": "0.1.32",
"@harmony-js/utils": "0.1.28"
},
"gitHead": "56606e9365721729a490c27d6a294e0daf90fbdf"
"gitHead": "0f2c4f00383611397ba83182322be3394451f8d6"
}

@ -1,9 +1,3 @@
/**
* @packageDocumentation
* @module woop-account
*
*/
import {
generatePrivateKey,
getAddressFromPrivateKey,
@ -15,7 +9,7 @@ import {
Keystore,
Signature,
getAddress,
} from '@woop-js/crypto';
} from '@harmony-js/crypto';
import {
isPrivateKey,
@ -23,151 +17,64 @@ 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';
export interface Balance {
balance?: string;
nonce?: number;
shardID?: number;
}
class Account {
/**
* static method create account
*
* @example
* ```javascript
* const account = new Account();
* console.log(account);
* ```
* @function new static method create account
* @return {Account} Account instance
*/
static new(): Account {
const newAcc = new Account()._new();
return newAcc;
}
/**
* Static Method: add a private key to Account
* @function add static method add a private key to Account
* @param {string} key - private Key
*
* @example
* ```javascript
* const account = new Account.add(key_1);
* console.log(account);
* ```
* @return {Account} Account instance
*/
static add(key: string): Account {
const newAcc = new Account()._import(key);
return newAcc;
}
/**@hidden */
privateKey?: string;
/**@hidden */
publicKey?: string;
/**@hidden */
address?: string;
/**@hidden */
balance?: string = '0';
/**@hidden */
nonce?: number = 0;
/**@hidden */
shardID: number;
/**@hidden */
shards: Shards;
/**@hidden */
messenger: Messenger;
/**@hidden */
encrypted: boolean = false;
/**
* check sum address
*
* @example
* ```javascript
* console.log(account.checksumAddress);
* ```
* @function checksumAddress checsumAddress getter
* @return {string} get the checksumAddress
*/
get checksumAddress(): string {
return this.address ? getAddress(this.address).checksum : '';
}
/**
* Get bech32 Address
*
* @example
* ```javascript
* console.log(account.bech32Address);
* ```
*/
get bech32Address(): string {
return this.address ? getAddress(this.address).bech32 : '';
}
/**
* get Bech32 TestNet Address
*
* @example
* ```javascript
* console.log(account.bech32TestNetAddress);
* ```
*/
get bech32TestNetAddress(): string {
return this.address ? getAddress(this.address).bech32TestNet : '';
}
/**
* get Shards number with this Account
*
* @example
* ```javascript
* console.log(account.getShardsCount);
* ```
* @function getShardsCount getShards number with this Account
* @return {number} shard size
*/
get getShardsCount(): number {
return this.shards.size;
}
/**
* Generate an account object
*
* @param key import an existing privateKey, or create a random one
* @param messenger you can setMessage later, or set message on `new`
*
* @example
* ```javascript
* // import the Account class
* const { Account } = require('@woop-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');
*
* // 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
* )
*
* // setMessenger later
* const randomAccount = new Account()
* randomAccount.setMessenger(customMessenger)
*
* // or you can set messenger on `new`
* const randomAccountWithCustomMessenger = new Account(undefined, customMessenger)
*
* // 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)
* ```
*/
constructor(key?: string, messenger: Messenger = defaultMessenger) {
this.messenger = messenger;
if (!key) {
@ -197,10 +104,10 @@ class Account {
async fromFile(keyStore: string, password: string): Promise<Account> {
try {
if (typeof password !== 'string') {
if (!password) {
throw new Error('you must provide password');
}
const file: Keystore = JSON.parse(keyStore.toLowerCase());
const file: Keystore = JSON.parse(keyStore);
const decyptedPrivateKey = await decrypt(file, password);
if (isPrivateKey(decyptedPrivateKey)) {
return this._import(decyptedPrivateKey);
@ -213,18 +120,10 @@ class Account {
}
/**
* Get the account balance
*
* @param blockNumber by default, it's `latest`
*
* @example
* ```javascript
* account.getBalance().then((value) => {
* console.log(value);
* });
* ```
* @function getBalance get Account's balance
* @return {type} {description}
*/
async getBalance(blockNumber: string = 'latest'): Promise<Balance> {
async getBalance(blockNumber: string = 'latest'): Promise<object> {
try {
if (this.messenger) {
const balance = await this.messenger.send(
@ -265,6 +164,7 @@ class Account {
/**
* @function updateShards
* @return {Promise<string>} {description}
*/
async updateBalances(blockNumber: string = 'latest'): Promise<void> {
// this.messenger.setShardingProviders();
@ -283,9 +183,6 @@ class Account {
}
}
/**
* @function signTransaction
*/
async signTransaction(
transaction: Transaction,
updateNonce: boolean = true,
@ -299,18 +196,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 +233,7 @@ class Account {
signature,
rawTransaction,
from:
this.messenger.chainPrefix === ChainType.Woop
this.messenger.chainPrefix === ChainType.Harmony
? this.bech32Address
: this.checksumAddress || '0x',
};
@ -334,16 +243,6 @@ class Account {
return transaction;
}
}
/**
* This function is still in development, coming soon!
*
* @param staking
* @param updateNonce
* @param encodeMode
* @param blockNumber
* @param shardID
*/
async signStaking(
staking: StakingTransaction,
updateNonce: boolean = true,
@ -358,16 +257,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 +285,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',
);
@ -386,40 +296,10 @@ class Account {
return staking;
}
}
/**
* @param messenger
*
* @example
* ```javascript
* // 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
* )
*
* // to create an Account with random privateKey
* // and you can setMessenger later
* const randomAccount = new Account()
* randomAccount.setMessenger(customMessenger)
* ```
*/
setMessenger(messenger: Messenger) {
this.messenger = messenger;
}
/**
* Get account address from shard ID
* @param shardID
*
* @example
* ```javascript
* console.log(account.getAddressFromShardID(0));
*
* > one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7-0
* ```
*/
getAddressFromShardID(shardID: number) {
const shardObject = this.shards.get(shardID);
if (shardObject) {
@ -428,15 +308,6 @@ class Account {
return undefined;
}
}
/**
* Get all shards' addresses from the account
*
* @example
* ```javascript
* console.log(account.getAddresses());
* ```
*/
getAddresses(): string[] {
const addressArray: string[] = [];
for (const [name, val] of this.shards) {
@ -446,19 +317,6 @@ class Account {
return addressArray;
}
/**
* Get the specific shard's balance
*
* @param shardID `shardID` is binding with the endpoint, IGNORE it!
* @param blockNumber by default, it's `latest`
*
* @example
* ```
* account.getShardBalance().then((value) => {
* console.log(value);
* });
* ```
*/
async getShardBalance(shardID: number, blockNumber: string = 'latest') {
const balance = await this.messenger.send(
RPCMethod.GetBalance,
@ -486,37 +344,9 @@ class Account {
nonce: Number.parseInt(hexToNumber(nonce.result), 10),
};
}
/**
* 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
* @ignore
*/
private _new(): Account {
const prv = generatePrivateKey();
@ -530,7 +360,6 @@ class Account {
* @function _import private method import a private Key
* @param {string} key - private key
* @return {Account} Account instance
* @ignore
*/
private _import(key: string): Account {
if (!isPrivateKey(key)) {
@ -551,7 +380,4 @@ class Account {
}
}
/**
* This comment _supports_ [Markdown](https://marked.js.org/)
*/
export { Account };

@ -1,9 +1,4 @@
/**
* @packageDocumentation
* @module woop-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,17 +9,15 @@ 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 */
export interface WalletsInterfaces {
[key: string]: Account;
}
/** @hidden */
export interface Web3TxPrams {
id?: string;
from?: string;
@ -50,29 +43,19 @@ export class HDNode {
}
return bip39.validateMnemonic(phrase);
}
static generateMnemonic(): string {
return bip39.generateMnemonic();
}
public provider: HttpProvider | WSProvider;
public gasLimit: string;
public gasPrice: string;
public messenger: Messenger;
/** @hidden */
private shardID: number;
/** @hidden */
private hdwallet: hdkey | undefined;
/** @hidden */
private path: string;
/** @hidden */
private index: number;
/** @hidden */
private addressCount: number;
/** @hidden */
private addresses: string[];
/** @hidden */
private wallets: WalletsInterfaces;
constructor(
@ -81,7 +64,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 +76,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 +134,6 @@ export class HDNode {
}
return this.addresses;
}
// tslint:disable-next-line: ban-types
getPrivateKey(address: string, cb?: Function) {
if (!cb) {
@ -169,14 +149,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 +194,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 +221,6 @@ export class HDNode {
return signed.getRawTransaction();
}
getAddress(idx?: number) {
if (!idx) {
return this.addresses[0];
@ -250,11 +228,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 +241,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,9 +1,3 @@
/**
* @packageDocumentation
* @module woop-account
* @ignore
*/
export * from './account';
export * from './wallet';
export * from './types';

@ -1,9 +1,3 @@
/**
* @packageDocumentation
* @module woop-account
* @hidden
*/
/**
* test type docs
*/

@ -0,0 +1,8 @@
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,8 @@
/**
* @packageDocumentation
* @module woop-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';
@ -17,45 +12,21 @@ class Wallet {
return bip39.generateMnemonic();
}
/** @hidden */
messenger: Messenger;
/** @hidden */
protected defaultSigner?: string;
/**
* @hidden
* @memberof Wallet
*
*/
private accountMap: Map<string, Account> = new Map();
/**
* get acounts addresses
*
* @memberof Wallet
* @return {string[]} accounts addresses
*
* @example
* ```javascript
* const wallet = new Wallet(customMessenger);
* const key_1 = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e';
* wallet.addByPrivateKey(key_1);
*
* console.log(wallet.accounts);
* ```
*/
get accounts(): string[] {
return [...this.accountMap.keys()];
}
/**
* get the signer of the account, by default, using the first account
*
* @example
* ```javascript
* const wallet = new Wallet(customMessenger);
* const key_1 = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e';
* wallet.addByPrivateKey(key_1);
*
* console.log(wallet.signer)
* ```
*/
get signer(): Account | undefined {
if (this.defaultSigner) {
return this.getAccount(this.defaultSigner);
@ -67,23 +38,6 @@ class Wallet {
}
}
/**
* @example
* ```
* const { Wallet } = require('@woop-js/account');
* const { HttpProvider, Messenger } = require('@woop-js/network');
* const { ChainType, ChainID } = require('@woop-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
* )
*
* const wallet = new Wallet(customMessenger);
* ```
*/
constructor(messenger: Messenger = defaultMessenger) {
this.messenger = messenger;
}
@ -97,18 +51,11 @@ class Wallet {
}
/**
* Add account using Mnemonic phrases
* @function addByMnemonic
* @memberof Wallet
* @description add account using Mnemonic phrases
* @param {string} phrase - Mnemonic phrase
* @param {index} index - index to hdKey root
*
* @example
* ```javascript
* const mnemonic_1 = 'urge clog right example dish drill card maximum mix bachelor section select';
* const wallet = new Wallet(customMessenger);
* wallet.addByMnemonic(mnemonic_1);
*
* console.log(wallet.accounts);
* ```
*/
addByMnemonic(phrase: string, index: number = 0) {
if (!this.isValidMnemonic(phrase)) {
@ -116,25 +63,18 @@ 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);
}
/**
* Add an account using privateKey
*
* @function addByPrivateKey
* @memberof Wallet
* @description add an account using privateKey
* @param {string} privateKey - privateKey to add
* @return {Account} return added Account
*
* @example
* ```javascript
* const wallet = new Wallet(customMessenger);
* const key_1 = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e';
* console.log(wallet.addByPrivateKey(key_1));
* ```
*/
addByPrivateKey(privateKey: string): Account {
try {
@ -155,7 +95,9 @@ class Wallet {
}
/**
* Add an account using privateKey
* @function addByKeyStore
* @memberof Wallet
* @description add an account using privateKey
* @param {string} keyStore - keystore jsonString to add
* @param {string} password - password to decrypt the file
* @return {Account} return added Account
@ -180,17 +122,9 @@ class Wallet {
}
/**
* create a new account using Mnemonic
* @function createAccount
* @description create a new account using Mnemonic
* @return {Account} {description}
*
* @example
* ```javascript
* console.log(wallet.accounts);
* wallet.createAccount();
* wallet.createAccount();
*
* console.log(wallet.accounts);
* ````
*/
async createAccount(password?: string, options?: EncryptOptions): Promise<Account> {
const prv = generatePrivateKey();
@ -206,21 +140,14 @@ class Wallet {
}
/**
* To encrypt an account that lives in the wallet.
* @function encryptAccount
* @memberof Wallet
* @description to encrypt an account that lives in the wallet,
* if encrypted, returns original one, if not found, throw error
* @param {string} address - address in accounts
* @param {string} password - string that used to encrypt
* @param {EncryptOptions} options - encryption options
* @return {Promise<Account>}
*
* @example
* ```javascript
* const key_1 = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e';
* wallet.addByPrivateKey(key_1);
* wallet.encryptAccount('one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7', '12345').then((value) => {
* console.log(value);
* })
* ```
*/
async encryptAccount(
address: string,
@ -241,26 +168,14 @@ class Wallet {
throw error;
}
}
/**
* To decrypt an account that lives in the wallet,if not encrypted, return original,
* @function decryptAccount
* @memberof Wallet
* @description to decrypt an account that lives in the wallet,if not encrypted, return original,
* if not found, throw error
* @param {string} address - address in accounts
* @param {string} password - string that used to encrypt
* @return {Promise<Account>}
*
* @example
* ```javascript
* const key_1 = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e';
* wallet.addByPrivateKey(key_1);
* wallet.encryptAccount('one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7', '12345')
* .then(() => {
* wallet.decryptAccount('one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7', '12345')
* .then((value) =>{
* console.log(value);
* });
* });
* ```
*/
async decryptAccount(address: string, password: string): Promise<Account> {
try {
@ -280,16 +195,11 @@ class Wallet {
}
/**
* Get Account instance using address as param
* @function getAccount
* @memberof Wallet
* @description get Account instance using address as param
* @param {string} address - address hex
* @return {Account} Account instance which lives in Wallet
*
* @example
* ```
* const key_1 = '45e497bd45a9049bcb649016594489ac67b9f052a6cdf5cb74ee2427a60bf25e';
* wallet.addByPrivateKey(key_1);
* console.log(wallet.getAccount('one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7'));
* ```
*/
getAccount(address: string): Account | undefined {
return this.accountMap.get(getAddress(address).basicHex);
@ -308,33 +218,12 @@ class Wallet {
}
}
/**
* Set Customer Messenage
* @param messenger
*
* @example
* ```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
* )
* const wallet = new Wallet();
* wallet.setMessenger(customMessenger);
* console.log(wallet.messenger);
* ```
*/
setMessenger(messenger: Messenger): void {
this.messenger = messenger;
}
/**
* Set signer
*
* @param address one of the address in the accounts
*/
setSigner(address: string): void {
if (!isAddress(address) && !this.getAccount(address)) {
if (!isAddress(address) || !this.getAccount(address)) {
throw new Error('could not set signer');
}
this.defaultSigner = address;
@ -386,7 +275,6 @@ class Wallet {
throw new Error('sign transaction failed');
}
}
async signStaking(
staking: StakingTransaction,
account: Account | undefined = this.signer,
@ -436,14 +324,12 @@ class Wallet {
throw new Error('sign transaction failed');
}
}
/**
* @function isValidMnemonic
* @memberof Wallet
* @description check if Mnemonic is valid
* @param {string} phrase - Mnemonic phrase
* @return {boolean}
* @ignore
*/
private isValidMnemonic(phrase: string): boolean {
if (phrase.trim().split(/\s+/g).length < 12) {

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

@ -1,7 +1,7 @@
{
"name": "@woop-js/contract",
"version": "0.1.58",
"description": "contract libraries for woop",
"name": "@harmony-js/contract",
"version": "0.1.32",
"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.32",
"@harmony-js/crypto": "0.1.32",
"@harmony-js/network": "0.1.31",
"@harmony-js/transaction": "0.1.32",
"@harmony-js/utils": "0.1.28"
},
"gitHead": "56606e9365721729a490c27d6a294e0daf90fbdf"
"gitHead": "0f2c4f00383611397ba83182322be3394451f8d6"
}

@ -1,156 +1,3 @@
/**
# @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);
```
*
* @packageDocumentation
* @module woop-contract
*/
// this file is mainly ported from `ethers.js`, but done some fixes
// 1. added bytesPadRight support
// 2. ts-lint
@ -171,26 +18,22 @@ 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);
/** @hidden */
const One: BN = new BN(1);
/** @hidden */
// const Two: BN = new BN(2);
const Zero: BN = new BN(0);
/** @hidden */
const HashZero = '0x0000000000000000000000000000000000000000000000000000000000000000';
/** @hidden */
const HashZero =
'0x0000000000000000000000000000000000000000000000000000000000000000';
const MaxUint256: BN = hexToBN(
'0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
);
/** @hidden */
export type CoerceFunc = (type: string, value: any) => any;
/** @hidden */
export interface ParamType {
name?: string;
type: string;
@ -200,7 +43,6 @@ export interface ParamType {
// @TODO: should this just be a combined Fragment?
/** @hidden */
export interface EventFragment {
type: string;
name: string;
@ -210,7 +52,6 @@ export interface EventFragment {
inputs: ParamType[];
}
/** @hidden */
export interface FunctionFragment {
type: string;
name: string;
@ -227,15 +68,15 @@ export interface FunctionFragment {
}
///////////////////////////////
/** @hidden */
const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/);
/** @hidden */
const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/);
/** @hidden */
const paramTypeArray = new RegExp(/^(.*)\[([0-9]*)\]$/);
/** @hidden */
export const defaultCoerceFunc: CoerceFunc = (type: string, value: any): any => {
export const defaultCoerceFunc: CoerceFunc = (
type: string,
value: any,
): any => {
const match = type.match(paramTypeNumber);
if (match && parseInt(match[2], 10) <= 48) {
// return value.toNumber();
@ -250,12 +91,9 @@ export const defaultCoerceFunc: CoerceFunc = (type: string, value: any): any =>
///////////////////////////////////
// Parsing for Solidity Signatures
/** @hidden */
const regexParen = new RegExp('^([^)(]*)\\((.*)\\)([^)(]*)$');
/** @hidden */
const regexIdentifier = new RegExp('^[A-Za-z_][A-Za-z0-9_]*$');
/** @hidden */
function verifyType(type: string): string {
// These need to be transformed to their full description
if (type.match(/^uint($|[^1-9])/)) {
@ -267,7 +105,6 @@ function verifyType(type: string): string {
return type;
}
/** @hidden */
interface ParseState {
allowArray?: boolean;
allowName?: boolean;
@ -276,7 +113,6 @@ interface ParseState {
readArray?: boolean;
}
/** @hidden */
interface ParseNode {
parent?: any;
type?: string;
@ -286,7 +122,6 @@ interface ParseNode {
components?: any[];
}
/** @hidden */
function parseParam(param: string, allowIndexed?: boolean): ParamType {
const originalParam = param;
// tslint:disable-next-line: no-shadowed-variable
@ -320,7 +155,9 @@ function parseParam(param: string, allowIndexed?: boolean): ParamType {
node.type = verifyType(node.type);
}
node.components = [{ type: '', name: '', parent: node, state: { allowType: true } }];
node.components = [
{ type: '', name: '', parent: node, state: { allowType: true } },
];
node = node.components[0];
break;
@ -461,7 +298,6 @@ function parseParam(param: string, allowIndexed?: boolean): ParamType {
}
// @TODO: Better return type
/** @hidden */
function parseSignatureEvent(fragment: string): EventFragment {
const abi: EventFragment = {
anonymous: false,
@ -502,18 +338,15 @@ function parseSignatureEvent(fragment: string): EventFragment {
return abi;
}
/** @hidden */
export function parseParamType(type: string): ParamType {
return parseParam(type, true);
}
// @TODO: Allow a second boolean to expose names
/** @hidden */
export function formatParamType(paramType: ParamType): string {
return getParamCoder(defaultCoerceFunc, paramType).type;
}
/** @hidden */
function parseSignatureFunction(fragment: string): FunctionFragment {
const abi: FunctionFragment = {
constant: false,
@ -582,7 +415,7 @@ function parseSignatureFunction(fragment: string): FunctionFragment {
// We have outputs
if (comps.length > 1) {
const right = comps[1].match(regexParen);
if (right === null || right[1].trim() !== '' || right[3].trim() !== '') {
if (right === null || (right[1].trim() !== '' || right[3].trim() !== '')) {
throw new Error('unexpected tokens');
}
@ -606,13 +439,20 @@ function parseSignatureFunction(fragment: string): FunctionFragment {
}
// @TODO: Allow a second boolean to expose names and modifiers
/** @hidden */
export function formatSignature(fragment: EventFragment | FunctionFragment): string {
return fragment.name + '(' + fragment.inputs.map((i) => formatParamType(i)).join(',') + ')';
export function formatSignature(
fragment: EventFragment | FunctionFragment,
): string {
return (
fragment.name +
'(' +
fragment.inputs.map((i) => formatParamType(i)).join(',') +
')'
);
}
/** @hidden */
export function parseSignature(fragment: string): EventFragment | FunctionFragment {
export function parseSignature(
fragment: string,
): EventFragment | FunctionFragment {
if (typeof fragment === 'string') {
// Make sure the "returns" is surrounded by a space and all whitespace is exactly one space
fragment = fragment.replace(/\s/g, ' ');
@ -637,13 +477,11 @@ export function parseSignature(fragment: string): EventFragment | FunctionFragme
///////////////////////////////////
// Coders
/** @hidden */
interface DecodedResult {
consumed: number;
value: any;
}
/** @hidden */
abstract class Coder {
readonly coerceFunc: CoerceFunc;
readonly name: string;
@ -670,7 +508,6 @@ abstract class Coder {
// Clones the functionality of an existing Coder, but without a localName
// tslint:disable-next-line: max-classes-per-file
/** @hidden */
class CoderAnonymous extends Coder {
private coder: Coder;
constructor(coder: Coder) {
@ -686,7 +523,6 @@ class CoderAnonymous extends Coder {
}
// tslint:disable-next-line: max-classes-per-file
/** @hidden */
class CoderNull extends Coder {
constructor(coerceFunc: CoerceFunc, localName: string) {
super(coerceFunc, 'null', '', localName, false);
@ -709,11 +545,15 @@ class CoderNull extends Coder {
}
// tslint:disable-next-line: max-classes-per-file
/** @hidden */
class CoderNumber extends Coder {
readonly size: number;
readonly signed: boolean;
constructor(coerceFunc: CoerceFunc, size: number, signed: boolean, localName: string) {
constructor(
coerceFunc: CoerceFunc,
size: number,
signed: boolean,
localName: string,
) {
const name = (signed ? 'int' : 'uint') + size * 8;
super(coerceFunc, name, name, localName, false);
@ -724,12 +564,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)) {
@ -762,11 +597,15 @@ class CoderNumber extends Coder {
decode(data: Uint8Array, offset: number): DecodedResult {
if (data.length < offset + 32) {
throwError('insufficient data for ' + this.name + ' type', INVALID_ARGUMENT, {
arg: this.localName,
coderType: this.name,
value: hexlify(data.slice(offset, offset + 32)),
});
throwError(
'insufficient data for ' + this.name + ' type',
INVALID_ARGUMENT,
{
arg: this.localName,
coderType: this.name,
value: hexlify(data.slice(offset, offset + 32)),
},
);
}
const junkLength = 32 - this.size;
const dataValue = hexlify(data.slice(offset + junkLength, offset + 32));
@ -785,8 +624,6 @@ class CoderNumber extends Coder {
};
}
}
/** @hidden */
const uint256Coder = new CoderNumber(
(type: string, value: any) => {
return value;
@ -797,7 +634,6 @@ const uint256Coder = new CoderNumber(
);
// tslint:disable-next-line: max-classes-per-file
/** @hidden */
class CoderBoolean extends Coder {
constructor(coerceFunc: CoerceFunc, localName: string) {
super(coerceFunc, 'bool', 'bool', localName, false);
@ -829,7 +665,6 @@ class CoderBoolean extends Coder {
}
// tslint:disable-next-line: max-classes-per-file
/** @hidden */
class CoderFixedBytes extends Coder {
readonly length: number;
constructor(coerceFunc: CoerceFunc, length: number, localName: string) {
@ -876,13 +711,15 @@ class CoderFixedBytes extends Coder {
return {
consumed: 32,
value: this.coerceFunc(this.name, hexlify(data.slice(offset, offset + this.length))),
value: this.coerceFunc(
this.name,
hexlify(data.slice(offset, offset + this.length)),
),
};
}
}
// tslint:disable-next-line: max-classes-per-file
/** @hidden */
class CoderAddress extends Coder {
constructor(coerceFunc: CoerceFunc, localName: string) {
super(coerceFunc, 'address', 'address', localName, false);
@ -919,7 +756,6 @@ class CoderAddress extends Coder {
}
}
/** @hidden */
function _encodeDynamicBytes(value: Uint8Array): Uint8Array {
const dataLength = 32 * Math.ceil(value.length / 32);
const padding = new Uint8Array(dataLength - value.length);
@ -927,8 +763,11 @@ function _encodeDynamicBytes(value: Uint8Array): Uint8Array {
return concat([uint256Coder.encode(new BN(value.length)), value, padding]);
}
/** @hidden */
function _decodeDynamicBytes(data: Uint8Array, offset: number, localName: string): DecodedResult {
function _decodeDynamicBytes(
data: Uint8Array,
offset: number,
localName: string,
): DecodedResult {
if (data.length < offset + 32) {
throwError('insufficient data for dynamicBytes length', INVALID_ARGUMENT, {
arg: localName,
@ -964,7 +803,6 @@ function _decodeDynamicBytes(data: Uint8Array, offset: number, localName: string
}
// tslint:disable-next-line: max-classes-per-file
/** @hidden */
class CoderDynamicBytes extends Coder {
constructor(coerceFunc: CoerceFunc, localName: string) {
super(coerceFunc, 'bytes', 'bytes', localName, true);
@ -991,7 +829,6 @@ class CoderDynamicBytes extends Coder {
}
// tslint:disable-next-line: max-classes-per-file
/** @hidden */
class CoderString extends Coder {
constructor(coerceFunc: CoerceFunc, localName: string) {
super(coerceFunc, 'string', 'string', localName, true);
@ -1015,12 +852,10 @@ class CoderString extends Coder {
}
}
/** @hidden */
function alignSize(size: number): number {
return 32 * Math.ceil(size / 32);
}
/** @hidden */
function pack(coders: Coder[], values: any[]): Uint8Array {
if (Array.isArray(values)) {
// do nothing
@ -1085,8 +920,11 @@ function pack(coders: Coder[], values: any[]): Uint8Array {
return data;
}
/** @hidden */
function unpack(coders: Coder[], data: Uint8Array, offset: number): DecodedResult {
function unpack(
coders: Coder[],
data: Uint8Array,
offset: number,
): DecodedResult {
const baseOffset = offset;
let consumed = 0;
const value: any = [];
@ -1133,11 +971,15 @@ function unpack(coders: Coder[], data: Uint8Array, offset: number): DecodedResul
}
// tslint:disable-next-line: max-classes-per-file
/** @hidden */
class CoderArray extends Coder {
readonly coder: Coder;
readonly length: number;
constructor(coerceFunc: CoerceFunc, coder: Coder, length: number, localName: string) {
constructor(
coerceFunc: CoerceFunc,
coder: Coder,
length: number,
localName: string,
) {
const type = coder.type + '[' + (length >= 0 ? length : '') + ']';
const dynamic = length === -1 || coder.dynamic;
super(coerceFunc, 'array', type, localName, dynamic);
@ -1191,11 +1033,15 @@ class CoderArray extends Coder {
try {
decodedLength = uint256Coder.decode(data, offset);
} catch (error) {
throwError('insufficient data for dynamic array length', INVALID_ARGUMENT, {
arg: this.localName,
coderType: 'array',
value: error.value,
});
throwError(
'insufficient data for dynamic array length',
INVALID_ARGUMENT,
{
arg: this.localName,
coderType: 'array',
value: error.value,
},
);
}
try {
count = decodedLength.value.toNumber();
@ -1223,7 +1069,6 @@ class CoderArray extends Coder {
}
// tslint:disable-next-line: max-classes-per-file
/** @hidden */
class CoderTuple extends Coder {
readonly coders: Coder[];
constructor(coerceFunc: CoerceFunc, coders: Coder[], localName: string) {
@ -1253,7 +1098,6 @@ class CoderTuple extends Coder {
}
}
/** @hidden */
function splitNesting(value: string): any[] {
value = value.trim();
@ -1287,7 +1131,6 @@ function splitNesting(value: string): any[] {
}
// @TODO: Is there a way to return "class"?
/** @hidden */
const paramTypeSimple: { [key: string]: any } = {
address: CoderAddress,
bool: CoderBoolean,
@ -1295,7 +1138,6 @@ const paramTypeSimple: { [key: string]: any } = {
bytes: CoderDynamicBytes,
};
/** @hidden */
function getTupleParamCoder(
coerceFunc: CoerceFunc,
components: any[],
@ -1312,7 +1154,6 @@ function getTupleParamCoder(
return new CoderTuple(coerceFunc, coders, localName);
}
/** @hidden */
function getParamCoder(coerceFunc: CoerceFunc, param: ParamType | any): any {
const coder = paramTypeSimple[param.type];
if (coder) {
@ -1327,7 +1168,12 @@ function getParamCoder(coerceFunc: CoerceFunc, param: ParamType | any): any {
value: param,
});
}
return new CoderNumber(coerceFunc, size / 8, matcher[1] === 'int', param.name || '');
return new CoderNumber(
coerceFunc,
size / 8,
matcher[1] === 'int',
param.name || '',
);
}
const matcher2 = param.type.match(paramTypeBytes);
@ -1348,11 +1194,20 @@ function getParamCoder(coerceFunc: CoerceFunc, param: ParamType | any): any {
param = shallowCopy(param);
param.type = matcher3[1];
param = deepCopy(param);
return new CoderArray(coerceFunc, getParamCoder(coerceFunc, param), size, param.name || '');
return new CoderArray(
coerceFunc,
getParamCoder(coerceFunc, param),
size,
param.name || '',
);
}
if (param.type.substring(0, 5) === 'tuple') {
return getTupleParamCoder(coerceFunc, param.components || [], param.name || '');
return getTupleParamCoder(
coerceFunc,
param.components || [],
param.name || '',
);
}
if (param.type === '') {
@ -1365,7 +1220,6 @@ function getParamCoder(coerceFunc: CoerceFunc, param: ParamType | any): any {
});
}
/** @hidden */
export enum UnicodeNormalizationForm {
current = '',
NFC = 'NFC',
@ -1374,7 +1228,6 @@ export enum UnicodeNormalizationForm {
NFKD = 'NFKD',
}
/** @hidden */
export function toUtf8Bytes(
str: string,
form: UnicodeNormalizationForm = UnicodeNormalizationForm.current,
@ -1418,7 +1271,6 @@ export function toUtf8Bytes(
}
// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499
/** @hidden */
export function toUtf8String(bytes: Arrayish, ignoreErrors?: boolean): string {
bytes = arrayify(bytes) || new Uint8Array();
@ -1455,7 +1307,9 @@ export function toUtf8String(bytes: Arrayish, ignoreErrors?: boolean): string {
} else {
if (!ignoreErrors) {
if ((c & 0xc0) === 0x80) {
throw new Error('invalid utf8 byte sequence; unexpected continuation byte');
throw new Error(
'invalid utf8 byte sequence; unexpected continuation byte',
);
}
throw new Error('invalid utf8 byte sequence; invalid prefix');
}
@ -1496,7 +1350,9 @@ export function toUtf8String(bytes: Arrayish, ignoreErrors?: boolean): string {
if (res === null) {
if (!ignoreErrors) {
throw new Error('invalid utf8 byte sequence; invalid continuation byte');
throw new Error(
'invalid utf8 byte sequence; invalid continuation byte',
);
}
continue;
}
@ -1531,13 +1387,15 @@ export function toUtf8String(bytes: Arrayish, ignoreErrors?: boolean): string {
}
res -= 0x10000;
result += String.fromCharCode(((res >> 10) & 0x3ff) + 0xd800, (res & 0x3ff) + 0xdc00);
result += String.fromCharCode(
((res >> 10) & 0x3ff) + 0xd800,
(res & 0x3ff) + 0xdc00,
);
}
return result;
}
/** @hidden */
export function formatBytes32String(text: string): string {
// Get the bytes
const bytes = toUtf8Bytes(text);
@ -1551,7 +1409,6 @@ export function formatBytes32String(text: string): string {
return hexlify(concat([bytes, HashZero]).slice(0, 32));
}
/** @hidden */
export function parseBytes32String(bytes: Arrayish): string {
const data = arrayify(bytes) || new Uint8Array();
@ -1573,12 +1430,10 @@ export function parseBytes32String(bytes: Arrayish): string {
return toUtf8String(data.slice(0, length));
}
/** @hidden */
export function isType(object: any, type: string): boolean {
return object && object._ethersType === type;
}
/** @hidden */
export function shallowCopy(object: any): any {
const result: any = {};
// tslint:disable-next-line: forin
@ -1588,14 +1443,12 @@ export function shallowCopy(object: any): any {
return result;
}
/** @hidden */
const opaque: { [key: string]: boolean } = {
boolean: true,
number: true,
string: true,
};
/** @hidden */
export function deepCopy(object: any, frozen?: boolean): any {
// Opaque objects are not mutable, so safe to copy by assignment
if (object === undefined || object === null || opaque[typeof object]) {
@ -1649,7 +1502,6 @@ export function deepCopy(object: any, frozen?: boolean): any {
}
// tslint:disable-next-line: max-classes-per-file
/** @hidden */
export class AbiCoder {
coerceFunc: CoerceFunc;
constructor(coerceFunc?: CoerceFunc) {
@ -1685,7 +1537,9 @@ export class AbiCoder {
coders.push(getParamCoder(this.coerceFunc, typeObject));
}, this);
const encodedArray = new CoderTuple(this.coerceFunc, coders, '_').encode(values);
const encodedArray = new CoderTuple(this.coerceFunc, coders, '_').encode(
values,
);
return hexlify(encodedArray);
}
@ -1711,5 +1565,4 @@ export class AbiCoder {
}
}
/** @hidden */
export const defaultAbiCoder: AbiCoder = new AbiCoder();

@ -1,12 +1,6 @@
/**
* @packageDocumentation
* @module woop-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 {
@ -130,7 +124,9 @@ export class AbiCoderClass {
decodedValue = values[index];
returnValues[itemKey] = bnToString(decodedValue);
returnValues[nonIndexedInputItems[index].name] = bnToString(decodedValue);
returnValues[nonIndexedInputItems[index].name] = bnToString(
decodedValue,
);
});
}

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

@ -1,11 +1,5 @@
/**
* @packageDocumentation
* @module woop-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('(')) {
@ -22,7 +16,9 @@ export const flattenTypes = (includeTuple: any, puts: any[]) => {
puts.forEach((param: any) => {
if (typeof param.components === 'object') {
if (param.type.substring(0, 5) !== 'tuple') {
throw new Error('components found but type is not tuple; report on GitHub');
throw new Error(
'components found but type is not tuple; report on GitHub',
);
}
let suffix = '';
const arrayBracket = param.type.indexOf('[');

@ -1,12 +1,6 @@
/**
* @packageDocumentation
* @module woop-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 +14,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 +21,6 @@ export class Contract {
transaction?: Transaction;
status: ContractStatus;
shardID: number;
errorFunc: string = 'Error(string)';
errorFuncSig: string;
constructor(
abi: any = [],
@ -41,7 +30,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 +41,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 +105,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,4 @@
/**
* @packageDocumentation
* @module woop-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,4 @@
/**
* @packageDocumentation
* @module woop-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,4 @@
/**
* @packageDocumentation
* @module woop-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';
@ -33,7 +27,7 @@ export class EventFactory {
new EventMethod(
key,
// params,
this.map(this.abiModel.getEvent(key), this.contract, params),
this.map(this.abiModel, this.contract, params),
this.abiModel.getEvent(key),
this.contract,
);

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

@ -1,18 +1,15 @@
/**
* @packageDocumentation
* @module woop-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,68 +31,69 @@ 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
const signTxs = () => {
this.transaction = this.transaction.map((tx: any) => {
return { ...tx, ...params, gasLimit };
});
this.transaction = this.transaction.map((tx: any) => {
return { ...tx, ...params };
});
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.transaction.emitter.resolve(this.contract);
}
});
})
.catch((error) => {
this.transaction.emitter.reject(error);
});
};
const updateNonce: boolean = params.nonce !== undefined ? false : true;
if (gasLimit === undefined) {
this.estimateGas(params).then((gas) => {
gasLimit = hexToBN(gas);
signTxs();
this.signTransaction(updateNonce).then((signed) => {
this.sendTransaction(signed).then((sent) => {
const [txn, id] = sent;
this.transaction = txn;
this.contract.transaction = this.transaction;
this.confirm(id).then(() => {
this.transaction.emitter.resolve(this.contract);
});
});
} else {
signTxs();
}
});
return this.transaction.emitter;
} catch (error) {
throw error;
}
}
async call(options: any, blockNumber: any = 'latest') {
if (options && !options.gasLimit) {
options.gasLimit = options.gas;
}
try {
const shardID =
options !== undefined && options.shardID !== undefined
? options.shardID
: this.contract.shardID;
const nonce =
this.wallet.signer || (options !== undefined && options.from)
? getResultForData(
await this.wallet.messenger.send(
RPCMethod.GetTransactionCount,
[this.wallet.signer ? this.wallet.signer.address : options.from, blockNumber],
shardID,
),
)
: '0x0';
let gasLimit: any;
// tslint:disable-next-line: prefer-conditional-expression
if (options !== undefined) {
gasLimit = options.gas || options.gasLimit;
} else {
gasLimit = hexToBN(await this.estimateGas());
}
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);
@ -157,30 +155,16 @@ export class ContractMethod {
throw error;
}
}
async estimateGas(options: any) {
async estimateGas() {
try {
interface Payload {
[key: string]: any;
}
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 (this.abiItem.isOfType('constructor')) {
delete estPayload.to;
}
const result = getResultForData(
// tslint:disable-line
await (<Wallet>this.wallet).messenger.send(RPCMethod.EstimateGas, [estPayload]),
await (<Wallet>this.wallet).messenger.send(RPCMethod.EstimateGas, [
{
to: this.transaction.txParams.to,
data: this.transaction.txParams.data,
},
]),
);
if (result.responseType === 'error') {
@ -224,9 +208,7 @@ export class ContractMethod {
'rlp',
'latest', // 'pending',
);
if (this.abiItem.isOfType('constructor')) {
this.contract.address = TransactionFactory.getContractAddress(signed);
}
this.contract.address = TransactionFactory.getContractAddress(signed);
this.contract.setStatus(ContractStatus.SIGNED);
return signed;
} catch (error) {
@ -252,7 +234,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 +249,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 +259,12 @@ 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.contract.address === '0x' ? '0x' : getAddress(this.contract.address).checksum,
data: this.encodeABI(),
};
// tslint:disable-line
const result = new TransactionFactory((<Wallet>this.wallet).messenger).newTx(txObject);
@ -300,32 +275,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,9 +1,3 @@
/**
* @packageDocumentation
* @module woop-contract
* @hidden
*/
import { AbiCoderClass } from '../abi/api';
import { AbiModel } from '../models/types';
import { Contract } from '../contract';
@ -27,18 +21,15 @@ export class MethodFactory {
this.methodKeys.forEach((key: string) => {
const newObject: any = {};
newObject[key] = (...params: any[]) =>
new ContractMethod(key, params, this.abiModel.getMethod(key), this.contract);
new ContractMethod(
key,
params,
this.abiModel.getMethod(key),
this.contract,
);
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,4 @@
/**
* @packageDocumentation
* @module woop-contract
* @hidden
*/
import { isArray } from '@woop-js/utils';
import { isArray } from '@harmony-js/utils';
import { AbiItemModel, AbiOutput, AbiInput } from './types';
export class AbiItem {

@ -1,9 +1,3 @@
/**
* @packageDocumentation
* @module woop-contract
* @hidden
*/
import { AbiItemModel } from './types';
export class AbiModel {
@ -33,20 +27,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 +47,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,9 +1,3 @@
/**
* @packageDocumentation
* @module woop-contract
* @hidden
*/
// defined by web3.js
// fixed
export interface AbiModel {

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

@ -1,10 +1,4 @@
/**
* @packageDocumentation
* @module woop-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 +7,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,9 @@
/**
* @packageDocumentation
* @module woop-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 +11,7 @@ import {
isString,
isAddress,
hexToBN,
} from '@woop-js/utils';
} from '@harmony-js/utils';
import { toUtf8Bytes } from '../abi/abiCoder';
export const inputLogFormatter = (options: any) => {
@ -93,7 +92,11 @@ export const outputLogFormatter = (log: any) => {
};
export const inputBlockNumberFormatter = (blockNumber: any) => {
if (blockNumber === undefined || blockNumber === null || isPredefinedBlockNumber(blockNumber)) {
if (
blockNumber === undefined ||
blockNumber === null ||
isPredefinedBlockNumber(blockNumber)
) {
return blockNumber;
}
@ -109,7 +112,11 @@ export const inputBlockNumberFormatter = (blockNumber: any) => {
};
export const isPredefinedBlockNumber = (blockNumber: string) => {
return blockNumber === 'latest' || blockNumber === 'pending' || blockNumber === 'earliest';
return (
blockNumber === 'latest' ||
blockNumber === 'pending' ||
blockNumber === 'earliest'
);
};
export const inputAddressFormatter = (address: string) => {

@ -1,10 +1,4 @@
/**
* @packageDocumentation
* @module woop-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 +9,6 @@ export const abiMapper = (abi: any[], abiCoder: AbiCoderClass): AbiModel => {
const mappedAbiItems: any = {
methods: {},
events: {},
fallback: undefined,
receive: undefined,
};
let hasConstructor = false;
@ -72,11 +64,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
@ -99,7 +86,9 @@ export const abiMapper = (abi: any[], abiCoder: AbiCoderClass): AbiModel => {
export const isConstant = (abiItem: AbiItemModel) => {
return (
abiItem.stateMutability === 'view' || abiItem.stateMutability === 'pure' || abiItem.constant
abiItem.stateMutability === 'view' ||
abiItem.stateMutability === 'pure' ||
abiItem.constant
);
};

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

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

@ -1,11 +1,6 @@
/**
* @packageDocumentation
* @ignore
*/
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 {

File diff suppressed because one or more lines are too long

@ -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,7 +1,7 @@
{
"name": "@woop-js/core",
"version": "0.1.58",
"description": "woop core package",
"name": "@harmony-js/core",
"version": "0.1.32",
"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.32",
"@harmony-js/contract": "0.1.32",
"@harmony-js/crypto": "0.1.32",
"@harmony-js/network": "0.1.31",
"@harmony-js/staking": "0.1.32",
"@harmony-js/transaction": "0.1.32",
"@harmony-js/utils": "0.1.28"
},
"gitHead": "56606e9365721729a490c27d6a294e0daf90fbdf"
"gitHead": "0f2c4f00383611397ba83182322be3394451f8d6"
}

@ -0,0 +1,526 @@
import {
RPCMethod,
Messenger,
ResponseMiddleware,
WSProvider,
NewPendingTransactions,
NewHeaders,
LogSub,
Syncing,
} from '@harmony-js/network';
import {
assertObject,
AssertType,
// HarmonyCore,
DefaultBlockParams,
} from '@harmony-js/utils';
import { getAddress } from '@harmony-js/crypto';
import { Transaction } from '@harmony-js/transaction';
import { StakingTransaction } from '@harmony-js/staking';
class Blockchain {
messenger: Messenger;
constructor(messenger: Messenger) {
this.messenger = messenger;
}
setMessenger(messenger: Messenger) {
this.messenger = messenger;
}
getRpcResult(result: any) {
if (result instanceof ResponseMiddleware) {
return result.getRaw;
} else {
return result;
}
}
/**
*
*/
@assertObject({
address: ['isValidAddress', AssertType.required],
blockNumber: ['isBlockNumber', AssertType.optional],
shardID: ['isNumber', AssertType.optional],
})
async getBalance({
address,
blockNumber = DefaultBlockParams.latest,
shardID = this.messenger.currentShard,
}: {
address: string;
blockNumber?: string;
shardID?: number;
}) {
const result = await this.messenger.send(
RPCMethod.GetBalance,
[getAddress(address).checksum, blockNumber],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
async getBlockNumber(shardID: number = this.messenger.currentShard) {
const result = await this.messenger.send(
RPCMethod.BlockNumber,
[],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
/**
*
*/
@assertObject({
blockHash: ['isHash', AssertType.required],
returnObject: ['isBoolean', AssertType.optional],
shardID: ['isNumber', AssertType.optional],
})
async getBlockByHash({
blockHash,
returnObject = true,
shardID = this.messenger.currentShard,
}: {
blockHash: string;
returnObject?: boolean;
shardID?: number;
}) {
const result = await this.messenger.send(
RPCMethod.GetBlockByHash,
[blockHash, returnObject],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
/**
*
*/
@assertObject({
blockNumber: ['isBlockNumber', AssertType.optional],
returnObject: ['isBoolean', AssertType.optional],
shardID: ['isNumber', AssertType.optional],
})
async getBlockByNumber({
blockNumber = DefaultBlockParams.latest,
returnObject = true,
shardID = this.messenger.currentShard,
}: {
blockNumber?: string;
returnObject?: boolean;
shardID?: number;
}) {
const result = await this.messenger.send(
RPCMethod.GetBlockByNumber,
[blockNumber, returnObject],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
@assertObject({
blockHash: ['isHash', AssertType.required],
shardID: ['isNumber', AssertType.optional],
})
async getBlockTransactionCountByHash({
blockHash,
shardID = this.messenger.currentShard,
}: {
blockHash: string;
shardID?: number;
}) {
const result = await this.messenger.send(
RPCMethod.GetBlockTransactionCountByHash,
[blockHash],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
@assertObject({
blockNumber: ['isBlockNumber', AssertType.required],
shardID: ['isNumber', AssertType.optional],
})
async getBlockTransactionCountByNumber({
blockNumber,
shardID = this.messenger.currentShard,
}: {
blockNumber: string;
shardID?: number;
}) {
const result = await this.messenger.send(
RPCMethod.GetBlockTransactionCountByNumber,
[blockNumber],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
/**
*
*/
@assertObject({
blockHash: ['isHash', AssertType.required],
index: ['isHex', AssertType.required],
shardID: ['isNumber', AssertType.optional],
})
async getTransactionByBlockHashAndIndex({
blockHash,
index,
shardID = this.messenger.currentShard,
}: {
blockHash: string;
index: string;
shardID?: number;
}) {
const result = await this.messenger.send(
RPCMethod.GetTransactionByBlockHashAndIndex,
[blockHash, index],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
@assertObject({
blockNumber: ['isBlockNumber', AssertType.optional],
index: ['isHex', AssertType.required],
shardID: ['isNumber', AssertType.optional],
})
async getTransactionByBlockNumberAndIndex({
blockNumber = DefaultBlockParams.latest,
index,
shardID = this.messenger.currentShard,
}: {
blockNumber?: string;
index: string;
shardID?: number;
}) {
const result = await this.messenger.send(
RPCMethod.GetTransactionByBlockNumberAndIndex,
[blockNumber, index],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
@assertObject({
txnHash: ['isHash', AssertType.required],
shardID: ['isNumber', AssertType.optional],
})
async getTransactionByHash({
txnHash,
shardID = this.messenger.currentShard,
}: {
txnHash: string;
shardID?: number;
}) {
const result = await this.messenger.send(
RPCMethod.GetTransactionByHash,
[txnHash],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
/**
*
*/
@assertObject({
txnHash: ['isString', AssertType.required],
shardID: ['isNumber', AssertType.optional],
})
async getTransactionReceipt({
txnHash,
shardID = this.messenger.currentShard,
}: {
txnHash: string;
shardID?: number;
}) {
const result = await this.messenger.send(
RPCMethod.GetTransactionReceipt,
[txnHash],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
@assertObject({
txnHash: ['isString', AssertType.required],
shardID: ['isNumber', AssertType.required],
})
async getCxReceiptByHash({ txnHash, shardID }: { txnHash: string; shardID: number }) {
const result = await this.messenger.send(
RPCMethod.GetCXReceiptByHash,
[txnHash],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
/**
*
*/
@assertObject({
address: ['isValidAddress', AssertType.required],
blockNumber: ['isBlockNumber', AssertType.optional],
shardID: ['isNumber', AssertType.optional],
})
async getCode({
address,
blockNumber = DefaultBlockParams.latest,
shardID = this.messenger.currentShard,
}: {
address: string;
blockNumber?: string;
shardID?: number;
}) {
const result = await this.messenger.send(
RPCMethod.GetCode,
[getAddress(address).checksum, blockNumber],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
async net_peerCount(shardID: number = this.messenger.currentShard) {
const result = await this.messenger.send(RPCMethod.PeerCount, [], 'net', shardID);
return this.getRpcResult(result);
}
async net_version(shardID: number = this.messenger.currentShard) {
const result = await this.messenger.send(RPCMethod.NetVersion, [], 'net', shardID);
return this.getRpcResult(result);
}
async getProtocolVersion(shardID: number = this.messenger.currentShard) {
const result = await this.messenger.send(
RPCMethod.ProtocolVersion,
[],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
@assertObject({
address: ['isValidAddress', AssertType.required],
position: ['isHex', AssertType.required],
blockNumber: ['isBlockNumber', AssertType.optional],
shardID: ['isNumber', AssertType.optional],
})
async getStorageAt({
address,
position,
blockNumber = DefaultBlockParams.latest,
shardID = this.messenger.currentShard,
}: {
address: string;
position: string;
blockNumber?: string;
shardID?: number;
}) {
const result = await this.messenger.send(
RPCMethod.GetStorageAt,
[getAddress(address).checksum, position, blockNumber],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
@assertObject({
address: ['isValidAddress', AssertType.required],
blockNumber: ['isBlockNumber', AssertType.optional],
shardID: ['isNumber', AssertType.optional],
})
async getTransactionCount({
address,
blockNumber = DefaultBlockParams.latest,
shardID = this.messenger.currentShard,
}: {
address: string;
blockNumber?: string;
shardID?: number;
}) {
const result = await this.messenger.send(
RPCMethod.GetTransactionCount,
[getAddress(address).checksum, blockNumber],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
async getShardingStructure() {
const result = await this.messenger.send(
RPCMethod.GetShardingStructure,
[],
this.messenger.chainPrefix,
);
return this.getRpcResult(result);
}
async sendTransaction(transaction: Transaction) {
if (!transaction.isSigned() || !transaction) {
throw new Error('transaction is not signed or not exist');
}
const result = await this.messenger.send(
RPCMethod.SendRawTransaction,
[transaction.getRawTransaction()],
this.messenger.chainPrefix,
typeof transaction.txParams.shardID === 'string'
? Number.parseInt(transaction.txParams.shardID, 10)
: transaction.txParams.shardID,
);
return this.getRpcResult(result);
}
async sendRawTransaction(transaction: Transaction) {
if (!transaction.isSigned() || !transaction) {
throw new Error('transaction is not signed or not exist');
}
const [txn, result] = await transaction.sendTransaction();
if (txn.isPending()) {
return result;
}
}
createObservedTransaction(transaction: Transaction) {
try {
transaction.sendTransaction().then((response: any) => {
const [txReturned, TranID] = response;
txReturned.confirm(TranID).then((txConfirmed: Transaction) => {
transaction.emitter.resolve(txConfirmed);
});
});
return transaction.emitter;
} catch (err) {
throw err;
}
}
async sendRawStakingTransaction(staking: StakingTransaction) {
if (!staking.isSigned() || !staking) {
throw new Error('staking transaction is not signed or not exist');
}
const [txn, result] = await staking.sendTransaction();
if (txn.isPending()) {
return result;
}
}
createObservedStakingTransaction(staking: StakingTransaction) {
try {
staking.sendTransaction().then((response: any) => {
const [txReturned, TranID] = response;
txReturned.confirm(TranID).then((txConfirmed: StakingTransaction) => {
staking.emitter.resolve(txConfirmed);
});
});
return staking.emitter;
} catch (err) {
throw err;
}
}
@assertObject({
to: ['isValidAddress', AssertType.optional],
data: ['isHex', AssertType.optional],
shardID: ['isNumber', AssertType.optional],
})
async estimateGas({
to,
data,
shardID = this.messenger.currentShard,
}: {
to: string;
data: string;
shardID?: number;
}) {
const result = await this.messenger.send(
RPCMethod.EstimateGas,
[{ to: getAddress(to).checksum, data }],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
async gasPrice(shardID: number = this.messenger.currentShard) {
const result = await this.messenger.send(
RPCMethod.GasPrice,
[],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
async call({
payload,
blockNumber = DefaultBlockParams.latest,
shardID = this.messenger.currentShard,
}: {
payload: any;
blockNumber?: string;
shardID?: number;
}) {
const result = await this.messenger.send(
RPCMethod.Call,
[payload, blockNumber],
this.messenger.chainPrefix,
shardID,
);
return this.getRpcResult(result);
}
newPendingTransactions(shardID: number = this.messenger.currentShard) {
if (this.messenger.provider instanceof WSProvider) {
return new NewPendingTransactions(this.messenger, shardID);
} else {
throw new Error('HttpProvider does not support this feature');
}
}
newBlockHeaders(shardID: number = this.messenger.currentShard) {
if (this.messenger.provider instanceof WSProvider) {
return new NewHeaders(this.messenger, shardID);
} else {
throw new Error('HttpProvider does not support this feature');
}
}
syncing(shardID: number = this.messenger.currentShard) {
if (this.messenger.provider instanceof WSProvider) {
return new Syncing(this.messenger, shardID);
} else {
throw new Error('HttpProvider does not support this feature');
}
}
logs(options: any, shardID: number = this.messenger.currentShard) {
if (this.messenger.provider instanceof WSProvider) {
return new LogSub(options, this.messenger, shardID);
} else {
throw new Error('HttpProvider does not support this feature');
}
}
}
export { Blockchain };

@ -0,0 +1,99 @@
import * as crypto from '@harmony-js/crypto';
import * as utils from '@harmony-js/utils';
import { Provider, HttpProvider, Messenger, WSProvider, ShardingItem } from '@harmony-js/network';
import { TransactionFactory, Transaction } from '@harmony-js/transaction';
import { StakingTransaction } from '@harmony-js/staking';
import { ContractFactory, Contract } from '@harmony-js/contract';
import { Wallet, Account } from '@harmony-js/account';
import { Blockchain } from './blockchain';
import { HarmonyConfig } from './util';
export class Harmony extends utils.HarmonyCore {
Modules = {
HttpProvider,
WSProvider,
Messenger,
Blockchain,
TransactionFactory,
Wallet,
Transaction,
StakingTransaction,
Account,
Contract,
};
messenger: Messenger;
transactions: TransactionFactory;
wallet: Wallet;
blockchain: Blockchain;
contracts: ContractFactory;
crypto: any;
utils: any;
defaultShardID?: number;
private provider: HttpProvider | WSProvider;
constructor(
url: string,
config: HarmonyConfig = {
chainId: utils.defaultConfig.Default.Chain_ID,
chainType: utils.defaultConfig.Default.Chain_Type,
},
) {
super(config.chainType, config.chainId);
const providerUrl = config.chainUrl || url || utils.defaultConfig.Default.Chain_URL;
this.provider = new Provider(providerUrl).provider;
this.messenger = new Messenger(this.provider, this.chainType, this.chainId);
this.blockchain = new Blockchain(this.messenger);
this.transactions = new TransactionFactory(this.messenger);
this.wallet = new Wallet(this.messenger);
this.contracts = new ContractFactory(this.wallet);
this.crypto = crypto;
this.utils = utils;
this.defaultShardID = config.shardID;
if (this.defaultShardID !== undefined) {
this.setShardID(this.defaultShardID);
}
}
public setProvider(provider: string | HttpProvider | WSProvider): void {
this.provider = new Provider(provider).provider;
this.messenger.setProvider(this.provider);
this.setMessenger(this.messenger);
}
public setChainId(chainId: utils.ChainID) {
this.chainId = chainId;
this.messenger.setChainId(this.chainId);
this.setMessenger(this.messenger);
}
public setShardID(shardID: number) {
this.defaultShardID = shardID;
this.messenger.setDefaultShardID(this.defaultShardID);
this.setMessenger(this.messenger);
}
public setChainType(chainType: utils.ChainType) {
this.chainType = chainType;
this.messenger.setChainType(this.chainType);
this.setMessenger(this.messenger);
}
public shardingStructures(shardingStructures: ShardingItem[]) {
for (const shard of shardingStructures) {
const shardID =
typeof shard.shardID === 'string' ? Number.parseInt(shard.shardID, 10) : shard.shardID;
this.messenger.shardProviders.set(shardID, {
current: shard.current !== undefined ? shard.current : false,
shardID,
http: shard.http,
ws: shard.ws,
});
}
this.setMessenger(this.messenger);
}
private setMessenger(messenger: Messenger) {
this.blockchain.setMessenger(messenger);
this.wallet.setMessenger(messenger);
this.transactions.setMessenger(messenger);
}
}

@ -1,8 +1,3 @@
/**
* @packageDocumentation
* @module woop-core
*/
import {
HttpProvider,
WSProvider,
@ -10,35 +5,30 @@ 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 {
MathWallet = 'MathWallet',
OneWallet = 'OneWallet',
}
/** @hidden */
export interface ExtensionAccount {
address: 'string';
name: 'string';
}
/** @hidden */
export interface ExtensionNetwork {
chain_url: string;
net_version: number;
}
/** @hidden */
export interface ExtensionInterface {
signTransaction: (
transaction: Transaction,
@ -47,64 +37,34 @@ export interface ExtensionInterface {
blockNumber: string,
) => Promise<Transaction>;
getAccount: () => Promise<ExtensionAccount>;
forgetIdentity: () => Promise<void>;
messenger?: Messenger;
version: string;
isMathWallet?: boolean;
isOneWallet?: boolean;
network: ExtensionNetwork;
}
export class WoopExtension {
/**@ignore*/
export class HarmonyExtension {
extensionType: ExtensionType | null;
/**@ignore*/
wallet: ExtensionInterface;
/**@ignore*/
provider: HttpProvider | WSProvider;
/**@ignore*/
messenger: Messenger;
/**@ignore*/
blockchain: Blockchain;
/**@ignore*/
transactions: TransactionFactory;
/**@ignore*/
contracts: ContractFactory;
/**@ignore*/
crypto: any;
/**@ignore*/
utils: any;
/**@ignore*/
defaultShardID?: number;
/**
* Create an blockchain instance support wallet injection
*
* @param wallet could be MathWallet or OneWallet instance
* @param config (optional), using default `Chain_Id` and `Chain_Type`
*
* @example
* ```javascript
* // Using Mathwallet instance
* export const initEx = async() => {
* wikiEx = new WoopExtension(window.woop);
* }
* // Using OneWallet instance
* export const initEx = async() => {
* wikiEx = new WoopExtension(window.onewallet);
* }
* ```
*/
constructor(
wallet: ExtensionInterface,
config: WoopConfig = {
config: HarmonyConfig = {
chainId: utils.defaultConfig.Default.Chain_ID,
chainType: utils.defaultConfig.Default.Chain_Type,
},
) {
this.extensionType = null;
this.wallet = wallet;
// check if it is mathwallet or onewallet
// check if it is mathwallet
this.isExtension(this.wallet);
if (wallet.messenger) {
@ -121,31 +81,12 @@ export class WoopExtension {
this.crypto = crypto;
this.utils = utils;
}
/**
* Will change the provider for its module.
*
* @param provider a valid provider, you can replace it with your own working node
*
* @example
* ```javascript
* const tmp = wikiEx.setProvider('http://localhost:9500');
* ```
*/
public setProvider(provider: string | HttpProvider | WSProvider): void {
this.provider = new Provider(provider).provider;
this.messenger.setProvider(this.provider);
this.setMessenger(this.messenger);
}
/**
* Change the Shard ID
*
* @example
* ```
* wikiEx.setShardID(2);
* ```
*/
public setShardID(shardID: number) {
this.defaultShardID = shardID;
this.messenger.setDefaultShardID(this.defaultShardID);
@ -155,12 +96,11 @@ export class WoopExtension {
public isExtension(wallet: ExtensionInterface) {
let isExtension = false;
this.extensionType = null;
if (wallet.isMathWallet || wallet.isOneWallet) {
if (wallet.isMathWallet) {
isExtension = true;
if (wallet.isMathWallet) this.extensionType = ExtensionType.MathWallet;
else this.extensionType = ExtensionType.OneWallet;
this.extensionType = ExtensionType.MathWallet;
// remake signTransaction of MathWallet or OneWallet
// remake signTransaction of MathWallet
const { signTransaction } = this.wallet;
this.wallet.signTransaction = async (
transaction: Transaction,
@ -172,7 +112,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 +122,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({
@ -199,49 +139,12 @@ export class WoopExtension {
}
return;
}
/**
* Get the wallet account
*
* @example
* ```javascript
* const account = wikiEx.login();
* console.log(account);
* ```
*/
public async login() {
const account = await this.wallet.getAccount();
// Use address
return account;
}
/**
* Log out the wallet account
*
* @example
* ```javascript
* wikiEx.logout();
* ```
*/
public async logout() {
await this.wallet.forgetIdentity();
}
/**
* Set the sharding Structure
*
* @param shardingStructures The array of information of sharding structures
*
* @example
* ```javascript
* wikiEx.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",
* "shardID":1,"ws":"ws://127.0.0.1:9801"}
* ]);
* ```
*/
public shardingStructures(shardingStructures: ShardingItem[]) {
for (const shard of shardingStructures) {
const shardID =
@ -255,8 +158,6 @@ export class WoopExtension {
}
this.setMessenger(this.messenger);
}
/**@ignore*/
private setMessenger(messenger: Messenger) {
this.blockchain.setMessenger(messenger);
this.wallet.messenger = messenger;

@ -0,0 +1,5 @@
export * from './harmony';
export * from './blockchain';
export * from './truffleProvider';
export * from './harmonyExtension';
export * from './types';

@ -1,21 +1,12 @@
/**
* @packageDocumentation
* @module woop-core
* @hidden
*/
import {
HttpProvider,
WSProvider,
RPCRequestPayload,
ResponseMiddleware,
} from '@woop-js/network';
import { ChainID, ChainType, Unit, isBech32Address } from '@woop-js/utils';
import { HDNode } from '@woop-js/account';
import { fromBech32, HRP } from '@woop-js/crypto';
} from '@harmony-js/network';
const packageInfo = { version: '1.0.0' };
import { ChainID, ChainType, Unit } from '@harmony-js/utils';
import { HDNode } from '@harmony-js/account';
export interface ArgsResolver {
newArgs: any;
@ -30,13 +21,11 @@ export interface HDOptions {
index: number;
addressCount: number;
}
export interface ChainOptions {
shardID: number;
chainType: ChainType;
chainId: ChainID;
}
export interface TransactionOptions {
gasLimit: string;
gasPrice: string;
@ -52,8 +41,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 +65,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 +79,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 +95,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',
},
@ -144,29 +133,13 @@ export class TruffleProvider extends HDNode {
jsonrpc: '2.0',
};
}
case 'web3_clientVersion': {
callback(null, {
result: `Woop/${packageInfo.version}/@woop-js`,
id,
jsonrpc: '2.0',
});
return {
result: `Woop/${packageInfo.version}/@woop-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)
@ -179,9 +152,6 @@ export class TruffleProvider extends HDNode {
.toWei()
.toString('hex')}`;
}
if (isBech32Address(response.result.miner)) {
response.result.miner = fromBech32(response.result.miner, HRP);
}
callback(null, response);
} catch (error) {
throw error;
@ -191,7 +161,7 @@ export class TruffleProvider extends HDNode {
}
default: {
// wiki_getBlockByNumber
// hmy_getBlockByNumber
const result = await this.provider.send(
newArgs,
@ -213,7 +183,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,25 @@
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,7 @@
/**
* @packageDocumentation
* @module woop-core
* @hidden
*/
import { ChainType, ChainID, defaultConfig } from '@harmony-js/utils';
import { Harmony } from './harmony';
import { ChainType, ChainID, defaultConfig } from '@woop-js/utils';
import { Woop } from './woop';
export interface WoopConfig {
export interface HarmonyConfig {
chainUrl?: string;
chainType: ChainType;
chainId: ChainID;
@ -17,18 +11,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 +61,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 };
}

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

@ -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,7 +1,7 @@
{
"name": "@woop-js/crypto",
"version": "0.1.58",
"description": "crypto libraries for woop",
"name": "@harmony-js/crypto",
"version": "0.1.32",
"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.28",
"aes-js": "^3.1.2",
"bip39": "^2.5.0",
"bn.js": "^4.11.8",
@ -27,8 +27,8 @@
"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"
"gitHead": "775e2ba36924fcffd8d2c0b73587b549ed90bb81"
}

@ -0,0 +1,80 @@
import { isAddress, isBech32Address, isBech32TestNetAddress } from '@harmony-js/utils';
import { toChecksumAddress } from './keyTool';
import { fromBech32, toBech32, HRP, tHRP } from './bech32';
export class HarmonyAddress {
// static validator
static isValidBasic(str: string) {
const toTest = new HarmonyAddress(str);
return toTest.raw === toTest.basic;
}
// static validator
static isValidChecksum(str: string) {
const toTest = new HarmonyAddress(str);
return toTest.raw === toTest.checksum;
}
// static validator
static isValidBech32(str: string) {
const toTest = new HarmonyAddress(str);
return toTest.raw === toTest.bech32;
}
// static validator
static isValidBech32TestNet(str: string) {
const toTest = new HarmonyAddress(str);
return toTest.raw === toTest.bech32TestNet;
}
raw: string;
basic: string;
get basicHex() {
return `0x${this.basic}`;
}
get checksum() {
return toChecksumAddress(`0x${this.basic}`);
}
get bech32() {
return toBech32(this.basic, HRP);
}
get bech32TestNet() {
return toBech32(this.basic, tHRP);
}
constructor(raw: string) {
this.raw = raw;
this.basic = this.getBasic(this.raw);
}
private getBasic(addr: string) {
const basicBool = isAddress(addr);
const bech32Bool = isBech32Address(addr);
const bech32TestNetBool = isBech32TestNetAddress(addr);
if (basicBool) {
return addr.replace('0x', '').toLowerCase();
}
if (bech32Bool) {
const fromB32 = fromBech32(addr, HRP);
return fromB32.replace('0x', '').toLowerCase();
}
if (bech32TestNetBool) {
const fromB32TestNet = fromBech32(addr, tHRP);
return fromB32TestNet.replace('0x', '').toLowerCase();
}
throw new Error(`"${addr}" is an invalid address format`);
}
}
export function getAddress(address: string) {
try {
return new HarmonyAddress(address);
} catch (error) {
throw error;
}
}

@ -1,10 +1,4 @@
/**
* @packageDocumentation
* @module woop-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 +121,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,21 +178,25 @@ 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)) {
throw new Error('Invalid address format.');
}
const addrBz = convertBits(Buffer.from(address.replace('0x', ''), 'hex'), 8, 5);
const addrBz = convertBits(
Buffer.from(address.replace('0x', ''), 'hex'),
8,
5,
);
if (addrBz === null) {
throw new Error('Could not convert byte Buffer to 5-bit Buffer');
@ -210,7 +208,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,9 +1,3 @@
/**
* @packageDocumentation
* @module woop-crypto
* @hidden
*/
// This file is ported from ether.js/src.ts/utils/bytes.ts
// and done some fixes
@ -31,14 +25,16 @@ export function isHexable(value: any): value is Hexable {
}
function addSlice(array: Uint8Array): Uint8Array {
if (typeof array === 'object' && typeof array.slice === 'function') {
if (array.slice) {
return array;
}
// tslint:disable-next-line: only-arrow-functions
array.slice = function() {
const args = Array.prototype.slice.call(arguments);
return addSlice(new Uint8Array(Array.prototype.slice.apply(array, [args[0], args[1]])));
return addSlice(
new Uint8Array(Array.prototype.slice.apply(array, [args[0], args[1]])),
);
};
return array;
@ -68,10 +64,11 @@ export function isArrayish(value: any): value is Arrayish {
export function arrayify(value: Arrayish | Hexable): Uint8Array | null {
if (value == null) {
errors.throwError('cannot convert null value to array', errors.INVALID_ARGUMENT, {
arg: 'value',
value,
});
errors.throwError(
'cannot convert null value to array',
errors.INVALID_ARGUMENT,
{ arg: 'value', value },
);
}
if (isHexable(value)) {
@ -89,10 +86,11 @@ export function arrayify(value: Arrayish | Hexable): Uint8Array | null {
}
if (match !== null && match[1] !== '0x') {
errors.throwError('hex string must have 0x prefix', errors.INVALID_ARGUMENT, {
arg: 'value',
value,
});
errors.throwError(
'hex string must have 0x prefix',
errors.INVALID_ARGUMENT,
{ arg: 'value', value },
);
}
value = value.substring(2);
@ -205,10 +203,11 @@ export function hexlify(value: Arrayish | Hexable | number): string {
if (typeof value === 'number') {
if (value < 0) {
errors.throwError('cannot hexlify negative value', errors.INVALID_ARGUMENT, {
arg: 'value',
value,
});
errors.throwError(
'cannot hexlify negative value',
errors.INVALID_ARGUMENT,
{ arg: 'value', value },
);
}
// @TODO: Roll this into the above error as a numeric fault (overflow); next version, not backward compatible
@ -247,10 +246,11 @@ export function hexlify(value: Arrayish | Hexable | number): string {
}
if (match !== null && match[1] !== '0x') {
errors.throwError('hex string must have 0x prefix', errors.INVALID_ARGUMENT, {
arg: 'value',
value,
});
errors.throwError(
'hex string must have 0x prefix',
errors.INVALID_ARGUMENT,
{ arg: 'value', value },
);
}
if (value.length % 2) {
@ -283,7 +283,11 @@ export function hexDataLength(data: string) {
return (data.length - 2) / 2;
}
export function hexDataSlice(data: string, offset: number, endOffset?: number): string {
export function hexDataSlice(
data: string,
offset: number,
endOffset?: number,
): string {
if (!isHexString(data)) {
errors.throwError('invalid hex data', errors.INVALID_ARGUMENT, {
arg: 'value',
@ -342,7 +346,9 @@ export function bytesPadLeft(value: string, byteLength: number): string {
const striped = value.substring(2);
if (striped.length > byteLength * 2) {
throw new Error(`hex string length = ${striped.length} beyond byteLength=${byteLength}`);
throw new Error(
`hex string length = ${striped.length} beyond byteLength=${byteLength}`,
);
}
const padLength = byteLength * 2 - striped.length;
const returnValue = '0x' + '0'.repeat(padLength) + striped;
@ -358,7 +364,9 @@ export function bytesPadRight(value: string, byteLength: number): string {
const striped = value.substring(2);
if (striped.length > byteLength * 2) {
throw new Error(`hex string length = ${striped.length} beyond byteLength=${byteLength}`);
throw new Error(
`hex string length = ${striped.length} beyond byteLength=${byteLength}`,
);
}
const padLength = byteLength * 2 - striped.length;
const returnValue = '0x' + striped + '0'.repeat(padLength);
@ -424,7 +432,13 @@ export function splitSignature(signature: Arrayish | Signature): Signature {
export function joinSignature(signature: Signature): string {
signature = splitSignature(signature);
return hexlify(concat([signature.r, signature.s, signature.recoveryParam ? '0x1c' : '0x1b']));
return hexlify(
concat([
signature.r,
signature.s,
signature.recoveryParam ? '0x1c' : '0x1b',
]),
);
}
/**

@ -1,97 +1,13 @@
/**
# @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);
* });
* });
```
*
* @packageDocumentation
* @module woop-crypto
*/
// This file is ported from ether.js/src.ts/errors.ts
// Unknown Error
/** @hidden */
export const UNKNOWN_ERROR = 'UNKNOWN_ERROR';
// Not implemented
/** @hidden */
export const NOT_IMPLEMENTED = 'NOT_IMPLEMENTED';
// Missing new operator to an object
// - name: The name of the class
/** @hidden */
export const MISSING_NEW = 'MISSING_NEW';
// Call exception
@ -102,63 +18,55 @@ export const MISSING_NEW = 'MISSING_NEW';
// - errorSignature?: The EIP848 error signature
// - errorArgs?: The EIP848 error parameters
// - reason: The reason (only for EIP848 "Error(string)")
/** @hidden */
export const CALL_EXCEPTION = 'CALL_EXCEPTION';
// Invalid argument (e.g. value is incompatible with type) to a function:
// - argument: The argument name that was invalid
// - value: The value of the argument
/** @hidden */
export const INVALID_ARGUMENT = 'INVALID_ARGUMENT';
// Missing argument to a function:
// - count: The number of arguments received
// - expectedCount: The number of arguments expected
/** @hidden */
export const MISSING_ARGUMENT = 'MISSING_ARGUMENT';
// Too many arguments
// - count: The number of arguments received
// - expectedCount: The number of arguments expected
/** @hidden */
export const UNEXPECTED_ARGUMENT = 'UNEXPECTED_ARGUMENT';
// Numeric Fault
// - operation: the operation being executed
// - fault: the reason this faulted
/** @hidden */
export const NUMERIC_FAULT = 'NUMERIC_FAULT';
// Insufficien funds (< value + gasLimit * gasPrice)
// - transaction: the transaction attempted
/** @hidden */
export const INSUFFICIENT_FUNDS = 'INSUFFICIENT_FUNDS';
// Nonce has already been used
// - transaction: the transaction attempted
/** @hidden */
export const NONCE_EXPIRED = 'NONCE_EXPIRED';
// The replacement fee for the transaction is too low
// - transaction: the transaction attempted
/** @hidden */
export const REPLACEMENT_UNDERPRICED = 'REPLACEMENT_UNDERPRICED';
// Unsupported operation
// - operation
/** @hidden */
export const UNSUPPORTED_OPERATION = 'UNSUPPORTED_OPERATION';
// tslint:disable-next-line: variable-name
/** @hidden */
let _permanentCensorErrors = false;
// tslint:disable-next-line: variable-name
/** @hidden */
let _censorErrors = false;
// @TODO: Enum
/** @hidden */
export function throwError(message: string, code: string | null | undefined, params: any): never {
export function throwError(
message: string,
code: string | null | undefined,
params: any,
): never {
if (_censorErrors) {
throw new Error('unknown error');
}
@ -197,15 +105,17 @@ export function throwError(message: string, code: string | null | undefined, par
throw error;
}
/** @hidden */
export function checkNew(self: any, kind: any): void {
if (!(self instanceof kind)) {
throwError('missing new', MISSING_NEW, { name: kind.name });
}
}
/** @hidden */
export function checkArgumentCount(count: number, expectedCount: number, suffix?: string): void {
export function checkArgumentCount(
count: number,
expectedCount: number,
suffix?: string,
): void {
if (!suffix) {
suffix = '';
}
@ -223,7 +133,6 @@ export function checkArgumentCount(count: number, expectedCount: number, suffix?
}
}
/** @hidden */
export function setCensorship(censorship: boolean, permanent?: boolean): void {
if (_permanentCensorErrors) {
throwError('error censorship permanent', UNSUPPORTED_OPERATION, {
@ -235,7 +144,6 @@ export function setCensorship(censorship: boolean, permanent?: boolean): void {
_permanentCensorErrors = !!permanent;
}
/** @hidden */
export function checkNormalize(): void {
try {
// Make sure all forms of normalization are supported
@ -247,18 +155,21 @@ export function checkNormalize(): void {
}
});
if (String.fromCharCode(0xe9).normalize('NFD') !== String.fromCharCode(0x65, 0x0301)) {
if (
String.fromCharCode(0xe9).normalize('NFD') !==
String.fromCharCode(0x65, 0x0301)
) {
throw new Error('broken implementation');
}
} catch (error) {
throwError('platform missing String.prototype.normalize', UNSUPPORTED_OPERATION, {
operation: 'String.prototype.normalize',
form: error.message,
});
throwError(
'platform missing String.prototype.normalize',
UNSUPPORTED_OPERATION,
{ operation: 'String.prototype.normalize', form: error.message },
);
}
}
/** @hidden */
const LogLevels: { [name: string]: number } = {
debug: 1,
default: 2,
@ -267,10 +178,8 @@ const LogLevels: { [name: string]: number } = {
error: 4,
off: 5,
};
/** @hidden */
let LogLevel = LogLevels.default;
/** @hidden */
export function setLogLevel(logLevel: string): void {
const level = LogLevels[logLevel];
if (level == null) {
@ -280,7 +189,6 @@ export function setLogLevel(logLevel: string): void {
LogLevel = level;
}
/** @hidden */
function log(logLevel: string, args: [any?, ...any[]]): void {
if (LogLevel > LogLevels[logLevel]) {
return;
@ -288,12 +196,10 @@ function log(logLevel: string, args: [any?, ...any[]]): void {
console.log.apply(console, args);
}
/** @hidden */
export function warn(...args: [any?, ...any[]]): void {
log('warn', args);
}
/** @hidden */
export function info(...args: [any?, ...any[]]): void {
log('info', args);
}

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

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

@ -1,16 +1,10 @@
/**
* @packageDocumentation
* @module woop-crypto
*/
import elliptic from 'elliptic';
import * as bytes from './bytes';
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 +76,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,20 +1,15 @@
/**
* @packageDocumentation
* @module woop-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';
import { keccak256 } from './keccak256';
import { KDF, KDFParams, EncryptOptions, PBKDF2Params, ScryptParams, Keystore } from './types';
/** @hidden */
const DEFAULT_ALGORITHM = 'aes-128-ctr';
/**
@ -63,7 +58,9 @@ export const encrypt = async (
if (!isPrivateKey(privateKey)) {
throw new Error('privateKey is not correct');
}
if (typeof password !== 'string') {
// TODO: should use isString() to implement this
if (!password) {
throw new Error('password is not found');
}
const address = getAddressFromPrivateKey(privateKey);
@ -99,7 +96,7 @@ export const encrypt = async (
version: 3,
id: uuid.v4({ random: uuidRandom || hexToIntArray(randomBytes(16)) }),
address: address.toLowerCase().replace('0x', ''),
crypto: {
Crypto: {
ciphertext: ciphertext.toString('hex'),
cipherparams: {
iv: iv.toString('hex'),
@ -119,15 +116,15 @@ export const encrypt = async (
* @return {string} privateKey
*/
export const decrypt = async (keystore: Keystore, password: string): Promise<string> => {
const ciphertext = Buffer.from(keystore.crypto.ciphertext, 'hex');
const iv = Buffer.from(keystore.crypto.cipherparams.iv, 'hex');
const { kdfparams } = keystore.crypto;
const ciphertext = Buffer.from(keystore.Crypto.ciphertext, 'hex');
const iv = Buffer.from(keystore.Crypto.cipherparams.iv, 'hex');
const { kdfparams } = keystore.Crypto;
const derivedKey = await getDerivedKey(Buffer.from(password), keystore.crypto.kdf, kdfparams);
const derivedKey = await getDerivedKey(Buffer.from(password), keystore.Crypto.kdf, kdfparams);
const mac = keccak256(concat([derivedKey.slice(16, 32), ciphertext])).replace('0x', '');
if (mac.toUpperCase() !== keystore.crypto.mac.toUpperCase()) {
if (mac.toUpperCase() !== keystore.Crypto.mac.toUpperCase()) {
return Promise.reject(new Error('Failed to decrypt.'));
}
@ -139,15 +136,12 @@ export const decrypt = async (keystore: Keystore, password: string): Promise<str
return decrypted;
};
/**
* encrypt Phrase
*/
export const encryptPhrase = async (
phrase: string,
password: string,
options?: EncryptOptions,
): Promise<string> => {
if (typeof password !== 'string') {
if (!password) {
throw new Error('password is not found');
}
const salt = randomBytes(32);
@ -178,7 +172,7 @@ export const encryptPhrase = async (
return JSON.stringify({
version: 3,
id: uuid.v4({ random: uuidRandom || hexToIntArray(randomBytes(16)) }),
crypto: {
Crypto: {
ciphertext: ciphertext.toString('hex'),
cipherparams: {
iv: iv.toString('hex'),
@ -191,9 +185,6 @@ export const encryptPhrase = async (
});
};
/**
* decrypt phrase
*/
export const decryptPhrase = async (keystore: Keystore, password: string): Promise<string> => {
const result = await decrypt(keystore, password);
return Buffer.from(result.replace('0x', ''), 'hex').toString();

@ -1,19 +1,18 @@
/**
* @packageDocumentation
* @module woop-crypto
*/
/**
* Uses JS-native CSPRNG to generate a specified number of bytes.
* @NOTE
* this method throws if no PRNG is available.
* @function randomBytes
* @description Uses JS-native CSPRNG to generate a specified number of bytes.
* NOTE: this method throws if no PRNG is available.
* @param {Number} bytes bytes number to generate
* @return {String} ramdom hex string
*/
export const randomBytes = (bytes: number): string => {
let randBz: number[] | Uint8Array;
if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) {
if (
typeof window !== 'undefined' &&
window.crypto &&
window.crypto.getRandomValues
) {
randBz = window.crypto.getRandomValues(new Uint8Array(bytes));
} else if (typeof require !== 'undefined') {
randBz = require('crypto').randomBytes(bytes);

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

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

@ -1,9 +1,3 @@
/**
* @packageDocumentation
* @module woop-crypto
* @ignore
*/
export type KDF = 'pbkdf2' | 'scrypt';
export interface PBKDF2Params {
@ -30,7 +24,7 @@ export interface EncryptOptions {
export interface Keystore {
address?: string;
crypto: {
Crypto: {
cipher: string;
cipherparams: {
iv: string;

@ -1,9 +1,4 @@
/**
* @packageDocumentation
* @ignore
*/
import { getAddress, WoopAddress } from '../src/address';
import { getAddress, HarmonyAddress } from '../src/address';
import { randomBytes } from '../src/random';
import { toBech32, fromBech32, HRP, tHRP } from '../src/bech32';
import { toChecksumAddress, isValidChecksumAddress } from '../src/keyTool';
@ -15,7 +10,7 @@ const bech32Testnet = toBech32(checksum, tHRP);
describe('test address', () => {
it('should test HamonyAddress', () => {
const hAddress = new WoopAddress(bytes);
const hAddress = new HarmonyAddress(bytes);
expect(hAddress.basic).toEqual(bytes);
expect(hAddress.basicHex).toEqual(bytesWith0x);
expect(hAddress.checksum).toEqual(checksum);
@ -30,10 +25,10 @@ describe('test address', () => {
expect(fromBech32(bech32, HRP)).toEqual(checksum);
expect(fromBech32(bech32)).toEqual(checksum);
expect(fromBech32(bech32Testnet, tHRP)).toEqual(checksum);
expect(WoopAddress.isValidBasic(bytes)).toEqual(true);
expect(WoopAddress.isValidChecksum(checksum)).toEqual(true);
expect(WoopAddress.isValidBech32(bech32)).toEqual(true);
expect(WoopAddress.isValidBech32TestNet(bech32Testnet)).toEqual(true);
expect(HarmonyAddress.isValidBasic(bytes)).toEqual(true);
expect(HarmonyAddress.isValidChecksum(checksum)).toEqual(true);
expect(HarmonyAddress.isValidBech32(bech32)).toEqual(true);
expect(HarmonyAddress.isValidBech32TestNet(bech32Testnet)).toEqual(true);
expect(isValidChecksumAddress(checksum)).toEqual(true);
try {
// tslint:disable-next-line: no-unused-expression

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

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

@ -1,10 +1,5 @@
/**
* @packageDocumentation
* @ignore
*/
import * as keys from '../src/keyTool';
import { isPrivateKey, isAddress, isPublicKey } from '@woop-js/utils';
import { isPrivateKey, isAddress, isPublicKey } from '@harmony-js/utils';
describe('test keyTools', () => {
it('test keygen', () => {

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

@ -5,5 +5,5 @@
"outDir": "dist"
},
"include": ["src", "../../typings/**/*.d.ts"],
"references": [{"path": "../woop-utils"}]
"references": [{"path": "../harmony-utils"}]
}

@ -1,7 +1,7 @@
{
"name": "@woop-js/network",
"version": "0.1.58",
"description": "network suites for woop",
"name": "@harmony-js/network",
"version": "0.1.31",
"description": "network suites for harmony",
"main": "dist/index.js",
"node": "dist/index.js",
"browser": "dist/index.js",
@ -18,10 +18,10 @@
"author": "neeboo@firestack.one",
"license": "MIT",
"dependencies": {
"@woop-js/utils": "0.1.58",
"@harmony-js/utils": "0.1.28",
"cross-fetch": "^3.0.2",
"mitt": "^1.2.0",
"mitt": "1.2.0",
"websocket": "^1.0.28"
},
"gitHead": "56606e9365721729a490c27d6a294e0daf90fbdf"
"gitHead": "775e2ba36924fcffd8d2c0b73587b549ed90bb81"
}

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

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

Loading…
Cancel
Save