Giter Site home page Giter Site logo

sdk's Introduction

Harmony JavaScript SDK

npm version Build Status

This is the Harmony Javascript SDK which provides an easier way to interact with Harmony blockchain.

Please read the documentation for full API doc.

The SDK includes following packages with package-level documentation and examples inside each package.

  1. @harmony-js/core
  2. @harmony-js/account
  3. @harmony-js/crypto
  4. @harmony-js/network
  5. @harmony-js/utils
  6. @harmony-js/transaction
  7. @harmony-js/contract
  8. @harmony-js/staking

Examples

Installation

This library works on both nodejs and browser. Please use it according to your use case.

Enviorment requirement

  • Nodejs: 10.0+
  • Browser: Latest Chrome and Firefox

Install from npm/yarn

Note: we added a @next tag to npm package, please use the following command to install with npm/yarn

# npm
npm install @harmony-js/core@next 

# yarn
yarn add @harmony-js/core@next

# tslib is required, we'd better install it as well
npm install tslib
yarn add tslib

Building from source files

Install lerna and typescript globally

yarn global add lerna && yarn global add typescript

Bootstrap and build

yarn bootstrap

Bundle

Build umd and esm version javascript for each sub-packages, which can be accessed by import or require

yarn dist

All files are exported in packages/dist folder, use **.esm.js or **.umd.js format

Running Tests

Unit tests

yarn test:src

e2e tests

  1. Remove the 'cross-fetch': 'jest-fetch-mock' line from scripts/jest/jest.e2e.config.js
  2. Run harmony node locally, follow the instructions: https://github.com/harmony-one/harmony
  3. Wait for 1-2 mins, and run this:
yarn build && yarn test:e2e

sdk's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sdk's Issues

Contract event listener stops receiving events

Hi there.

Is it fair to say that the Harmony SDK should handle re-connects by itself when using the websocket API? See code below on how we listen for events on a smart contract. We've noticed at some point events stop coming through. We only deployed this yesterday, and it stopped overnight, so it may possibly be some kind of inactivity timeout?

Any guidance on options we should use to prevent timeouts, if needed, would be appreciated.

Thank you!

const HARMONY_WS = new WSProvider('wss://ws.s0.t.hmny.io');

const {
    ChainID,
    ChainType,
    hexToNumber,
    numberToHex,
    fromWei,
    Units,
    Unit,
} = require('@harmony-js/utils');

const wallet = new Wallet(
    new Messenger(
        HARMONY_WS,
        ChainType.Harmony,
        ChainID.HmyMainnet,
    ),
);
const factory = new ContractFactory(wallet);
const contractAddr = "0xfe1b516A7297eb03229A8B5AfAD80703911E81cB";
const contract = factory.createContract(contractJson, contractAddr);

