Giter VIP home page Giter VIP logo

ontology-ts-sdk's Introduction

Ontology TypeScript SDK

Version V1.1.18

Overview

This is the official Ontology TypeScript SDK - a comprehensive library for developing with the Ontology blockchain in both TypeScript and JavaScript. It currently supports management of wallets, digital identities and digital assets - as well as the deployment and invocation of smart contracts.

Getting Started

Installation

Download Through npm/Yarn

npm install 'ontology-ts-sdk' --save

or

yarn add 'ontology-ts-sdk'

Build from Source Code

Downloading

git clone 'https://github.com/ontio/ontology-ts-sdk.git'

Then install the dependencies with:

yarn

Compiling

Compile the project with the:

yarn build:dev // or yarn build:prod

This will create a compiled version of the SDK in the lib directory.

Testing

The tests can be found in the test directory. They are distinguished into three categories stored in separate subfolders:

  • unit: unit tests that can be run without external or network dependencies
  • integration: integration tests that require access to one or more Blockchain nodes and test the actual interaction with the Blockchain
  • example: pure sample code without test assertations that can be used for explorative testing or documentation purposes

To run the tests, use one of:

# unit tests
npm run test:unit
# integration tests
npm run test:integration
# examples
npm run test:example
# all
npm run test

or

yarn run test:unit
# integration tests
yarn run test:integration
# examples
yarn run test:example
# all
yarn test

The integration tests use several accounts on the testnet that require funding of ONG tokens in order to pay for the transactions. If there are any test failures with error messages like "insufficient funds" or similar, make sure the following accounts are properly funded:

  • APT4wZG9sFQfjhyfGALPXQj5UyrQ3ZCVkY
  • ANH5bHrrt111XwNEnuPZj6u95Dd6u7G4D6
  • AXK2KtCfcJnSMyRzSwTuwTKgNrtx5aXfFX
  • AVXf5w8WD2y6jV1Lzi36oSKYNif1C7Surc
  • AdLUBSSHUuFaak9j169hiamXUmPuCTnaRz
  • AJkkLbouowk6teTaxz1F2DYKfJh24PVk3r
  • ATk57i8rMXFSBpHAdX3UQ4TNe48BBrfCoc
  • AU9TioM24rXk5E3tUGrv8jwgBA1aZVVKDW
  • AHTdWzj4jYBzbU48YBCfovvouTMc45M6iP
  • AJym8dF7wZLjtoiY8C3mmYt8f2tZDxq5iz

Use in Project

Import

Using import to include the modules from 'ontology-ts-sdk':

import {Wallet} from 'ontology-ts-sdk';
var wallet = Wallet.create('test');

Require

Using require to include the modules from 'ontology-ts-sdk':

var Ont = require('ontology-ts-sdk');
var wallet = Ont.Wallet.create('test');

In the Browser

To use in the browser you must use the compiled version (as listed above). The browser.js file is located in the lib directory. Include it into the project with a <script> tag:

<script src="./lib/browser.js"></script>

Everything will be available under the Ont variable, just like in the require example above.

var wallet = Ont.Wallet.create('test');

Contributing

Contributors are welcome to the ontology-ts-sdk. Before beginning, please take a look at our contributing guidelines. You can open an issue by clicking here.

If you have any issues getting setup, open an issue or reach out in the Ontology Discord.

License

The Ontology TypeScript SDK is availabl under the LGPL-3.0 License.

ontology-ts-sdk's People

Contributors

backslash47 avatar dependabot[bot] avatar doresimon avatar dyassab avatar erickyangs avatar jerryli617 avatar jpbu avatar liuqiang1357 avatar mickwang avatar mickweb3 avatar nashmiao avatar onto-app avatar ontology-opendoc avatar pomykalskimateusz avatar qiluge avatar roccomuso avatar veryhappyok avatar voodoo12345 avatar xiaobin83 avatar xiaomin49 avatar zeyuyuan avatar zhengq1 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ontology-ts-sdk's Issues

PublicKeys generated from xPrivateKey & xPublicKey are not the same in hdkey-secp256r1

