Code Monkey home page Code Monkey logo

hedera-sdk-js's Introduction

Hedera™ Hashgraph JavaScript SDK

Docs NPM Package

The JavaScript SDK for interacting with Hedera Hashgraph: the official distributed consensus platform built using the hashgraph consensus algorithm for fast, fair and secure transactions. Hedera enables and empowers developers to build an entirely new class of decentralized applications.

Install

NOTE: v1 of the SDK is deprecated and support will be discontinued after October 2021. Please install the latest version 2.x or migrate from v1 to the latest 2.x version. You can reference the migration documentation.

# with NPM
$ npm install --save @hashgraph/sdk

# with Yarn
$ yarn add @hashgraph/sdk

# with PNPM
$ pnpm add @hashgraph/sdk

Build

After downloading the repo run task build to build the SDK.

React Native Support

The Hedera JavaScript SDK supports the following:

  • React Native with Expo - keep in mind that the SDK uses some functionalities provided from ethers/ethersproject and there is an issue using parts of ethers.js in this environment. A shims package has to be installed and imported before importing the SDK in your project as it is showed here
  • Useful information: here and here

The Hedera JavaScript SDK does not currently support the following:

  • React Native Bare

Usage

See examples.

Every example can be executed using the following command from the root directory: node examples/[name-of-example].js

Start tests

  • To start the integration tests follow the next steps:
  • To start unit tests follow the next steps:
    • Run task test:unit (Note: the local node should not be running)

Contributing to this Project

We welcome participation from all developers! For instructions on how to contribute to this repo, please review the Contributing Guide.

License Information

Licensed under Apache License, Version 2.0 – see LICENSE in this repo or apache.org/licenses/LICENSE-2.0.

hedera-sdk-js's People

Contributors

andrix10 avatar bguiz avatar chalker avatar cmdhema avatar dependabot[bot] avatar derdis14 avatar dikel avatar easpaas avatar gregscullard avatar imhunterand avatar isavov avatar ivaylonikolov7 avatar janaakhterov avatar justin-m-lacy avatar keira-black avatar keirabee avatar mehcode avatar natanasow avatar nathanklick avatar ochikov avatar petreze avatar pinpong avatar rbarkersl avatar rickylb avatar rokn avatar simihunjan avatar steven-sheehy avatar svetoslav-nikol0v avatar valtyr-naut avatar willparks avatar

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  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  avatar  avatar

hedera-sdk-js's Issues

[Help] Error getting balance - DNS resolution failed

I believe my JS SDK transactions are failing due to MyHbarWallet's proxy being down? If this is the case, can we potentially provide a better error message?

Pablo from Hashing Systems filed a seemingly related issue within the MHW repo here (#280) which actually made me realize this was likely the issue I was encountering.

Additionally, could someone clarify which client proxy config is correct for this release? (discussed in the additional attempts to resolve section)

Details
Running the get-account-info.js example for release v.0.8.0-beta.0 returns the following errors

(node:4974) UnhandledPromiseRejectionWarning: Error: 14 UNAVAILABLE: DNS resolution failed
    at Object.exports.createStatusError (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/grpc/src/common.js:91:15)
    at Object.onReceiveStatus (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/grpc/src/client_interceptors.js:1209:28)
    at InterceptingListener._callNext (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/grpc/src/client_interceptors.js:568:42)
    at InterceptingListener.onReceiveStatus (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/grpc/src/client_interceptors.js:618:8)
    at callback (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/grpc/src/client_interceptors.js:847:24)
(node:4974) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:4974) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Code

require("dotenv").config();

const { Client, AccountBalanceQuery } = require("@hashgraph/sdk");

async function main() {
    const operatorPrivateKey = process.env.OPERATOR_KEY;
    const operatorAccount = process.env.OPERATOR_ID;

    if (operatorPrivateKey == null || operatorAccount == null) {
        throw new Error("environment variables OPERATOR_KEY and OPERATOR_ID must be present");
    }

    const client = new Client({
      network: { "https://grpc-web.myhederawallet.com": "0.0.3" },
      operator: {
            account: operatorAccount,
            privateKey: operatorPrivateKey
        }
    });
    
    const balance = await new AccountBalanceQuery()
        .setAccountId(operatorAccount)
        .execute(client);

    console.log(`${operatorAccount} balance = ${balance.value()}`);
}