contract.events
    .Transfer()
    .on('data', async (event) => {
    
  [... rest of code omitted ...]

Transactions to smart contracts fail silently

While developing a dapp, I sent a transaction to a smart contract with insufficient gas. However, I got no indication that the transaction failed.

Now that the hmy_sendRawTransaction RPC returns an error if the transaction is unable to be submitted to the mem-pool, such errors should be 'reportable'.

Quickly inspecting the SDK, I found the following snippet:

protected async sendTransaction(signed: Transaction) {
try {
const result = await signed.sendTransaction();
this.contract.setStatus(ContractStatus.SENT);
return result;
} catch (error) {
throw error;
}
}

Note that we never check if the transaction is rejected, maybe there is a good place to start.

Math Wallet Deliverables and SDK Dependencies

Additional Math Wallet Features

  • 1. When using a mnemonic pass phrase to create a wallet would like to be able to generate multiple accounts
  • 2. When doing a transfer would like to get the transaction hash returned (moving forward this may be a link to explorer)
  • 3. Would like to see transaction history for an account
  • 4. Would be nice if the balance of the account updated automatically after the transfer (currently requires a refresh)

Unable to catch errors some errors from the SDK in transactionBase.js

For some reason I can't seem to gracefully recover from errors thrown in the SDK, despite using the .on("error" handler AND wrapping the send function a try catch block. Any ideas why that's the case? Sample code below:

try {
            let sendoptions = {
                from: from,
                gasLimit: '250000',
                gasPrice: new hmy.utils.Unit(GAS_PRICE_GWEI).asGwei().toWei(),
            };
            await contract.methods
                .transfer(to, new Unit(amount).asOne().toWei())
                .send(sendoptions)
                .on("transactionHash", (_hash) => {
                })
                .on("receipt", (_receipt) => {
                })
                .on("confirmation", (confirmation) => {

                })
                .on("error", (error) => {

                });
        } catch (err) {

        }

And the error that's taking down the process below:

17:33:59: Withdraw: send failure within Harmony, reverting balance for wallet 8271
17:33:59: REJECTED
/path/hidden/node_modules/@harmony-js/transaction/dist/transactionBase.js:202
                        throw new Error("The transaction is still not confirmed after " + maxAttempts + " attempts.");
                              ^

Error: The transaction is still not confirmed after 20 attempts.
    at Transaction.<anonymous> (/path/hidden/node_modules/@harmony-js/transaction/dist/transactionBase.js:202:31)
    at step (/path/hidden/node_modules/tslib/tslib.js:143:27)
    at Object.next (/path/hidden/node_modules/tslib/tslib.js:124:57)
    at fulfilled (/path/hidden/node_modules/tslib/tslib.js:114:62)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

Superfluous pop in getRLPSigned

I see a set of three superfluous raw.pop(); statements which appear to be removing information from the raw (encoded but not signed) staking transaction here.

I believe these statements are callous because they are meant to be removing the pushes which only occur when chainId is not null, that is, when this condition: (this.chainId != null && this.chainId !== 0) is true.

To provide an example, if chainId were null, the pop statements would drop the last three elements of the array, that is, gasLimit, gasPrice and nonce. Is this intentional ?

In simple transactions (non-staking), this is taken care of by checking the array length but I do not see a similar check here.

Returned error: invalid address: 0x0000000000000000000000000000000000000000

Running harmony localnet or node using ganache-cli is broken. Could be due to this change.

This error is similar to truffle deploy error as reported in this post. For the truffle error, temporary work around was passing -- skip-dry-run option or specifying skipDryRun: true in the truffle network config.

Steps to reproduce:

  • run harmony node (localnet or actual node)
  • spin up ganache-cli for that node
    ganache-cli -f http://localhost:9500 --networkId 1666700000
  • try to deploy a contract by wrapping ganache url into web3: let web3 = new Web3(<ganache url>), you will get the error as follows:
Error: Returned error: Returned error: invalid address: 0x0000000000000000000000000000000000000000
    at Object.ErrorResponse (/Users/gupadhyaya/demo/node_modules/web3-core-helpers/lib/errors.js:28:19)
    at /Users/gupadhyaya/demo/node_modules/web3-core-requestmanager/lib/index.js:303:36
    at XMLHttpRequest.request.onreadystatechange (/Users/gupadhyaya/demo/node_modules/web3-providers-http/lib/index.js:98:13)
    at XMLHttpRequestEventTarget.dispatchEvent (/Users/gupadhyaya/demo/node_modules/xhr2-cookies/dist/xml-http-request-event-target.js:34:22)
    at XMLHttpRequest._setReadyState (/Users/gupadhyaya/demo/node_modules/xhr2-cookies/dist/xml-http-request.js:208:14)
    at XMLHttpRequest._onHttpResponseEnd (/Users/gupadhyaya/demo/node_modules/xhr2-cookies/dist/xml-http-request.js:318:14)
    at IncomingMessage.<anonymous> (/Users/gupadhyaya/demo/node_modules/xhr2-cookies/dist/xml-http-request.js:289:61)
    at IncomingMessage.emit (node:events:381:22)
    at endReadableNT (node:internal/streams/readable:1307:12)
    at processTicksAndRejections (node:internal/process/task_queues:81:21) {
  data: {
    stack: 'Error: Returned error: invalid address: 0x0000000000000000000000000000000000000000\n' +
      '    at Object.ErrorResponse (/Users/gupadhyaya/.nvm/versions/node/v10.17.0/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:53:1421880)\n' +
      '    at /Users/gupadhyaya/.nvm/versions/node/v10.17.0/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:53:1420752\n' +
      '    at t.n.onreadystatechange (/Users/gupadhyaya/.nvm/versions/node/v10.17.0/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:89:10247)\n' +
      '    at t.e.dispatchEvent (/Users/gupadhyaya/.nvm/versions/node/v10.17.0/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:17:47987)\n' +
      '    at t._setReadyState (/Users/gupadhyaya/.nvm/versions/node/v10.17.0/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:89:15283)\n' +
      '    at t._onHttpResponseEnd (/Users/gupadhyaya/.nvm/versions/node/v10.17.0/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:89:18380)\n' +
      '    at IncomingMessage.<anonymous> (/Users/gupadhyaya/.nvm/versions/node/v10.17.0/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:89:17635)\n' +
      '    at IncomingMessage.emit (events.js:203:15)\n' +
      '    at endReadableNT (_stream_readable.js:1145:12)\n' +
      '    at process._tickCallback (internal/process/next_tick.js:63:19)',
    name: 'Error'
  }
}

invalid chain id for signer for

I tried to create a transaction following the sdk example:

  const hmy = new Harmony(
    'https://api.fuzz.fi/',
    {
        chainType: ChainType.Harmony,
        chainId: ChainID.Harmony,
    },
  );
  hmy.wallet.addByPrivateKey('');
  const txn = hmy.transactions.newTx({
    to: receiver_address,
    value: new Unit(1).asOne().toWei(),
    gasLimit: '21000',
    shardID: 0,
    toShardID: 0,
    gasPrice: new hmy.utils.Unit('31').asGwei().toWei(),
  });
  const signedTxn = await hmy.wallet.signTransaction(txn);
  const txnHash = await hmy.blockchain.sendTransaction(signedTxn);

but got the following error msg:

{
  jsonrpc: '2.0',
  id: 3,
  error: {
    code: -32000,
    message: 'blockchain chain id:1, given 2: invalid chain id for signer'
  },
  req: {
    payload: {
      jsonrpc: '2.0',
      id: 3,
      method: 'hmy_sendRawTransaction',
      params: [Array]
    },
    url: 'https://api.fuzz.fi/',
    options: {
      method: 'POST',
      timeout: 120000,
      headers: [Object],
      user: null,
      password: null
    }
  },
  responseType: 'raw'
}

Not sure why since only one chainId is provided.

Another Harmony SDK bug `FetchError: invalid json response body at https://api.s0.t.hmny.io/ reason: Unexpected token < in JSON at position 0`

This happens on occasion when calling the transfer method of our HRC20 contract.

The SDK doesn't recover from it.

15|withdraw-handler  | Error: FetchError: invalid json response body at https://api.s0.t.hmny.io/ reason: Unexpected token < in JSON at position 0
15|withdraw-handler  |     at Messenger.<anonymous> (/path/dev/crypto_royale/node_modules/@harmony-js/network/dist/messenger/messenger.js:82:35)
15|withdraw-handler  |     at step (/path/dev/crypto_royale/node_modules/tslib/tslib.js:143:27)
15|withdraw-handler  |     at Object.throw (/path/dev/crypto_royale/node_modules/tslib/tslib.js:124:57)
15|withdraw-handler  |     at rejected (/path/dev/crypto_royale/node_modules/tslib/tslib.js:115:69)
15|withdraw-handler  |     at runMicrotasks (<anonymous>)
15|withdraw-handler  |     at processTicksAndRejections (node:internal/process/task_queues:96:5)```

web3_clientVersion not supported in the TruffleProvider

I've been working on a team project over harmony. For setting up the contract to be upgradeable, we used OpenZeppelin CLI along with @openzeppelin-upgrades library...
It works fine when deployed in Ganache. However, an error is thrown when trying to deploy in the testnet for Harmony blockchain…
Below is the error i get when deploying on stable net using oz create:

oz create
Nothing to compile, all contracts are up to date.
? Pick a contract to instantiate Ball
? Pick a network stable
✓ Added contract Ball
Returned error: The method web3_clientVersion does not exist/is not available

The dependencies are as follows:
Truffle v5.0.38 (core: 5.0.38)
Solidity - 0.5.7 (solc-js)
Node v8.10.0
Web3.js v1.2.1
@openzeppelin-cli and @openzeppelin-upgrades version 2.5.1

I contacted with the Openzeppelin team and they said that:
"It sounds like Harmony SDK doesn’t currently support web3_clientVersion in their TruffleProvider. (https://github.com/harmony-one/sdk/blob/master/packages/harmony-core/src/truffleProvider.ts)

This appears similar to an issue connecting to Loom network: OpenZeppelin/openzeppelin-sdk#405 (comment)"

Please do solve this, without this, we'll have to forbid using truffle altogether for our development and do it manually! Thank you!

Running concurrent HRC20 token transfers, without an error.

Simply, is it possible?

Whenever we attempt to run two token transfers concurrently, using:

   await contract.methods
                .transfer(to, new Unit(amount).asOne().toWei())
                .send({
                    from: from,
                    gasLimit: '250000', //default gaslimit for Hrc20 transaction is 250000
                    gasPrice: new hmy.utils.Unit('10').asGwei().toWei(),
                })

One of them fails with an error, usually: transaction failed:replacement transaction underprice

We could build a queuing system of course, but wondering if it's necessary.

Cheers

Milestones to 1.0 Release

Features

  • Add missing RPC API to Blockchain class
  • Fix broken types as much as possible(typescript)

Documentation:

  • Use TypeDoc to generate all function/feature api.
  • Remake build script
  • Make every intro README.md to each package
  • Write guide for each package
  • An api site can be accessed via gh-page

Tests

  • Increase test coverage to 75% in general
  • More unit test
  • Remake integration test (TestNet)
  • Remake e2e test (Local Testnet)

Create new contract will point to wrong address.

Steps
Create new contract with abi and address as params: hmy.contracts.createContract(abi, contractAddress);
What expected?
New contract instance will send to contractAddress
What happend?
New contract instance will send to options addresss.
Suggestion
Check if constructor with address will using this param don't using in options.address
Code line?

this.address = this.options.address || address;

v0.1.31 - TypeError: Object prototype may only be an Object or null - when calling contract method

Hi,

We at Monetha are adapting our blockchain SDK for verifiable data to Harmony blockchain. I have followed various examples in harmony-one repository and was successful so far. Along the way I have encountered an issue with @harmony-js/core SDK version 0.1.31 (latest at the time of writing), where error occurs when calling a contract. The error does not occur on version 0.1.30 or lower and call succeeds.

Here is the code which reproduces the error (Node 10, Windows):

const crypto = require('@harmony-js/crypto');
const core = require('@harmony-js/core');
const BN = crypto.BN;
const Harmony = core.Harmony;

// This is one of our contracts as an example - but the error occurs with any contract
const CompiledContract = require('../build/contracts/PassportLogicRegistry.json');

const privateKey = '01f903ce0c960ff3a9e68e80ff5ffc344358d80ce1c221c3f9711af07f83a3bd';
const contractAddress = '0x89581592e0881E278D32d287bFDe44B283070494';

const harmony = new Harmony('https://api.s0.b.hmny.io', {
  chainType: 'hmy',
  chainId: 2,
  shardID: 0
});

harmony.wallet.addByPrivateKey(privateKey);

const deployedContract = harmony.contracts.createContract(
  CompiledContract.abi,
  contractAddress
);

const methodConfig = deployedContract.methods['getCurrentPassportLogicVersion'].apply(null)

// The call below throws an error `TypeError: Object prototype may only be an Object or null: undefined` in v 0.1.31
methodConfig.call({
  gasLimit: new BN('210000'),
  gasPrice: new BN('100000000000')
})
  .then(result => console.log(result));

and line methodConfig.call produces this error:

C:\src\examples\harmony-verifiable-data-poc\node_modules\tslib\tslib.js:65
        extendStatics(d, b);
        ^

TypeError: Object prototype may only be an Object or null: undefined
    at setPrototypeOf (<anonymous>)
    at Object.__extends (C:\src\examples\harmony-verifiable-data-poc\node_modules\tslib\tslib.js:65:9)
    at C:\src\examples\harmony-verifiable-data-poc\node_modules\@harmony-js\staking\dist\stakingTransaction.js:25:13
    at Object.<anonymous> (C:\src\examples\harmony-verifiable-data-poc\node_modules\@harmony-js\staking\dist\stakingTransaction.js:179:2)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)

Here is package.json for reference

{
  "name": "harmony-verifiable-data-poc",
  "version": "1.0.0",
  "description": "POC for verifiable data smart contracts on Harmony network",
  "dependencies": {
    "@harmony-js/core": "0.1.31",
    "tslib": "^1.10.0"
  }
}

As I mentioned, the problem only occurs on version 0.1.31, but works on 0.1.30 and lower.

Thank you!

TruffleProvider is not processing web3.eth.getTransaction calls explicitly, causing errors

With TruffleProvider as the provider, if one uses web3.eth.getTransaction(txHash) with a valid txHash, the web3 client would complain the underlying sender address one1xxxxxx... is not a valid Ethereum address. I noticed hmy_getTransactionReceipt is overloaded and handled in a special way in truffleProvider.ts, but not hmy_getTransaction. That may be the underlying reason for the error.

A workaround is to use getTransactionByHash in @harmony-js/core/blockchain.ts, but that requires creating a separate instance for RPC call rather than using web3, which would be undesirable

Remove encoding library bloat in @hamony-js/staking JavaScript SDK

When analyzing a recent build, I noticed that @harmony-js/staking is causing my bundle size to blow up due to the use of "text-encoding", which is now a deprecated library.

image

Reference:

import { TextEncoder } from 'text-encoding';

  1. I searched @harmony-js and it appears this library is only used in the staking sdk: https://github.com/harmony-one/sdk/search?q=%22text-encoding%22
  2. It looks like harmony is only using the UTF-8 encoder, since that's the default if no params are passed.
    https://github.com/harmony-one/sdk/blob/master/packages/harmony-staking/src/stakingTransaction.ts#L324

Given the above, I'd like to propose a leaner / tree-shakeable alternative to the deprecated "text-encoding"

help: generating a bundle using browserify

Description

I'm trying to generate a bundle of the harmony sdk so that I can use in a django app.
I've tried generating one for @harmony-js/core and it fails as it is unable to find scrypt-shim which comes from
@harmony-js/core.
Could I some help in figuring how I'd go about including this package so that i can generate a js bundle that i can use in my app ?

Error: Can't walk dependency graph: Cannot find module 'scrypt-shim' 
from '/Users/adianand/Labs/harmony-bundle/node_modules/@harmony-js/crypto/dist/keystore.js'
required by /Users/adianand/Labs/harmony-bundle/node_modules/@harmony-js/crypto/dist/keystore.js

thelostone-mc/harmony-bundle#1

Difference between one and 0x address when calling transfer and contract methods respectively.

Two functions: one to transfer ONE tokens and the other to transfer HRC-20 (HRC) smart contract tokens.

I feel like developers will have some trouble switching between bech32Address and address formats and fields in our SDK.

Is there any way to abstract away the ambiguity? Feel free to chat with me on discord mattlock.

export const transferONE = ({ amount, address }) => async (dispatch, getState) => {
    const tx = hmy.transactions.newTx({
        to: address,  // <--- address is of one format
        value: new hmy.utils.Unit(amount).asEther().toWei(),
        gasLimit: '210000',
        shardID: 0,
        toShardID: 0,
        gasPrice: new hmy.utils.Unit('10').asGwei().toWei(),
    });
    ...
}

export const transferHRC = ({ amount, address }) => async (dispatch, getState) => {
    const tx = contract.methods.transfer(address, parseInt(amount)).send({
        from: active.address, // <--- address is of 0x format
        gasLimit: '1000000',
        gasPrice: new hmy.utils.Unit('10').asGwei().toWei(),
    })
    ...
}

Event subscription doesn't respect the event topics.

After calling a single function that emits a single event, all event subscriptions are emitting in the SDK.

For example: If I call a function newContract that emits a single event (NewContract) and I've subscribed for NewContract and
Withdraw events, both event handlers are invoked for the newContract call.

        this.contract.events
            .NewContract()
            .on('data', (event) => {
                console.log(event);
            })
            .on('error', console.error);

        this.contract.events
            .Withdraw()
            .on('data', (event) => {
                console.log(event);
            })
            .on('error', console.error);

RangeError: Maximum call stack size exceeded (during getTransactionCount)

Hi

We're encountering another uncaught exception coming from the SDK. This time when we use the blochamin.getTransactionCount() API

Error: RangeError: Maximum call stack size exceeded
    at Messenger.<anonymous>
     (/path/crypto_royale/node_modules/@harmony-js/network/dist/messenger/messenger.js:82:35)
    at step (/path/crypto_royale/node_modules/tslib/tslib.js:143:27)
    at Object.throw (/path/crypto_royale/node_modules/tslib/tslib.js:124:57)
    at rejected (/path/crypto_royale/node_modules/tslib/tslib.js:115:69)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

Here is try-catch block in which the exception occurs:

 try {
            let count = await hmy.blockchain.getTransactionCount({ address: MAIN_ACCOUNT })
            nonce = parseInt(count.result);
            while (nonce in transactionsInProgress) {
                nonce += 1;
            }
            transactionsInProgress[nonce] = true;
  } catch (err) {
            resolve({ success: false, error: `Nonce creation error` });
            return;
  }

Once this happens once, it keeps occuring until we restart the process.

Any thoughts/fixes/workarounds appreciated.

Contract call return of uint8 returns incorrect value

A call to a public variable inside a contract that is of type uint8 returns integer value and not hex bytes value. For example, a call to a token contract's decimal variable will return 12 and not 0x12, which would equal an integer of 18.

Create documentation for the SDK

Overview
We'd like to create documentation for our developers. This will provide similar information as ethereum's web3 documentation

Task Overview

  1. Decide on documentation tooling (e.g. typedoc)
  2. Familiarize yourself with the tools by generating sample documentation.
  3. Decide on hosting mechanism (e.g. AWS or readthedocs or github)
  4. Document document creation process (e.g. documentation.md
  5. Generate the documentation and host it
  6. Refine the documentation so it is clearly structured and understandable
  7. Create a fitgap (comparison) of modules Harmony supports vs ethereum
  8. Create documentation standards for developers (e.g what comments need to be created for each module)
  9. Update the documentation so all modules are clearly documented (this may be done under a followup ticket

Acceptance Criteria
a. Documentation is created and hosted
b. Documentation has been shared and reviewed by internal team members
c. Documentation has been shared and reviewed by external developers (p-dev or developers)
d. Fitgap documentation is created (google shete)
e. Documentation standards are created

cannot deploy contract

In Ethereum, when the 'to' field of a tx is empty, it indicates that the tx is a contract deployment. But the SDK does not allow the 'to' field to be empty.

Help with contract.wallet.addByPrivateKey

so, i deployed an Ownable contract using my ONE wallet account, I then tried to call an onlyOwner function in the contract by using the send api, did contract.wallet.addByPrivateKey('private key of my ONE wallet account') to add the signing account to the wallet. But I am getting the "Ownable: caller is not the owner was thrown". Does anyone know why this might be happening? When I call the owner function from the contract, I am getting the correct wallet address...

addByKeyStore requires password of length > 0

using async addByKeyStore(keyStore: string, password: string): Promise<Account>

It's impossible to pass in a password of length == 0, even though this may be a popular option for test accounts or local environments.

Version:
"@harmony-js/core": "^0.1.32"

Code to reproduce:

const keystore = '...'
const delegator = await harmony.wallet.addByKeyStore(keystore, '')

Temp fix for line 107 of account.js (dist):

if (!password) {
  throw new Error('you must provide password');
}
// guessing... !password evaluates to false for '' if coming from TypeScript?
// below I want to skip this throw...
if (false && !password) {
   throw new Error('you must provide password');
}

Delegate and undelegate wrong amount type

Amount of tokens to delegate and undelegate is typed as number, but expects amount in wei and is too big for number type.
If type ignored and amount is sent as hex string with wei amount it works.

The param "returnObject" is not work in functions: getBlockbyHash and getBlockbyNumber

Position

harmony-core/src/blockchain.ts

Questions

For two functions in blockchain.ts, getBlockByHash and getBlockByNumber,
There are three params: blockNumber/blockHahs, returnObject, shardID

The param returnObject dose nothing.

Functions:

// getBlockByHash 
@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);
  }
//getBlockByNumber
  @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);
  }

Expectation

The typereturnObject is boolean:

  • true: the returned block will contain all transactions as objects
  • false: the returned block only contains the transaction hashes, by default, it's false.

Contract deployed but getting gasLimit error

> Compiled successfully using:
   - solc: 0.5.14+commit.01f1aaa4.Emscripten.clang



Migrations dry-run (simulation)
===============================
> Network name:    'testnet-fork'
> Network id:      2
> Block gas limit: 0x668eb0


1_initial_migration.js
======================

   Deploying 'Migrations'
   ----------------------
   > block number:        337639
   > block timestamp:     1593449502
   > account:             0x3aea49553Ce2E478f1c0c5ACC304a84F5F4d1f98
   > balance:             6799524.880868240959712675
   > gas used:            128242
   > gas price:           2 gwei
   > value sent:          0 ETH
   > total cost:          0.000256484 ETH

   -------------------------------------
   > Total cost:         0.000256484 ETH


2_simple_price_database.js
==========================

   Deploying 'SimplePriceDB'
   -------------------------
   > block number:        337641
   > block timestamp:     1593449520
   > account:             0x3aea49553Ce2E478f1c0c5ACC304a84F5F4d1f98
   > balance:             6799524.879118582959712675
   > gas used:            847903
   > gas price:           2 gwei
   > value sent:          0 ETH
   > total cost:          0.001695806 ETH

   -------------------------------------
   > Total cost:         0.001695806 ETH


Summary
=======
> Total deployments:   2
> Final cost:          0.00195229 ETH





Starting migrations...
======================
> Network name:    'testnet'
> Network id:      2
> Block gas limit: 0x668eb0


1_initial_migration.js
======================

   Deploying 'Migrations'
   ----------------------
   > transaction hash:    0x8360e61b5ee198c4ad921d10f53b4fd0d509621cbbf6b9939277b48b42a40031
   ⠴ Blocks: 3            Seconds: 22TypeError: Cannot read property 'gasLimit' of undefined
TypeError: Cannot read property 'gasLimit' of undefined

I can find the deployed contract at the transaction hash mentioned above but this error doesn't let the deployment of second contract.

Dependencies:
"@harmony-js/core": "^0.1.45",
"dotenv": "^8.2.0",
"openzeppelin-solidity": "2.4.0",
"truffle": "5.1.3",
"tslib": "^2.0.0"
Node Version: v10.16.3

Returned error: replacement transaction underpriced

I got this error while using the openzeppelin cli to deploy contract instances.

 npx oz deploy 
Nothing to compile, all contracts are up to date.
? Choose the kind of deployment upgradeable
? Pick a network lrtn_testnet
? Pick a contract to deploy ContractName
? One or more linked dependencies are not yet deployed on morden.
Do you want to deploy them now? Yes
✖ Deploying @openzeppelin/contracts-ethereum-package dependency to network morden
Failed deployment of dependency @openzeppelin/contracts-ethereum-package with error: Returned error: replacement transaction underpriced

I googled and the issue was mentioned here:
OpenZeppelin/openzeppelin-sdk#55

which was further linked to:
trufflesuite/truffle-hdwallet-provider#65

So, I was wondering if this issue is handled in our version of TruffleProvider

Support for Trust Wallet

Overview
As part of Trust Wallet support for Harmony we need to ensure API Compatibility.
This aligns with Harmony 1340

Background - Reference Material
Communication

  • via Telegram (Trust Wallet/Harmony)

Key Contact

Documents

Key Areas

johns-mbp:docs johnwhitton$ curl http://localhost:9500 -H "Content-Type: application/json" -X POST --data '{"jsonrpc":"2.0","method":"hmy_getBalance","params":["0x3aea49553Ce2E478f1c0c5ACC304a84F5F4d1f98", "latest"],"id":1}'
{"jsonrpc":"2.0","id":1,"result":"0x15af1d3b97541f000"}

Sub Tasks

Acceptance Criteria

  • query account / address balance
  • query sent / received transactions for an account / address
  • query transaction details
  • query fee / nonce for sending transaction
  • query blockchain status (block height)
  • send raw transaction

How to get a specific token off of the harmony blockchain

Sorry for the - maybe obvious - question, but I seem to not be able to find how to address this in the documentation.

Currently I'm able to get the ONE balance off of my wallet using

      const account = new Account(
          privateKey,
          customHTTPMessenger
      );
      account.getBalance().then(response => {
          console.log(fromWei(response.balance, Units.one));
      });

Is it possible to retrieve the balance of a specific token on my wallet?

Harmony RPC support on evm_increaseTime and evm_decreaseTime in test environments

These RPC calls are provided by ganache-cli (https://github.com/trufflesuite/ganache-cli). They are necessary for creating tests for smart contracts that are time-dependent, e.g. spending limit, lock out, last resort, etc.

This may be out of the scope for this SDK, but it would be extremely helpful to have this implemented sooner or later. Ideally there should something similar to ganache-cli, that generates a series of funded accounts in local environment, with ability to fund them at will.

The truffleprovider version needs to be updated

Hi Guys,

I had tried to compile one of the Ethereum smartcontract basically a NFT token standard, but it said the truffle version needs to updated to the latest.

the standard i was testing is ERC721Full

Thanks

HMY edit-validator ask for Absolute Path

Trying to edit my validator on devnet by running the command bellow:

./hmy staking edit-validator --validator-addr one1echapu535qgtc5ktkgjj3raec4x4gp0a2mh9ec --name Yelllowsin --identity Yelllowsin --website [email protected] --security-contact Yellowsin --details "Maha Lakshmi" --rate 0.3 --min-self-delegation 2 --max-total-delegation 11000 --remove-bls-key 0xa8a0637c7e11e2ea82c23ec1c0dcae3963a34bbabd92b03f9d895d04377ac72ae770da75c4c5868490378501cbd3888e --add-bls-key 0xa8a0637c7e11e2ea82c23ec1c0dcae3963a34bbabd92b03f9d895d04377ac72ae770da75c4c5868490378501cbd3888e --chain-id devnet

HMY returns with this error:

For bls public key: 0xa8a0637c7e11e2ea82c23ec1c0dcae3963a34bbabd92b03f9d895d04377ac72ae770da75c4c5868490378501cbd3888e
Enter the absolute path to the encrypted bls private key file:

Error: keypath is not absolute path
v179f4cf946: keypath is not absolute path

I am sure i am passing the correct BLS KEY parameter as this same parameter works for "create-validator" as shown bellow:

./hmy staking create-validator --validator-addr one1echapu535qgtc5ktkgjj3raec4x4gp0a2mh9ec --name Yelllowsin --identity yelllowsin --website [email protected] --security-contact Yelllowsin --details "Maha Lakshmi" --rate 0.3 --max-rate 0.9 --max-change-rate 0.05 --min-self-delegation 2 --max-total-delegation 11000 --amount 1000 --bls-pubkeys 0xa8a0637c7e11e2ea82c23ec1c0dcae3963a34bbabd92b03f9d895d04377ac72ae770da75c4c5868490378501cbd3888e --chain-id devnet

question : prompt for signature on harmony extension

How would I prompt a txn to be signed via the harmony extension on the dapp?
This works perfectly fine when you add a private key but I won't be able to do that in a dapp.

      let hmy = new HarmonyJs.Harmony(
          'https://api.s1.b.hmny.io/',
          {
              chainType: HarmonyUtils.ChainType.Harmony,
              chainId: HarmonyUtils.ChainID.HmyTestnet,
          },
      );

      async function transfer() {
        const txn = hmy.transactions.newTx({
          to: 'one1crzp6qhczwms38uchngp3xk04ak48ghlky0jkc',
          value: new HarmonyUtils.Unit(1).asOne().toWei(),
          gasLimit: '21000',
          shardID: 0,
          toShardID: 0,
          gasPrice: new hmy.utils.Unit('1').asGwei().toWei(),
        });

        // sign add to wallet 
        hmy.wallet.addByPrivateKey('...');


        // sign the transaction use wallet;
        const signedTxn = await hmy.wallet.signTransaction(txn);
        const txnHash = await hmy.blockchain.sendTransaction(signedTxn);
        console.log(txnHash.result);
      }

Can't use the SDK with vite

After installing the crypto package via yarn add @harmony-js/crypto (installed v0.1.56), starting the application produces the following error:

yarn run v1.22.11
$ vite
 > node_modules/vite/dist/node/chunks/dep-98dbe93b.js:39126:14: error: [plugin: vite:dep-scan] Failed to resolve entry for package "@harmony-js/crypto". The package may have incorrect main/module/exports specified in its package.json.
    39126 │         throw new Error(`Failed to resolve entry for package "${id}". ` +
          ╵               ^
    at resolvePackageEntry (/home/ofir/Development/private/test/node_modules/vite/dist/node/chunks/dep-98dbe93b.js:39126:15)
    at tryNodeResolve (/home/ofir/Development/private/test/node_modules/vite/dist/node/chunks/dep-98dbe93b.js:38938:11)
    at Context.resolveId (/home/ofir/Development/private/test/node_modules/vite/dist/node/chunks/dep-98dbe93b.js:38819:28)
    at Object.resolveId (/home/ofir/Development/private/test/node_modules/vite/dist/node/chunks/dep-98dbe93b.js:51254:55)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at async resolve (/home/ofir/Development/private/test/node_modules/vite/dist/node/chunks/dep-98dbe93b.js:51453:26)
    at async /home/ofir/Development/private/test/node_modules/vite/dist/node/chunks/dep-98dbe93b.js:51565:34
    at async callback (/home/ofir/Development/private/test/node_modules/esbuild/lib/main.js:812:28)
    at async handleRequest (/home/ofir/Development/private/test/node_modules/esbuild/lib/main.js:644:30)

   node_modules/vite/dist/node/chunks/dep-98dbe93b.js:51555:18: note: This error came from the "onResolve" callback registered here
    51555 │             build.onResolve({
          ╵                   ~~~~~~~~~
    at setup (/home/ofir/Development/private/test/node_modules/vite/dist/node/chunks/dep-98dbe93b.js:51555:19)
    at handlePlugins (/home/ofir/Development/private/test/node_modules/esbuild/lib/main.js:736:23)
    at Object.buildOrServe (/home/ofir/Development/private/test/node_modules/esbuild/lib/main.js:1024:7)
    at /home/ofir/Development/private/test/node_modules/esbuild/lib/main.js:1754:17
    at new Promise (<anonymous>)
    at Object.build (/home/ofir/Development/private/test/node_modules/esbuild/lib/main.js:1753:14)
    at Object.build (/home/ofir/Development/private/test/node_modules/esbuild/lib/main.js:1629:51)
    at /home/ofir/Development/private/test/node_modules/vite/dist/node/chunks/dep-98dbe93b.js:51412:54
    at Array.map (<anonymous>)

   src/services/tokens.js:2:31: note: The plugin "vite:dep-scan" was triggered by this import
        2 │ import { HarmonyAddress } from '@harmony-js/crypto';
          ╵                                ~~~~~~~~~~~~~~~~~~~~

error when starting dev server:
Error: Build failed with 1 error:
node_modules/vite/dist/node/chunks/dep-98dbe93b.js:39126:14: error: [plugin: vite:dep-scan] Failed to resolve entry for package "@harmony-js/crypto". The package may have incorrect main/module/exports specified in its package.json.
    at failureErrorWithLog (/home/ofir/Development/private/test/node_modules/esbuild/lib/main.js:1449:15)
    at /home/ofir/Development/private/test/node_modules/esbuild/lib/main.js:1131:28
    at runOnEndCallbacks (/home/ofir/Development/private/test/node_modules/esbuild/lib/main.js:921:63)
    at buildResponseToResult (/home/ofir/Development/private/test/node_modules/esbuild/lib/main.js:1129:7)
    at /home/ofir/Development/private/test/node_modules/esbuild/lib/main.js:1236:14
    at /home/ofir/Development/private/test/node_modules/esbuild/lib/main.js:609:9
    at handleIncomingPacket (/home/ofir/Development/private/test/node_modules/esbuild/lib/main.js:706:9)
    at Socket.readFromStdout (/home/ofir/Development/private/test/node_modules/esbuild/lib/main.js:576:7)
    at Socket.emit (events.js:400:28)
    at Socket.emit (domain.js:470:12)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Invalid path on module field

This is related to @harmony-js/crypto lib

For context im using Vite

Inside the package.json of the lib this path is set as the module, but on the dist folder this file doesnt exist

"module": "dist/index.esm.js",

This ends triggering an error
Failed to resolve entry for package "@harmony-js/crypto". The package may have incorrect main/module/exports specified in its package.json: Failed to resolve entry for package "@harmony-js/crypto". The package may have incorrect main/module/exports specified in its package.json.

Am i missing something?

ChainID enum being ambient const enums breaks react typescript production build

$ react-scripts build
The following changes are being made to your tsconfig.json file:
  - compilerOptions.isolatedModules must be true (implementation limitation)

Creating an optimized production build...
Failed to compile.

/Users/dennis.won/go/src/github.com/harmony-one/swoop-interface/src/constants/index.ts
TypeScript error in /Users/dennis.won/go/src/github.com/harmony-one/swoop-interface/src/constants/index.ts(13,3):
Cannot access ambient const enums when the '--isolatedModules' flag is provided.  TS2748

Dependency Problem with @harmony-js/core

On importing TruffleProvider from @harmony-js/core and :

const newAcc = truffleProvider.addByPrivateKey(process.env.TESTNET_PRIVATE_KEY);

generates the following error:

photo_2021-04-27_19-09-32

To reproduce:

  • Use any project using @harmony-js/core
  • Remove node_modules
  • Reinstall node_modules
  • Rerun your project.

Note: The private key in the picture is from Ganache Testing. But the same error is occurring for different networks with original keys.

Empty Header on RPC events

When listening for transaction receipts and confirmations, there is no block number returned from the socketConfirmation data. This causes the JS SDK to throw an error.

const blockNumber =
            this.messenger.chainPrefix === 'hmy'
              ? data.params.result.Header.number
              : data.params.result.number;

The value of data.params.result.Header is {} causing number to be undefined.

This is a new issue based on upgrades to the core protocol recently (since Dec 15, 2019).

Please link to possible related issues

Missing "hmy_getBlocks"

I was playing around with the SDK and realized I wanted to minimize the amount of requests I was making through the getBlockByNumber method. I found there is a method to request a range of blocks in one call, but it is not available through the js SDK.

I recently made a PR which adds in the missing functionality.

Transaction issue failed when I trying to doing a transaction

Transaction failed:insufficient funds for gas * price + value.
I using the library in the back-end to sign the transaction.
When I tried a different gas limit (gas-limit: "2100000" & gas-Price: "10000000000") and has a value of :"0.001", it shows the transaction failed issue.

The transaction is still not confirmed after 20 attempts

For as long as I can remember we occasionally get these errors coming back from the SDK. More so in the last 48 hours. Are these to be expected from the Harmony blockchain, or are they Harmony SDK specific and would disappear if we move to ethers/webjs?

Thank you for your help

3|highstakes  | Error: The transaction is still not confirmed after 20 attempts.
3|highstakes  |     at Transaction.<anonymous> (/path/dev/crypto_royale/node_modules/@harmony-js/transaction/dist/transactionBase.js:202:31)
3|highstakes  |     at step (/path/dev/crypto_royale/node_modules/tslib/tslib.js:143:27)
3|highstakes  |     at Object.next (/path/dev/crypto_royale/node_modules/tslib/tslib.js:124:57)
3|highstakes  |     at fulfilled (/path/dev/crypto_royale/node_modules/tslib/tslib.js:114:62)
3|highstakes  |     at runMicrotasks (<anonymous>)
3|highstakes  |     at processTicksAndRejections (node:internal/process/task_queues:96:5)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.