I'm trying to generate address from xpub using this module @ont-community/hdkey-secp256r1 and later want to sign with privateKey generated from xpriv. But during the process, I noticed that the public keys generated from xpub and xpriv are not the same (this is not happen in cryptocoinjs/hdkey).

Here are my code to reproduce the problem:

const HDKey = require('@ont-community/hdkey-secp256r1');

// Please replace with your master private key
const xpriv = 'xprvxxxxx';

const hdkey = HDKey.fromExtendedKey(xpriv);
const newXpub = hdkey.publicExtendedKey;

const pubStr = hdkey.derive('m/0/0/176').publicKey.toString('hex');

const hdkey2 = HDKey.fromExtendedKey(newXpub);
const pubStr2 = hdkey2.derive('m/0/0/176').publicKey.toString('hex');

console.log(pubStr, pubStr2);

NodeJS Runtime Error

When attempting to run this package in NodeJS using NPM, requiring the module throws the following error:

ReferenceError: regeneratorRuntime is not defined

Steps to reproduce:

  • Install via npm or yarn
  • Create a empty JS file (eg. main.js)
  • Require the package module (var Ont = require('ontology-ts-sdk');)
  • Save and run from terminal (eg. node main.js)

Expected result:

  • Script will execute successfully

Actual result:

  • Console throws the error ReferenceError: regeneratorRuntime is not defined

This issue was not present about 6-8 months ago when I tried it last, so not sure what changed. Using node version 10.15.0

The encode of base-x issue

Hi, I found that the SDK using base-x for encoding/decoding, such as

function hexToBase58(hexEncoded: string): string {
const data = ADDR_VERSION + hexEncoded;
const hash = sha256(data);
const hash2 = sha256(hash);
const checksum = hash2.slice(0, 8);
const datas = data + checksum;
return base58.encode(hexstring2ab(datas));
}

However, the function encode(source) of base-x expects to receive the source as Buffer, not bytes array. Further more, in version 3.0.5, it will throw error if the parameter is not Buffer:
cryptocoinjs/base-x@6cbf08a#diff-168726dbe96b3ce427e7fedce31bb0bc

Please update the usage of encode using base-x.
Thank you.

z

z

Should not convert `amount` to number in javascript

Sorry to point this out, but I don't think we should convert amount to number in javascript since according to this stackoverflow: what is JavaScript's highest integer value that a number can go to without losing precision?, the actual amount to be transfered will not precise.

Here's my code to reproduce the problem:

const expectAmount = '90071992547409911';
const from = new Address('Some Address 1');
const to = new Address('Some Address 2');
const tx = makeTransferTx('ONG', from, to, expectAmount, '500', '30000');

const transferAmount = deserializeTransferTx(tx.serialize()).amount;
console.log('Expected Amount', expectAmount);   // Expected Amount 90071992547409911
console.log('Transfer Amount', transferAmount); // Transfer Amount 90071992547409900

Query DDO ask for payment gas

Test network ask for payment to query DDO.
The transaction with tx obtained by buildGetDDOTx function return "Please input gasLimit >= 20000 and gasPrice >= 500" when sent.

Is there any method for fee checking?

There is a method to calculate fees in transaction.ts.
But it is deprecated. Is there any new method or alternative solution to calculate fee dynamically?

deserializeTransferTx error

my code:

    let res
    const txid = "6b5bde081af77d6ba7e7e88d9d8655a6c5dcc68809b17e111f80b0c910a53ebd"

    console.log("----------rpc 查询交易id 解析----------")
    const rpcClient = new RpcClient('http://dappnode1.ont.io:20336');
    res = await rpcClient.getRawTransaction(txid)
    console.log(res)
    let txDetail = OntAssetTxBuilder.deserializeTransferTx(res.result);
    console.log(txDetail)

error happend in :

tx.method = hexstr2str(methodStr);

methodStr : "a147d9d8a8976cc416bb3b95b8af597886749b7cc84c86a14b3e5d59675dc1514c989893f32f55859b57e6805c86a0600eca43fca1ec86c51c1087472616e73666572"