main();

Attempt to fix

On the readme for release v.0.8.0-beta.0 it says to proxy to the grpc-web.myhederawallet.com domain, rather than the actual Node IP address that is included in the /examples so I attempted to run this as well...

Updated code

require("dotenv").config();

const { Client, AccountBalanceQuery } = require("@hashgraph/sdk");

async function main() {
    const operatorPrivateKey = process.env.OPERATOR_KEY;
    const operatorAccount = process.env.OPERATOR_ID;

    if (operatorPrivateKey == null || operatorAccount == null) {
        throw new Error("environment variables OPERATOR_KEY and OPERATOR_ID must be present");
    }

    const client = new Client({
      network: { "0.testnet.hedera.com:50211": "0.0.3" },
      operator: {
            account: operatorAccount,
            privateKey: operatorPrivateKey
        }
    });
    
    const balance = await new AccountBalanceQuery()
        .setAccountId(operatorAccount)
        .execute(client);

    console.log(`${operatorAccount} balance = ${balance.value()}`);
}

main();

Which delayed for quite some time before returning the following response.

Updated error

(node:5056) UnhandledPromiseRejectionWarning: Error: 14 UNAVAILABLE: failed to connect to all addresses
    at Object.exports.createStatusError (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/grpc/src/common.js:91:15)
    at Object.onReceiveStatus (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/grpc/src/client_interceptors.js:1209:28)
    at InterceptingListener._callNext (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/grpc/src/client_interceptors.js:568:42)
    at InterceptingListener.onReceiveStatus (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/grpc/src/client_interceptors.js:618:8)
    at callback (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/grpc/src/client_interceptors.js:847:24)
(node:5056) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:5056) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

package.json below, if it's of help

{
  "name": "test1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@hashgraph/sdk": "^0.8.0-beta.0",
    "dotenv": "^8.2.0"
  }
}

Overall the v.0.8.0-beta.0 functionality is looking nice though - excited to test it out 🎊

[help] FileCreateTransaction is asking to setFile before it exists?

I'm attempting to create a file on release v.0.8.0-beta-0 and getting the following error.

(node:2981) UnhandledPromiseRejectionWarning: Error: FileCreateTransaction failed validation:
FileCreateTransaction must have a file set
    at Object.runValidation (/Users/cooperkunz/Desktop/Hedera-JS-Examples/js-sdk/node_modules/@hashgraph/sdk/lib/util.js:100:15)
    at FileCreateTransaction.validate (/Users/cooperkunz/Desktop/Hedera-JS-Examples/js-sdk/node_modules/@hashgraph/sdk/lib/TransactionBuilder.js:45:16)
    at FileCreateTransaction.build (/Users/cooperkunz/Desktop/Hedera-JS-Examples/js-sdk/node_modules/@hashgraph/sdk/lib/TransactionBuilder.js:79:14)
    at main (/Users/cooperkunz/Desktop/Hedera-JS-Examples/js-sdk/file-create.js:25:6)
    at Object.<anonymous> (/Users/cooperkunz/Desktop/Hedera-JS-Examples/js-sdk/file-create.js:30:1)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)

When running a FileCreateTransaction, why would it expect to have a FileID already set?

Details
There are no examples for using the file service within the repository, but I expected the FileCreateTransaction Test would have been a good indicator for desired behavior. I have now attempted to run this test, and it doesn't appear to be working itself.

The code I would like to work is as follows.

require("dotenv").config();

const { Client, FileCreateTransaction } = require("@hashgraph/sdk");

async function main() {
  const operatorPrivateKey = process.env.OPERATOR_KEY;
  const operatorAccount = process.env.OPERATOR_ID;

  if (operatorPrivateKey == null || operatorAccount == null) {
    throw new Error(
      "environment variables OPERATOR_KEY and OPERATOR_ID must be present"
    );
  }

  const client = new Client({
    network: { "0.testnet.hedera.com:50211": "0.0.3" },
    operator: {
      account: operatorAccount,
      privateKey: operatorPrivateKey
    }
  });

  const transaction = new FileCreateTransaction()
    .setContents("testing file create transaction")
    .build(client);

  console.log(await transaction.execute(client));
}

