From 74bfcf9dc256fa8f6fc938edb4a07bd5b8f0456d Mon Sep 17 00:00:00 2001 From: neeboo Date: Tue, 21 May 2019 13:50:14 +0800 Subject: [PATCH] [fix] remove examples and move to another repo (added later) --- examples/contracts/Calc.sol | 19 -- examples/contracts/MyContract.sol | 8 - examples/contracts/SimpleStorage.sol | 23 -- examples/temp.html | 76 ----- examples/testContract.js | 225 ------------- examples/testGanache.js | 311 ------------------ examples/testNode.js | 136 -------- examples/testWallet.js | 32 -- package.json | 8 +- packages/harmony-core/src/blockchain.ts | 29 +- .../src/subscriptions/LogSub.ts | 20 ++ .../src/subscriptions/NewHeadersSub.ts | 8 + .../NewPendingTransactionsSub.ts | 11 + .../src/subscriptions/Subscription.ts | 6 +- .../src/subscriptions/SyncingSub.ts | 31 ++ .../harmony-transaction/src/transaction.ts | 2 +- packages/harmony-transaction/src/types.ts | 2 +- 17 files changed, 96 insertions(+), 851 deletions(-) delete mode 100644 examples/contracts/Calc.sol delete mode 100644 examples/contracts/MyContract.sol delete mode 100644 examples/contracts/SimpleStorage.sol delete mode 100644 examples/temp.html delete mode 100644 examples/testContract.js delete mode 100644 examples/testGanache.js delete mode 100644 examples/testNode.js delete mode 100644 examples/testWallet.js create mode 100644 packages/harmony-network/src/subscriptions/LogSub.ts create mode 100644 packages/harmony-network/src/subscriptions/NewHeadersSub.ts create mode 100644 packages/harmony-network/src/subscriptions/NewPendingTransactionsSub.ts create mode 100644 packages/harmony-network/src/subscriptions/SyncingSub.ts diff --git a/examples/contracts/Calc.sol b/examples/contracts/Calc.sol deleted file mode 100644 index 05fd01a..0000000 --- a/examples/contracts/Calc.sol +++ /dev/null @@ -1,19 +0,0 @@ -pragma solidity ^0.5.1; - -contract Calc { - - uint count; - - function getCount() public returns (uint) { - - return count; - - } - - function add(uint a, uint b) public returns (uint) { - count++; - return a + b; - } - - -} \ No newline at end of file diff --git a/examples/contracts/MyContract.sol b/examples/contracts/MyContract.sol deleted file mode 100644 index 401e058..0000000 --- a/examples/contracts/MyContract.sol +++ /dev/null @@ -1,8 +0,0 @@ -pragma solidity ^0.5.1; - - -contract MyContract { - function myFunction() public returns(uint256 myNumber, string memory myString) { - return (23456, "Hello!%"); - } -} \ No newline at end of file diff --git a/examples/contracts/SimpleStorage.sol b/examples/contracts/SimpleStorage.sol deleted file mode 100644 index 564211b..0000000 --- a/examples/contracts/SimpleStorage.sol +++ /dev/null @@ -1,23 +0,0 @@ -pragma solidity ^0.5.1; - -contract SimpleStorage { - - event ValueChanged(address indexed author, string oldValue, string newValue); - - string _value; - - constructor(string memory value) public { - emit ValueChanged(msg.sender, _value, value); - _value = value; - } - - function getValue() view public returns (string memory) { - return _value; - } - - function setValue(string memory value) public { - emit ValueChanged(msg.sender, _value, value); - _value = value; - } - -} \ No newline at end of file diff --git a/examples/temp.html b/examples/temp.html deleted file mode 100644 index 4a9ce5d..0000000 --- a/examples/temp.html +++ /dev/null @@ -1,76 +0,0 @@ - - - - - - - - - - - - - - -
- -
- - - - - diff --git a/examples/testContract.js b/examples/testContract.js deleted file mode 100644 index 693b6dd..0000000 --- a/examples/testContract.js +++ /dev/null @@ -1,225 +0,0 @@ -// This example shows how you extract a contract's ABI -// And how to use `Contract.deploy().send()` to deploy the contract -// Then we can use `Contract.methods.call()` to call a method - -// Import Main Class -const { Harmony } = require('../packages/harmony-core/dist'); -// You can import BN from `@harmony-js/crypto` or use `Harmony.utils.BN`instead -const { BN } = require('../packages/harmony-crypto/dist'); -const { - SubscribeBlockTracker, - RPCMethod, -} = require('../packages/harmony-network/dist'); -// import more utils -const { - isArray, - ChainType, - ChainID, -} = require('../packages/harmony-utils/dist'); -// contract specific utils -const { - toUtf8String, - toUtf8Bytes, -} = require('../packages/harmony-contract/dist'); - -// we import `fs` and `solc` to complile the contract. you can do it in another js file -// but we show it here anyway. -const fs = require('fs'); -const solc = require('solc'); - -// consturct the input function, here the solidity file lives in `./contracts/` -// we just type the file name as inpnut -function constructInput(file) { - const content = fs.readFileSync(`./contracts/${file}`, { encoding: 'utf8' }); - const input = { - language: 'Solidity', - sources: {}, - settings: { - outputSelection: { - '*': { - '*': ['*'], - }, - }, - }, - }; - - input.sources[file] = { content }; - return JSON.stringify(input); -} - -// we try to comple this solidty file -const fileName = 'MyContract.sol'; - -// now we get the output -const output = JSON.parse(solc.compile(constructInput(fileName))); - -let abi; -let bin; - -// `output` here contains the JSON output as specified in the documentation -for (var contractName in output.contracts[fileName]) { - let contractAbi = output.contracts[fileName][contractName].abi; - let contractBin = - output.contracts[fileName][contractName].evm.bytecode.object; - if (contractAbi) { - abi = contractAbi; - } - if (contractBin) { - bin = contractBin; - } -} - -// To test with different settings, here is some config. - -const Settings = { - Ropsten: { - http: 'https://ropsten.infura.io/v3/4f3be7f5bbe644b7a8d95c151c8f52ec', - ws: 'wss://ropsten.infura.io/ws/v3/4f3be7f5bbe644b7a8d95c151c8f52ec', - type: ChainType.Ethereum, - id: ChainID.Ropsten, - }, - Rinkeby: { - http: 'https://rinkeby.infura.io/v3/4f3be7f5bbe644b7a8d95c151c8f52ec', - ws: 'wss://rinkeby.infura.io/ws/v3/4f3be7f5bbe644b7a8d95c151c8f52ec', - type: ChainType.Ethereum, - id: ChainID.Ropsten, - }, - Ganache: { - http: 'http://localhost:18545', - ws: 'ws://localhost:18545', - type: ChainType.Ethereum, - id: ChainID.Ganache, - }, -}; - -// a function that will map the setting to harmony class constructor inputs -function useSetting(setting, providerType) { - return [setting[providerType], setting.type, setting.id]; -} - -// simply change `Ropsten` to `Rinkeby` to test with different testnet -// and switch `ws` or `http` as RPC provider - -const harmony = new Harmony(...useSetting(Settings.Ropsten, 'ws')); - -// import our preset mnes -const mne = - 'food response winner warfare indicate visual hundred toilet jealous okay relief tornado'; - -// now we have the mnes added to wallet -const acc1 = harmony.wallet.addByMnemonic(mne, 0); - -// now we create contract using extracted abi -const myContract = harmony.contracts.createContract(abi); - -// harmony.messenger.send(RPCMethod.BlockNumber, []).then(console.log); - -// harmony.messenger.subscribe(RPCMethod.Subscribe, ['newHeads']).then((res) => { -// res.onData((data) => { -// console.log(data); -// }); -// }); - -// first we get the account's balance to see if we have enough token on the testnet -acc1.getBalance().then((res) => { - console.log(`-- hint: account balance of ${acc1.address}`); - console.log(``); - console.log({ account: res }); - console.log(``); - console.log(``); -}); - -// a deploy contract function -const deployContract = async () => { - //`Contract.deploy().send()` - const deployed = await myContract - .deploy({ - // the data key puts in the bin file with `0x` prefix - data: `0x${bin}`, - // we don't have any initial arguments to put in of this contract, so we leave blank - arguments: [], - }) - .send({ - // gasLimit defines the max value that blockchain will consume - // here we show that you can use Unit as calculator - // because we use BN as our save integer as default input - // use Unit converter is much safer - gasLimit: new harmony.utils.Unit('1000000').asWei().toWei(), - // gasPrice defines how many weis should be consumed each gas - // you can use `new BN(string)` directly, - // if you are sure about the amount is calculated in `wei` - gasPrice: new harmony.crypto.BN('10000'), - }) - // we use event emitter to listen the result when event happen - // here comes in the `transactionHash` - .on('transactionHash', (transactionHash) => { - console.log(`-- hint: we got Transaction Hash`); - console.log(``); - console.log(`${transactionHash}`); - console.log(``); - console.log(``); - - harmony.blockchain - .getTransactionByHash({ - txnHash: transactionHash, - }) - .then((res) => { - console.log(`-- hint: we got transaction detail`); - console.log(``); - console.log(res); - console.log(``); - console.log(``); - }); - }) - // when we get receipt, it will emmit - .on('receipt', (receipt) => { - console.log(`-- hint: we got transaction receipt`); - console.log(``); - console.log(receipt); - console.log(``); - console.log(``); - }) - // the http and websocket provider will be poll result and try get confirmation from time to time. - // when `confirmation` comes in, it will be emitted - .on('confirmation', (confirmation) => { - console.log(`-- hint: the transaction is`); - console.log(``); - console.log(confirmation); - console.log(``); - console.log(``); - }) - // if something wrong happens, the error will be emitted - .on('error', (error) => { - console.log(`-- hint: something wrong happens`); - console.log(``); - console.log(error); - console.log(``); - console.log(``); - }); - return deployed; -}; - -// now we call our deploy contract function -deployContract().then((deployed) => { - // after the contract is deployed ,we can get contract information - // first we can get the contract Code - harmony.blockchain.getCode({ address: deployed.address }).then((res) => { - if (res.result) { - console.log(`--hint: contract :${deployed.address}--`); - console.log(``); - console.log(`${res.result}`); - console.log(``); - console.log(``); - deployed.methods - .myFunction() - .call() - .then((result) => { - console.log(`--hint: we got contract called, this is result`); - console.log(``); - console.log(result); - console.log(``); - console.log(``); - }); - } - }); -}); diff --git a/examples/testGanache.js b/examples/testGanache.js deleted file mode 100644 index 02f8df4..0000000 --- a/examples/testGanache.js +++ /dev/null @@ -1,311 +0,0 @@ -const { Harmony } = require('../packages/harmony-core/dist'); -const { ChainID, ChainType } = require('../packages/harmony-utils/dist'); -const { - SubscribeBlockTracker, - SubscriptionMethod, -} = require('../packages/harmony-network/dist'); - -const ganache = require('ganache-cli'); - -const port = 18545; - -const url = `http://localhost:${port}`; - -const wsUrl = `ws://localhost:${port}`; - -const mne = - 'food response winner warfare indicate visual hundred toilet jealous okay relief tornado'; - -console.log('--- hint: please write these down'); -console.log('-------------------------------------'); -console.log(`${mne}`); -console.log('-------------------------------------'); - -// we use ChainType='hmy' to indicate we are using `harmony node` -// if we set it to 'eth', we use `eth` as our settings. -// here 'eth' is used, which means we use ethereum-node. - -console.log(ChainType); - -const harmony = new Harmony(wsUrl, ChainType.Ethereum, ChainID.Geth); - -const wsHarmony = new Harmony(wsUrl, ChainType.Ethereum, ChainID.Geth); - -async function createAndEncrypt(words, index, password) { - for (let i = 0; i < index; i++) { - const newAcc = harmony.wallet.addByMnemonic(words, i); - await harmony.wallet.encryptAccount(newAcc.address, password); - } -} - -const acc = harmony.wallet.addByMnemonic(mne, 0); - -console.log('--- hint: we use this private key to test with ganache'); -console.log('-------------------------------------'); -console.log(`${acc.privateKey}`); -console.log('-------------------------------------'); - -const server = ganache.server({ - accounts: [{ secretKey: acc.privateKey, balance: '0x21e19e0c9bab2400000' }], - default_balance_ether: 10000, - gasLimit: '0x3000000', - allowUnlimitedContractSize: true, -}); - -// now it is async time - -async function main() { - const password = '1234567890123'; - - await createAndEncrypt(mne, 10, password); - - // harmony.blockchain.newPendingTransacitons(); - - const latestBalance = await harmony.blockchain.getBalance({ - address: acc.address, - blockNumber: 'latest', - }); - console.log('--- testing: hmy_getBalance'); - console.log('-------------------------------------'); - console.log({ balance: harmony.utils.hexToNumber(latestBalance.result) }); - console.log('-------------------------------------'); - - const nonce = await harmony.blockchain.getTransactionCount({ - address: harmony.wallet.signer.address, - blockNumber: 'latest', - }); - console.log('--- testing: hmy_getTransactionCount'); - console.log('-------------------------------------'); - console.log({ - nonce: Number.parseInt(harmony.utils.hexToNumber(nonce.result), 10), - }); - console.log('-------------------------------------'); - - const balanceOfAccount = await harmony.wallet.signer.getBalance(); - - console.log('--- testing: Account.getBalance'); - console.log('-------------------------------------'); - console.log(balanceOfAccount); - console.log('-------------------------------------'); - - const sendTo = '0xccaed3f53bd0a55db215cc58182969e59d2242fe'; - - const txn = harmony.transactions.newTx({ - to: sendTo, - value: new harmony.utils.Unit('1234567').asWei().toWei(), - gasLimit: new harmony.utils.Unit('21000').asWei().toWei(), - gasPrice: new harmony.utils.Unit('100000000000').asWei().toWei(), - }); - - // now we sign and send a transaction - - const signed = await harmony.wallet.signTransaction(txn, undefined, password); - - console.log('--- testing: Account.signTransaction'); - console.log('-------------------------------------'); - console.log({ signedTransactionPayload: signed.txPayload }); - console.log('-------------------------------------'); - - const [sentTxn, TranID] = await signed.sendTransaction(); - - console.log('--- testing: Transaction.sendTransaction'); - console.log('-------------------------------------'); - console.log({ TranID }); - console.log('-------------------------------------'); - - const confirmed = await sentTxn.confirm(TranID, 20, 1000); - - console.log('--- testing: Transaction.confirm'); - console.log('-------------------------------------'); - console.log({ - confirmed: confirmed.isConfirmed(), - receipt: confirmed.receipt, - }); - console.log('-------------------------------------'); - - const latestBlock = await harmony.blockchain.getBlockByNumber({ - blockNumber: 'latest', - }); - console.log('--- testing: hmy_getBlockByNumber'); - console.log('-------------------------------------'); - console.log({ latestBlockHash: latestBlock.result.hash }); - console.log('-------------------------------------'); - - const sameLatestBlock = await harmony.blockchain.getBlockByHash({ - blockHash: latestBlock.result.hash, - }); - console.log('--- testing: hmy_getBlockByHash'); - console.log('-------------------------------------'); - console.log({ sameLatestBlockNumber: sameLatestBlock.result.number }); - console.log('-------------------------------------'); - - const blockTransactionCount = await harmony.blockchain.getBlockTransactionCountByHash( - { - blockHash: latestBlock.result.hash, - }, - ); - console.log('--- testing: hmy_getBlockTransactionCountByHash'); - console.log('-------------------------------------'); - console.log(blockTransactionCount.result); - console.log('-------------------------------------'); - - const sameBlockTransactionCount = await harmony.blockchain.getBlockTransactionCountByNumber( - { - blockNumber: latestBlock.result.number, - }, - ); - console.log('--- testing: hmy_getBlockTransactionCountByNumber'); - console.log('-------------------------------------'); - console.log(sameBlockTransactionCount.result); - console.log('-------------------------------------'); - - const transaction = await harmony.blockchain.getTransactionByBlockHashAndIndex( - { - blockHash: latestBlock.result.hash, - index: '0x0', - }, - ); - console.log('--- testing: hmy_getTransactionByBlockHashAndIndex'); - console.log('-------------------------------------'); - console.log(transaction.result); - console.log('-------------------------------------'); - - const sameTransaction = await harmony.blockchain.getTransactionByBlockNumberAndIndex( - { - blockNumber: latestBlock.result.number, - index: '0x0', - }, - ); - console.log('--- testing: hmy_getTransactionByBlockNumberAndIndex'); - console.log('-------------------------------------'); - console.log({ gas: sameTransaction.result.gas }); - console.log('-------------------------------------'); - - const sameTransaction2 = await harmony.blockchain.getTransactionByHash({ - txnHash: transaction.result.hash, - }); - const { gas, gasPrice, value } = sameTransaction2.result; - const valueBN = harmony.utils.hexToBN(value); - const gasBN = harmony.utils.hexToBN(gas); - const gasPriceBN = harmony.utils.hexToBN(gasPrice); - const actualCost = new harmony.utils.Unit(gasBN.mul(gasPriceBN).add(valueBN)) - .asWei() - .toWei(); - console.log('--- testing: hmy_getTransactionByHash'); - console.log('-------------------------------------'); - console.log({ - actualCost: actualCost.toString(), - gas: harmony.utils.hexToNumber(gas), - gasPrice: gasPriceBN.toString(), - value: valueBN.toString(), - comment: 'actualCost= gas * gasPrice + value', - }); - console.log('-------------------------------------'); - - const getBalanceAgainObject = await harmony.wallet.signer.getBalance(); - console.log('--- testing: get balance again'); - console.log('-------------------------------------'); - console.log(getBalanceAgainObject); - console.log('-------------------------------------'); - - setTimeout(async () => { - const txn2 = harmony.transactions.clone(txn); - const s2 = await harmony.wallet.signTransaction(txn2, undefined, password); - const [sentTxn, TranID] = await s2.sendTransaction(); - await sentTxn.confirm(TranID, 20, 1000); - console.log({ - blockNumbers: sentTxn.blockNumbers, - txStatus: sentTxn.txStatus, - confirmations: sentTxn.confirmations, - confirmationCheck: sentTxn.confirmationCheck, - }); - }, 5000); - - setTimeout(async () => { - const txn3 = harmony.transactions.clone(txn); - const s3 = await harmony.wallet.signTransaction(txn3, undefined, password); - const [sentTxn, TranID] = await s3.sendTransaction(); - await sentTxn.confirm(TranID, 20, 1000); - console.log({ - blockNumbers: sentTxn.blockNumbers, - txStatus: sentTxn.txStatus, - confirmations: sentTxn.confirmations, - confirmationCheck: sentTxn.confirmationCheck, - }); - }, 10000); - setTimeout(async () => { - const txns3 = harmony.transactions.clone(txn); - const s3 = await harmony.wallet.signTransaction(txns3, undefined, password); - const [sentTxn, TranID] = await s3.sendTransaction(); - await sentTxn.confirm(TranID, 20, 1000); - console.log({ - blockNumbers: sentTxn.blockNumbers, - txStatus: sentTxn.txStatus, - confirmations: sentTxn.confirmations, - confirmationCheck: sentTxn.confirmationCheck, - }); - }, 15000); - setTimeout(async () => { - const txn4 = harmony.transactions.clone(txn); - const s4 = await harmony.wallet.signTransaction(txn4, undefined, password); - const [sentTxn, TranID] = await s4.sendTransaction(); - await sentTxn.confirm(TranID, 20, 1000); - console.log({ - blockNumbers: sentTxn.blockNumbers, - txStatus: sentTxn.txStatus, - confirmations: sentTxn.confirmations, - confirmationCheck: sentTxn.confirmationCheck, - }); - }, 20000); - setTimeout(async () => { - const txn5 = harmony.transactions.clone(txn); - const s5 = await harmony.wallet.signTransaction(txn5, undefined, password); - const [sentTxn, TranID] = await s5.sendTransaction(); - await sentTxn.confirm(TranID, 20, 1000); - console.log({ - blockNumbers: sentTxn.blockNumbers, - txStatus: sentTxn.txStatus, - confirmations: sentTxn.confirmations, - confirmationCheck: sentTxn.confirmationCheck, - }); - }, 25000); - setTimeout(async () => { - const txn6 = harmony.transactions.clone(txn); - const s6 = await harmony.wallet.signTransaction(txn6, undefined, password); - const [sentTxn, TranID] = await s6.sendTransaction(); - await sentTxn.confirm(TranID, 20, 1000); - console.log({ - blockNumbers: sentTxn.blockNumbers, - txStatus: sentTxn.txStatus, - confirmations: sentTxn.confirmations, - confirmationCheck: sentTxn.confirmationCheck, - }); - }, 30000); -} - -server.listen(port, function(err, blockchain) { - // harmony.blockchain.newPendingTransactions().then((p) => { - // p.onData(async (res) => { - // const txn = await harmony.blockchain.getTransactionByHash({ - // txnHash: res.params.result, - // }); - // console.log({ res, txn }); - // }); - // }); - // const newPending = new SubscriptionMethod( - // ['newPendingTransactions'], - // harmony.messenger, - // ); - // newPending.onData(async (res) => { - // const txn = await harmony.blockchain.getTransactionByHash({ - // txnHash: res.params.result, - // }); - // console.log({ res, txn }); - // }); - // const newHeads = new SubscriptionMethod(['newHeads'], harmony.messenger); - // newHeads.onData((res) => { - // console.log(res.params.result.number); - // }); - - main(); -}); diff --git a/examples/testNode.js b/examples/testNode.js deleted file mode 100644 index 0a1aa47..0000000 --- a/examples/testNode.js +++ /dev/null @@ -1,136 +0,0 @@ -const { Harmony } = require('../packages/harmony-core/dist'); -// const ganache = require('ganache-cli'); - -var port = 9015; - -const url = `http://localhost:${port}`; -// const url = `https://testnet-rpc.thundercore.com:8544`; - -// we use ChainType=0 to indicate we are using `harmony node` -// if we set it to 1, we use `eth` as our settings. -// here 0 is by default, which means we use harmony-node by default. -const harmony = new Harmony(url); - -const mne = - 'food response winner warfare indicate visual hundred toilet jealous okay relief tornado'; - -const acc = harmony.wallet.addByMnemonic(mne, 0); - -console.log('--- hint: please write these down'); -console.log('-------------------------------------'); -console.log(`${mne}`); -console.log('-------------------------------------'); - -console.log('--- hint: we use this private key to as default account to test'); -console.log('-------------------------------------'); -console.log(`${acc.privateKey}`); -console.log('-------------------------------------'); - -// now it is async time - -async function main() { - const latestBlock = await harmony.blockchain.getBlockByNumber({ - blockNumber: 'latest', - }); - console.log('--- testing: hmy_getBlockNumber'); - console.log('-------------------------------------'); - console.log(latestBlock.result); - console.log('-------------------------------------'); - - const sameLatestBlock = await harmony.blockchain.getBlockByHash({ - blockHash: latestBlock.result.hash, - }); - console.log('--- testing: hmy_getBlockByHash'); - console.log('-------------------------------------'); - console.log(sameLatestBlock.result); - console.log('-------------------------------------'); - - const blockTransactionCount = await harmony.blockchain.getBlockTransactionCountByHash( - { - blockHash: latestBlock.result.hash, - }, - ); - console.log('--- testing: hmy_getBlockTransactionCountByHash'); - console.log('-------------------------------------'); - console.log(blockTransactionCount.result); - console.log('-------------------------------------'); - - const sameBlockTransactionCount = await harmony.blockchain.getBlockTransactionCountByNumber( - { - blockNumber: latestBlock.result.number, - }, - ); - console.log('--- testing: hmy_getBlockTransactionCountByNumber'); - console.log('-------------------------------------'); - console.log(sameBlockTransactionCount.result); - console.log('-------------------------------------'); - - const transaction = await harmony.blockchain.getTransactionByBlockHashAndIndex( - { - blockHash: latestBlock.result.hash, - index: '0x0', - }, - ); - console.log('--- testing: hmy_getTransactionByBlockHashAndIndex'); - console.log('-------------------------------------'); - console.log(transaction.result); - console.log('-------------------------------------'); - - const sameTransaction = await harmony.blockchain.getTransactionByBlockNumberAndIndex( - { - blockNumber: latestBlock.result.number, - index: '0x0', - }, - ); - console.log('--- testing: hmy_getTransactionByBlockNumberAndIndex'); - console.log('-------------------------------------'); - console.log(sameTransaction.result); - console.log('-------------------------------------'); - - const sameTransaction2 = await harmony.blockchain.getTransactionByHash({ - txnHash: transaction.result.hash, - }); - console.log('--- testing: hmy_getTransactionByHash'); - console.log('-------------------------------------'); - console.log(sameTransaction2.result); - console.log('-------------------------------------'); - - const latestBalance = await harmony.blockchain.getBalance({ - address: acc.address, - blockNumber: latestBlock.result.number, - }); - console.log('--- testing: hmy_getBalance'); - console.log('-------------------------------------'); - console.log({ balance: harmony.utils.hexToNumber(latestBalance.result) }); - console.log('-------------------------------------'); - - const latestBalance2 = await harmony.blockchain.getBalance({ - address: acc.address, - blockNumber: 'latest', - }); - console.log( - '--- testing: force blockNumber to "latest", should get same result as above', - ); - console.log('-------------------------------------'); - console.log({ balance: harmony.utils.hexToNumber(latestBalance2.result) }); - console.log('-------------------------------------'); - - const nonce = await harmony.blockchain.getTransactionCount({ - address: acc.address, - blockNumber: latestBlock.result.number, - }); - console.log('--- testing: hmy_getTransactionCount'); - console.log('-------------------------------------'); - console.log({ - nonce: Number.parseInt(harmony.utils.hexToNumber(nonce.result), 10), - }); - console.log('-------------------------------------'); - - const balanceOfAccount = await acc.getBalance(); - console.log('--- testing: Account.getBalance'); - console.log('-------------------------------------'); - console.log(balanceOfAccount); - console.log('-------------------------------------'); -} - -main(); diff --git a/examples/testWallet.js b/examples/testWallet.js deleted file mode 100644 index 9e43b35..0000000 --- a/examples/testWallet.js +++ /dev/null @@ -1,32 +0,0 @@ -const { Harmony } = require('../packages/harmony-core/dist'); - -const harmony = new Harmony('https://localhost:9015'); - -async function createAndEncrypt(words, index, password) { - for (let i = 0; i < index; i++) { - const newAcc = harmony.wallet.addByMnemonic(words, i); - await harmony.wallet.encryptAccount(newAcc.address, password); - } -} - -async function main() { - // const mne = harmony.wallet.generateMnemonic(); - const mne = - 'food response winner warfare indicate visual hundred toilet jealous okay relief tornado'; - const password = '1234567890123'; - console.log('---hint: please write these down'); - console.log(`${mne}`); - - console.log('---hint: we use simple password to encrypt your wallet'); - console.log(`${password}`); - - await createAndEncrypt(mne, 10, password); - console.log('---hint:we added 10 accounts for you'); - - console.log(harmony.wallet.accounts); - - console.log('---hint:now the signer has been encrypted'); - console.log(harmony.wallet.signer.privateKey); -} - -main(); diff --git a/package.json b/package.json index f078355..4a992b8 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,7 @@ "release": "yarn bootstrap && yarn bundle && lerna publish --exact", "format": "prettier --write '**/*.{ts,tsx,js}' --config .prettierrc", "formatSol": "prettier --list-different **/*.sol", - "dev:publish":"lerna publish --dist-tag next --exact --no-verify-access --no-verify-registry" + "dev:publish": "lerna publish --dist-tag next --exact --no-verify-access --no-verify-registry" }, "devDependencies": { "@babel/cli": "^7.0.0-beta.56", @@ -75,7 +75,6 @@ "dotenv": "^6.0.0", "fancy-log": "^1.3.2", "fbjs-scripts": "^0.8.3", - "ganache-cli": "^6.4.3", "glob": "^7.1.3", "glob-parent": "^3.1.0", "gulp": "^4.0.0", @@ -84,7 +83,7 @@ "jest-fetch-mock": "^1.6.6", "jest-json-schema": "^2.0.1", "jest-watch-typeahead": "^0.2.0", - "lerna": "^3.4.0", + "lerna": "^3.2.1", "mitt": "^1.1.3", "mkdirp": "^0.5.1", "prettier": "^1.14.3", @@ -102,7 +101,6 @@ "rollup-plugin-node-globals": "^1.4.0", "rollup-plugin-node-resolve": "^3.4.0", "rollup-plugin-typescript2": "^0.17.1", - "solc": "^0.5.8", "ts-jest": "^23.1.3", "ts-node": "^7.0.1", "tslint": "^5.11.0", @@ -115,5 +113,5 @@ "webpack-node-externals": "^1.7.2", "websocket": "^1.0.28" }, - "dependencies": {} + "name": "harmony-sdk-core" } diff --git a/packages/harmony-core/src/blockchain.ts b/packages/harmony-core/src/blockchain.ts index f8b2404..7c93a85 100644 --- a/packages/harmony-core/src/blockchain.ts +++ b/packages/harmony-core/src/blockchain.ts @@ -3,7 +3,8 @@ import { Messenger, ResponseMiddleware, WSProvider, - SubscribeReturns, + // SubscribeReturns, + SubscriptionMethod, } from '@harmony-js/network'; import { @@ -321,12 +322,13 @@ class Blockchain extends HarmonyCore { newPendingTransactions() { if (this.messenger.provider instanceof WSProvider) { - return this.messenger.subscribe( - RPCMethod.Subscribe, - ['newPendingTransactions'], - SubscribeReturns.method, - this.chainPrefix, - ); + // return this.messenger.subscribe( + // RPCMethod.Subscribe, + // ['newPendingTransactions'], + // SubscribeReturns.method, + // this.chainPrefix, + // ); + return new SubscriptionMethod(['newPendingTransactions'], this.messenger); } else { throw new Error('HttpProvider does not support this feature'); } @@ -334,12 +336,13 @@ class Blockchain extends HarmonyCore { newBlockHeaders() { if (this.messenger.provider instanceof WSProvider) { - return this.messenger.subscribe( - RPCMethod.Subscribe, - ['newHeads'], - SubscribeReturns.method, - this.chainPrefix, - ); + // return this.messenger.subscribe( + // RPCMethod.Subscribe, + // ['newHeads'], + // SubscribeReturns.method, + // this.chainPrefix, + // ); + return new SubscriptionMethod(['newHeads'], this.messenger); } else { throw new Error('HttpProvider does not support this feature'); } diff --git a/packages/harmony-network/src/subscriptions/LogSub.ts b/packages/harmony-network/src/subscriptions/LogSub.ts new file mode 100644 index 0000000..823982b --- /dev/null +++ b/packages/harmony-network/src/subscriptions/LogSub.ts @@ -0,0 +1,20 @@ +import { Messenger } from '../messenger/messenger'; +import { SubscriptionMethod } from './Subscription'; + +export class LogSub extends SubscriptionMethod { + constructor(params: any[] = ['logs'], messenger: Messenger) { + super(params, messenger); + } + + onNewSubscriptionItem(subscriptionItem: any) { + // todo log formatter + const log = subscriptionItem; + + if (log.removed) { + this.emitter.emit('changed', log); + } + + return log; + } + // todo formatter +} diff --git a/packages/harmony-network/src/subscriptions/NewHeadersSub.ts b/packages/harmony-network/src/subscriptions/NewHeadersSub.ts new file mode 100644 index 0000000..805c156 --- /dev/null +++ b/packages/harmony-network/src/subscriptions/NewHeadersSub.ts @@ -0,0 +1,8 @@ +import { Messenger } from '../messenger/messenger'; +import { SubscriptionMethod } from './Subscription'; + +export class NewHeaders extends SubscriptionMethod { + constructor(params: any[] = ['newHeads'], messenger: Messenger) { + super(params, messenger); + } +} diff --git a/packages/harmony-network/src/subscriptions/NewPendingTransactionsSub.ts b/packages/harmony-network/src/subscriptions/NewPendingTransactionsSub.ts new file mode 100644 index 0000000..58b2116 --- /dev/null +++ b/packages/harmony-network/src/subscriptions/NewPendingTransactionsSub.ts @@ -0,0 +1,11 @@ +import { Messenger } from '../messenger/messenger'; +import { SubscriptionMethod } from './Subscription'; + +export class NewPendingTransactions extends SubscriptionMethod { + constructor( + params: any[] = ['newPendingTransactions'], + messenger: Messenger, + ) { + super(params, messenger); + } +} diff --git a/packages/harmony-network/src/subscriptions/Subscription.ts b/packages/harmony-network/src/subscriptions/Subscription.ts index 4cf6e5b..2a7036e 100644 --- a/packages/harmony-network/src/subscriptions/Subscription.ts +++ b/packages/harmony-network/src/subscriptions/Subscription.ts @@ -31,7 +31,8 @@ export class SubscriptionMethod extends WSProvider { const id = await super.subscribe(subscribePayload); this.subscriptionId = id; this.on(id, (result: any) => { - this.emitter.emit('data', result); + const output = this.onNewSubscriptionItem(result); + this.emitter.emit('data', output); }); this.once('error', (error) => { this.removeEventListener(id); @@ -50,4 +51,7 @@ export class SubscriptionMethod extends WSProvider { ]); return super.unsubscribe(unsubscribePayload); } + onNewSubscriptionItem(subscriptionItem: any) { + return subscriptionItem; + } } diff --git a/packages/harmony-network/src/subscriptions/SyncingSub.ts b/packages/harmony-network/src/subscriptions/SyncingSub.ts new file mode 100644 index 0000000..bb670d3 --- /dev/null +++ b/packages/harmony-network/src/subscriptions/SyncingSub.ts @@ -0,0 +1,31 @@ +import { Messenger } from '../messenger/messenger'; +import { SubscriptionMethod } from './Subscription'; + +export class Syncing extends SubscriptionMethod { + isSyncing: boolean | null; + constructor(params: any[] = ['syncing'], messenger: Messenger) { + super(params, messenger); + this.isSyncing = null; + } + + onNewSubscriptionItem(subscriptionItem: any) { + const isSyncing = subscriptionItem.result.syncing; + + if (this.isSyncing === null) { + this.isSyncing = isSyncing; + this.emitter.emit('changed', this.isSyncing); + } + + if (this.isSyncing === true && isSyncing === false) { + this.isSyncing = isSyncing; + this.emitter.emit('changed', this.isSyncing); + } + + if (this.isSyncing === false && isSyncing === true) { + this.isSyncing = isSyncing; + this.emitter.emit('changed', this.isSyncing); + } + // todo formatter + return subscriptionItem; + } +} diff --git a/packages/harmony-transaction/src/transaction.ts b/packages/harmony-transaction/src/transaction.ts index 9b6412d..ca519f6 100644 --- a/packages/harmony-transaction/src/transaction.ts +++ b/packages/harmony-transaction/src/transaction.ts @@ -314,7 +314,7 @@ class Transaction { for (let attempt = 0; attempt < maxAttempts; attempt += 1) { try { const newBlock = await this.getBlockNumber(); - + // TODO: this is super ugly, must be a better way doing this const nextBlock = '0x' + new BN(checkBlock.substring(2), 'hex') diff --git a/packages/harmony-transaction/src/types.ts b/packages/harmony-transaction/src/types.ts index 82f7b5b..45bdccc 100644 --- a/packages/harmony-transaction/src/types.ts +++ b/packages/harmony-transaction/src/types.ts @@ -1,4 +1,4 @@ -import { BN, Signature } from '@harmony/crypto'; +import { BN, Signature } from '@harmony-js/crypto'; export interface TxParams { id: string; from: string;