tx.method : "¡GÙب�lÄ�»;�¸¯Yx�t�|ÈL�¡K>]Yg]ÁQL���ó/U��Wæ�\� `�ÊCü¡ì�Å���G&�ç6fW"

how to create a delegation tx

Which is the code part that allows me to create a delegation tx? in order to stake my ONT.
Can you point me to it?

sign transaction failed

Hello, here is my demo running on node11.3, it throws when signing the transaction :

const Account = require('ontology-ts-sdk').Account;
const Crypto = require('ontology-ts-sdk').Crypto;
const ontTxBuilder = require('ontology-ts-sdk').OntAssetTxBuilder;

//account generate by ontology-cli
let keystore = `{
    "address":"AJaz5KyntxxjExiRNYayXy9Xbfejp6V2AS",
    "enc-alg":"aes-256-gcm",
    "key":"PeR8p8qFaFUuUyiUjvD3Blk3EUXpY44D2lo5pWJtSIUpbEnrN43KhnZXXsUaXLar",
    "algorithm":"ECDSA",
    "salt":"+hf+nV312ZlkhFoa65g3KA==",
    "parameters":{"curve":"P-256"},
    "label":"",
    "publicKey":"0241a879cd9328c5f45d8608aa96a8725ea0a7a851785a9255d8f901f9c6fc3ad5",
    "signatureScheme":"SHA256withECDSA",
    "isDefault":true,
    "lock":false
}`

const account = Account.parseJson(keystore);

const tokenType = "ONT";
const to = "AWxFwFUEDzRW5FZbtq81rPEuxHDNd2BWoi";

var tx = ontTxBuilder.makeTransferTx( tokenType, account.address, to, '1000000000', 300, 10000 );
const raw = account.signTransaction("123456",tx);

The exception