main();

I would hope to run the above with defaults for fees, operator, no admin key, etc. and then the return value of the transaction execution (record/receipt/etc, whatever it is) would give me the File ID. Similarly to the Java SDK example.

Error: invalid private key: <pkey>

When I use string type pkey:

import {Client} from "@hashgraph/sdk";

const client = new Client({ 
    // this key defaults to this url, a public free proxy to the Hedera public testnet
    // generously hosted by MyHederaWallet.com
    url: "https://grpc-web.myhederawallet.com",
    operator: {
        // the account which signs transactions and query payments by default
        account: { shard: 0, realm: 0, account: ___ },
        // the private key used to sign the transactions, either encoded as a string
        // or as an `Ed25519PrivateKey` type 
        privateKey: "..."
    },
});

Error:

Error: invalid private key: <pkey>

How I can convert string type pkey to Ed25519 type ?

/** If `privateKey` is a string it will be parsed as an `Ed25519PrivateKey` */
export type PrivateKey = { privateKey: Ed25519PrivateKey | string };
export type PubKeyAndSigner = {
    publicKey: Ed25519PublicKey;
    signer: Signer;
};

Help with Account Info Query

Curious if this is just an issue on my end? If so, any suggestions on how to resolve? 🤞

Original issue
When running the get-account-info.js example for release v.0.7.2 I get the following errors

node get-account-info.js
(node:1501) UnhandledPromiseRejectionWarning: Error: AccountInfoQuery failed validation:
`.setPayment()` required
    at Object.runValidation (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/@hashgraph/sdk/lib/util.js:100:15)
    at AccountInfoQuery.validate (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/@hashgraph/sdk/lib/QueryBuilder.js:56:16)
    at AccountInfoQuery.<anonymous> (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/@hashgraph/sdk/lib/QueryBuilder.js:106:18)
    at Generator.next (<anonymous>)
    at /Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/@hashgraph/sdk/lib/QueryBuilder.js:8:71
    at new Promise (<anonymous>)
    at __awaiter (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/@hashgraph/sdk/lib/QueryBuilder.js:4:12)
    at AccountInfoQuery.execute (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/@hashgraph/sdk/lib/QueryBuilder.js:97:16)
    at /Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/get-account-info.js:21:108
    at Object.<anonymous> (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/get-account-info.js:22:2)

Attempt to resolve
After receiving that error, I attempted to setPayment(1000000), making the updated script

require("dotenv").config();

const { AccountInfoQuery, Client } = require("@hashgraph/sdk");

const privateKey = process.env.OPERATOR_KEY;

if (!privateKey) {
  throw new Error("missing env var OPERATOR_KEY");
}

const client = new Client({
  operator: {
    account: { shard: 0, realm: 0, account: process.env.OPERATOR_ID },
    privateKey
  }
});

const accountId = { shard: 0, realm: 0, account: 3 };

(async function() {
  console.log(
    "account info:",
    JSON.stringify(
      await new AccountInfoQuery(client)
        .setAccountId(accountId)
        .setPayment(1000000)
        .execute()
    )
  );
})();

Secondary issue
Which then results in the following error

(node:1518) UnhandledPromiseRejectionWarning: TypeError: c.toArray is not a function
    at Function.jspb.Message.setWrapperField (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/google-protobuf/google-protobuf.js:432:335)
    at proto.proto.QueryHeader.setPayment (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/@hashgraph/sdk/lib/generated/QueryHeader_pb.js:181:23)
    at AccountInfoQuery.setPayment (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/@hashgraph/sdk/lib/QueryBuilder.js:52:22)
    at /Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/get-account-info.js:21:108
    at Object.<anonymous> (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/get-account-info.js:22:2)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3

package.json below, if it's of help

{
  "name": "test1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@hashgraph/sdk": "^0.7.2",
    "dotenv": "^8.2.0"
  }
}

Error: Hedera returned response code: KEY_PREFIX_MISMATCH (68)

I am getting Error: Hedera returned response code: KEY_PREFIX_MISMATCH (68) when trying to run FileContentsQuery from the same account using which file is created

const fileIdLike = {
shard: 0, realm: 0, file: fileId
}
let fileQueryResp = await new FileContentsQuery(client).setFileId(fileIdLike).execute()

In BaseClient, too much of the operator internals is public

    public operator?: Operator;
    public operatorSigner?: Signer;
    public operatorPublicKey?: Ed25519PublicKey;

Not sure why we store / have all of that and why its all public. Look at the Java SDK Client. I think a step is not storing operator.

handlePrecheck seems to fail regarding payer balance on FileCreateTransaction

Have balance of 5k hBar while the cost of the transaction is estimated to be ~2.5 hbar.

Was attempting multiple transactions to total to a cost of ~25 hbar, but it seemed to fail on the first one.

Error: "Hedera returned response code: INSUFFICIENT_PAYER_BALANCE (10)"
    node_modules hashgraph/sdk/lib/errors.js:19
    node_modules hashgraph/sdk/lib/errors.js:39
    node_modules hashgraph/sdk/lib/util.js:86
    node_modules hashgraph/sdk/lib/Transaction.js:96
    node_modules hashgraph/sdk/lib/Transaction.js:5

Broken CryptoTransferExample

Issue

After running the updated crypto transfer example I'm getting the following error

(node:1854) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'maxTransactionFee' of undefined
    at new TransactionBuilder (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/@hashgraph/sdk/lib/TransactionBuilder.js:19:78)
    at new CryptoTransferTransaction (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/node_modules/@hashgraph/sdk/lib/account/CryptoTransferTransaction.js:11:9)
    at main (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/new-example.js:23:14)
    at Object.<anonymous> (/Users/cooperkunz/Desktop/hide/Hedera-JS-Examples/test1/new-example.js:32:1)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
(node:1854) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:1854) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Code to reproduce

require("dotenv").config();

const { Client, CryptoTransferTransaction } = require("@hashgraph/sdk");

async function main() {
  const operatorPrivateKey = process.env.OPERATOR_KEY;
  const operatorAccount = process.env.OPERATOR_ID;

  if (operatorPrivateKey == null || operatorAccount == null) {
    throw new Error(
      "environment variables OPERATOR_KEY and OPERATOR_ID must be present"
    );
  }

  const client = new Client({
    nodes: { "0.testnet.hedera.com:50211": "0.0.3" },
    operator: {
      account: operatorAccount,
      privateKey: operatorPrivateKey
    }
  });

  const tx = new CryptoTransferTransaction()
    .addSender(operatorAccount, 10)
    .addRecipient("0.0.3", 10)
    .setMemo("[sdk example] transfer to 0.0.3")
    .build(client);

  await tx.execute(client);
}

main();

Suggested solution

Add a default value for maxTransactionFee so that leaving undefined doesn't result in errors.

We should have a tighter release process to ensure that the examples always work.

Error: Cannot find module '@improbable-eng/grpc-web-node-http-transport/lib'

I'm trying to check the balance:

const { Client } = require("@hashgraph/sdk");

const privateKey = "<pkey>";

const client = new Client({
    operator: {
        account: {shard: 0, realm: 0, account: <acocountId>},
        privateKey
    }
});

(async function () {
    console.log('account balance:', (await client.getAccountBalance()).toString());
})();

Error:

internal/modules/cjs/loader.js:613
    throw err;
    ^

Error: Cannot find module '@improbable-eng/grpc-web-node-http-transport/lib'
Require stack:
- /Users/ilya/Documents/GitHub/hederaTestJs/node_modules/@hashgraph/sdk/index-node.js
- /Users/ilya/Documents/GitHub/hederaTestJs/src/index.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:610:15)
    at Function.Module._load (internal/modules/cjs/loader.js:526:27)
    at Module.require (internal/modules/cjs/loader.js:666:19)
    at require (internal/modules/cjs/helpers.js:16:16)
    at Object.<anonymous> (/Users/ilya/Documents/GitHub/hederaTestJs/node_modules/@hashgraph/sdk/index-node.js:8:15)
    at Module._compile (internal/modules/cjs/loader.js:759:30)

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:770:10)
    at Module.load (internal/modules/cjs/loader.js:628:32)
    at Function.Module._load (internal/modules/cjs/loader.js:555:12)
    at Module.require (internal/modules/cjs/loader.js:666:19)

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.