Error: 53000
scrypt.ts:399
    at decryptWithGcm (file:///Users/fanlinlin/ws/newbee-task/node_modules/ontology-ts-sdk/lib/index.js:6004:8)
    at decrypt (file:///Users/fanlinlin/ws/newbee-task/node_modules/ontology-ts-sdk/lib/index.js:2423:88)
    at exportPrivateKey (file:///Users/fanlinlin/ws/newbee-task/node_modules/ontology-ts-sdk/lib/index.js:269:33)
    at signTransaction (file:///Users/fanlinlin/ws/newbee-task/node_modules/ontology-ts-sdk/lib/index.js:272:25)
    at (anonymous) (file:///Users/fanlinlin/ws/newbee-task/ont.js:31:20)
    at Module._compile (internal/modules/cjs/loader.js:719:13)
    at Module._extensions..js (internal/modules/cjs/loader.js:733:9)
    at Module.load (internal/modules/cjs/loader.js:620:31)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:11)
    at Module._load (internal/modules/cjs/loader.js:552:2)
    at Module.runMain (internal/modules/cjs/loader.js:775:11)
    at startup (internal/bootstrap/node.js:300:18)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:826:2)

It is a wrapped Exception, I set a breakpoint and found the original Error in scrypt.tx:399:11 is

:"Unsupported state or unable to authenticate data"
stack:"Error: Unsupported state or unable to authenticate data
    at Decipheriv.final (internal/crypto/cipher.js:166:29)
    at decryptWithGcm (/Users/fanlinlin/ws/newbee-task/node_modules/ontology-ts-sdk/lib/index.js:6002:31)
    at PrivateKey.decrypt (/Users/fanlinlin/ws/newbee-task/node_modules/ontology-ts-sdk/lib/index.js:2423:89)
    at Account.exportPrivateKey (/Users/fanlinlin/ws/newbee-task/node_modules/ontology-ts-sdk/lib/index.js:269:34)
    at Account.signTransaction (/Users/fanlinlin/ws/newbee-task/node_modules/ontology-ts-sdk/lib/index.js:272:26)
    at Object.<anonymous> (/Users/fanlinlin/ws/newbee-task/ont.js:31:21)\n    at Module._compile (internal/modules/cjs/loader.js:719:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:733:10)\n    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)"

I know little about scrypt, did I pass the wrong parameters?

Signing Transactions with Different Payer Address: Handling Dual Signature Requirements in OntAssetTxBuilder

How should I sign the transaction if I specify a different payer address than the sender address in the following code snippet?

const tx = OntAssetTxBuilder.makeTransferTx(assetType, from, to, amount, gasPrice, gasLimit, payer);
TransactionBuilder.signTransaction(tx, from_privateKey)

Do I need to sign the transaction twice, first with the sender's private key and then with the fee payer's private key?

const tx = OntAssetTxBuilder.makeTransferTx(assetType, from, to, amount, gasPrice, gasLimit, payer);
TransactionBuilder.signTransaction(tx, from_privateKey)
TransactionBuilder.signTransaction(tx, payer_privateKey)

UnhandledPromiseRejectionWarning:

In Result : 'Address...' has no balance enough to cover gas cost 10000000.

Here my from(admin) address has amount : 30
and I've passed Private key which is returned by Account object while generating address.
I am transferring amount: 1.

This error is occurs every time, with the message that transactor does not have balance enough to cover gas cost 10000000.

get transaction id (hash)

I'm building a transaction, How to get transaction ID/Hash locally before any broadcast happen?
The Transaction hash that will be saved on the blockchain to be clear.

I tried getSignContent() but it's returning a different hash.

'npm run build' missing script build and 'npm run test' isn't working

  1. Compile step failed at below step and throw 'missing script build' error

npm run build

By inspecting package.json, it looks like it should be

npm run build:prod or npm run build:dev

package.json

"scripts": {
    "test": "jest",
    "build:dev": "webpack --display-error-details --config webpack.config.js --progress --color",
    "build:prod": "webpack --env.prod --config webpack.config.js --progress --color"
  }

And webpack installation is a prerequisite for this compile
npm install webpack --save

  1. Test script npm run test isn't working , throwing error 'sh: jest: command not found'

missing dependencies in package.json

Tried to build as per the instructions in Readme and got errors for missing dependencies. Using node 8.10.0. Installed these:

npm install utf-8-validate bufferutil

After that i got following error:

ERROR in ~/ontology-ts-sdk/src/index.ts(124,3)
          TS2304: Cannot find name 'Web'.

I see that Web was added in the most recent commit.

Send Transaction

How to generate raw transaction and broadcast by using web api ?

Why reverseHex once in address.toHexString()

Check code below:

constructor(value: string) {
if (value.length === 40 || value.length === 34) {
this.value = value;
} else {
throw ERROR_CODE.INVALID_PARAMS;
}
}

toHexString() {
let val;
if (this.value.length === 40) {
val = this.value;
} else {
val = base58ToHex(this.value);
}
return reverseHex(val);
}

If pass 40 bytes hex string into Address, then call toHexString(), you will get a reversed wrong hex address.

Invalid y value for curve on require('ontology-ts-sdk')

I got this error right at the require step

2021-07-28 09:37:19.427 ERROR 8476 Logger get balance and amount job error: Error: Invalid y value for curve.
    at Point.validate (/home/minhlpc/Desktop/staking-childpool-admin-web-backend/node_modules/bitcore-lib/lib/crypto/point.js:123:11)
    at new PresetCurve (/home/minhlpc/Desktop/staking-childpool-admin-web-backend/node_modules/elliptic/lib/elliptic/curves.js:22:17)
    at Object.get [as p256] (/home/minhlpc/Desktop/staking-childpool-admin-web-backend/node_modules/elliptic/lib/elliptic/curves.js:32:19)
    at new EC (/home/minhlpc/Desktop/staking-childpool-admin-web-backend/node_modules/elliptic/lib/elliptic/ec/index.js:22:21)
    at Module.<anonymous> (/home/minhlpc/Desktop/staking-childpool-admin-web-backend/node_modules/@ont-dev/hdkey-secp256r1/lib/index.js:1:1814)
    at t (/home/minhlpc/Desktop/staking-childpool-admin-web-backend/node_modules/@ont-dev/hdkey-secp256r1/lib/index.js:1:124)
    at /home/minhlpc/Desktop/staking-childpool-admin-web-backend/node_modules/@ont-dev/hdkey-secp256r1/lib/index.js:1:923
    at Object.<anonymous> (/home/minhlpc/Desktop/staking-childpool-admin-web-backend/node_modules/@ont-dev/hdkey-secp256r1/lib/index.js:1:932)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/home/minhlpc/Desktop/staking-childpool-admin-web-backend/node_modules/ontology-ts-sdk/lib/index.js:1:2731)

Got stuck in this line:

  if (p2.y.cmp(this.y) !== 0) {
    throw new Error('Invalid y value for curve.');
  }

Is there something new on curve function ?

Error serializing tx when using crypto curve ED25519

Here's my example:

const { GovernanceTxBuilder, TransactionBuilder, Crypto } = require('ontology-ts-sdk')
const { PrivateKey, Address } = Crypto

const seed = Buffer.from('05feadb3037d3afc7c878130a73b5b9e8fa6df42899dfaf874b4dfa8ab1bf4a4', 'hex')

const privateKey = new PrivateKey(seed, Crypto.KeyType.EDDSA, { curve: Crypto.CurveLabel.ED25519 })
// const privateKey = new PrivateKey(seed) // IT WORKS without EDDSA schema

//Sender's address
const address = new Address('APT4wZG9sFQfjhyfGALPXQj5UyrQ3ZCVkY')
// peers
const peerPubKeyList = ['039cadf7145731b3c868bd3528da9172757f89b566fc0372cd51b41351c3b6f237']
//Amount to stake
posList = [2]
//Gas price and gas limit are to compute the gas costs of the transaction.
const gasPrice = '2500'
const gasLimit = '20000'
//Payer's address to pay for the transaction gas
const tx = GovernanceTxBuilder.makeAuthorizeForPeerTx(address, peerPubKeyList, posList, address, gasPrice, gasLimit)

TransactionBuilder.signTransaction(tx, privateKey) // BUG with ed25519?

console.log('signed tx', tx)

// serialize tx ready to broadcast

const serialized = tx.serialize()
console.log('tx serialized', serialized)

I get this error when serializing the tx:

RangeError: num (57.5) must be a safe integer
    at Ee (/mnt/SSD-EVO/PROVE2/ontology-prove/node_modules/ontology-ts-sdk/lib/index.js:1:21252)
    at dt (/mnt/SSD-EVO/PROVE2/ontology-prove/node_modules/ontology-ts-sdk/lib/index.js:1:33749)
    at /mnt/SSD-EVO/PROVE2/ontology-prove/node_modules/ontology-ts-sdk/lib/index.js:1:34010
    at vt (/mnt/SSD-EVO/PROVE2/ontology-prove/node_modules/ontology-ts-sdk/lib/index.js:1:34031)
    at e.value (/mnt/SSD-EVO/PROVE2/ontology-prove/node_modules/ontology-ts-sdk/lib/index.js:1:71196)

It works fine without the EDDSA ED25519 crypto schema.

Missing Claim abifunction schema and need a makeInvokeTransaction and buildClaimTx in transactionBuilder.ts

Hi there,

I am testing Claim function here, have signed a claim object and ready to interact with ontology chain to register the claim, a few questions here:

  1. looks like we are missing a json schema section for RegisterClaim in /src/smartcontract/data/IdContract.abi.ts

  2. also need a new helper function makeInvokeTransaction in /src/transaction/transactionBuilder.ts
    current makeInvokeTransaction is declaring tx.type=TxType.Invoke, which should be TxType.Claim for Claim Tx, assuming other parameters remain the same.

  3. finally we need a new buildClaimTx helper function to construct the payload. Should it follow the same pattern as buildAddAttributeTx which takes 5 parameters to build?; Or 4 parameters without type, as described in identity_claim.md

'''var param = SDK.buildClaimTx(path, value, ontid, privateKey)'''

Happy to contribute by writing/testing them then submitting a pull request, if I know the required schema for RegisterClaim?

Thanks,
Bobio

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.