GithubHelp home page GithubHelp logo

xchainjs / xchainjs-lib Goto Github PK

View Code? Open in Web Editor NEW
101.0 9.0 91.0 10.48 MB

Lightweight typescript library for cross-chain wallets. Connect with multiple blockchains via a common interface, with support for the minimum features necessary.

License: MIT License

TypeScript 88.73% JavaScript 10.86% Shell 0.40%
bitcoin blockchain wallet binance bitcoincash cosmos ethereum litecoin thorchain

xchainjs-lib's Introduction

Contributors Forks Stargazers Issues MIT License


XChainJS is a comprehensive toolkit designed to facilitate blockchain development by providing developers with a wide range of utilities, modules, and functionalities. Its purpose is to streamline the process of building decentralized applications (DApps), interacting with blockchain networks, and integrating blockchain technology into various projects.

The library aims to abstract away the complexities of blockchain development, allowing developers to focus on building innovative solutions without getting bogged down in low-level implementation details.

Purpose

  • Simplify Blockchain Development: The primary purpose of the XchainJS library is to simplify blockchain development by providing developers with high-level abstractions and ready-to-use tools for common blockchain tasks.

  • Promote Interoperability: The library aims to promote interoperability by offering support for multiple blockchain protocols and standards, enabling developers to build applications that can interact seamlessly with different blockchain networks.

  • Empower Developers: By abstracting away the complexities of blockchain technology, the XchainJS library empowers developers of all skill levels to leverage the potential of blockchain in their projects, regardless of their expertise in cryptography or distributed systems.

Scope

Blockchain Interaction: The XchainJS library covers a wide range of functionalities related to interacting with blockchain networks, including transaction handling, wallet management, protocols interactions, and data querying. Protocol Support: It provides support for various blockchain protocols and standards, such as THORChain and MAYAProtocol.

Utilities and Tools: The library offers a collection of utilities and tools for common blockchain tasks, including cryptographic operations, address formatting, transaction parsing, and fetching data.

Key Features

Modularity: The xchain library is modular, allowing developers to pick and choose the modules and functionalities they need for their specific use cases. This modular approach promotes flexibility and scalability in blockchain development.

Abstraction: It abstracts away the complexities of blockchain technology, providing developers with high-level interfaces and abstractions that shield them from low-level implementation details.

Protocol Agnosticism: The library is designed to be protocol-agnostic, meaning it can support multiple blockchain protocols and standards. This allows developers to build applications that are not tied to a specific blockchain network.

Community Support: The xchain library is supported by a vibrant community of developers and contributors who actively maintain and improve the library, ensuring its relevance and usability in the rapidly evolving blockchain landscape.

Examples

To show different use cases and to facilitate developers experience with XChainJS, we have created a few examples on CodeSandbox where you will be able to see and fork our examples to create yours.

Follow the examples instructions to be able to start working with the library in just a few minutes.

Examples:

Documentation

More information about how to use each XChainJS package can be found on documentation

Packages

XChainJS is a library made up of different packages through which you can interact with different blockchains, data providers and protocols, or use its utility functions to simplify blockchain development.

Client packages

Blockchain clients with whom you can prepare, make and broadcast transactions, estimate transactions fees and get address balances.

Name Download
@xchainjs/xchain-bitcoin npm
@xchainjs/xchain-ethereum npm
@xchainjs/xchain-thorchain npm
@xchainjs/xchain-mayachain npm
@xchainjs/xchain-bitcoincash npm
@xchainjs/xchain-litecoin npm
@xchainjs/xchain-doge npm
@xchainjs/xchain-dash npm
@xchainjs/xchain-avax npm
@xchainjs/xchain-arbitrum npm
@xchainjs/xchain-bsc npm
@xchainjs/xchain-kujira npm
@xchainjs/xchain-cosmos npm
@xchainjs/xchain-binance npm

Utility packages

Utility packages

Name Download
@xchainjs/xchain-util npm
@xchainjs/xchain-crypto npm

Data provider packages

Data providers to retrieve blockchain data

Name Download
@xchainjs/xchain-utxo-providers npm
@xchainjs/xchain-evm-providers npm

Protocol packages

Thorchain

Packages to interact with Thorchain

Name Download
@xchainjs/xchain-thornode npm
@xchainjs/xchain-midgard npm
@xchainjs/xchain-thorchain-query npm
@xchainjs/xchain-thorchain-amm npm

Mayachain

Packages to interact with Mayachain

Name Download
@xchainjs/xchain-mayanode npm
@xchainjs/xchain-mayamidgard npm
@xchainjs/xchain-mayachain-query npm
@xchainjs/xchain-mayachain-amm npm

Really cool packages

Poweful tool to build whatever you want...

Name Download
@xchainjs/xchain-wallet npm
@xchainjs/xchain-aggregator npm

Tools

TxJammer

Tx Jammer is a script which pushes a random amount of different types of transactions to stagenet to verify new stagenet releases

Contributing

What to become a XChainJS contributor? Read our CONTRIBUTING.md and be part of our contributor member. It's people like you that make XChainJS better.

xchainjs-lib's People

Contributors

0xp3gasus avatar ahdzib-maya avatar baebb avatar davidp94 avatar ecalchot-maya avatar fedorovian avatar github-actions[bot] avatar gromxyz avatar hellokashif avatar hippocampus-web3 avatar icafa avatar l0blolly avatar mikewyszinski avatar mrnerdhair avatar omahs avatar pluto9r avatar polaris-9r avatar severinwullschleger avatar sourovafrin avatar ssdbkey avatar stoicdev6 avatar stuartwk avatar thatstrangeguythorchain avatar the-eridanus avatar thorcat avatar thorchain-admin avatar thorian1te avatar thorswapdev avatar veado avatar woweek 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

xchainjs-lib's Issues

ADD: xchain-utils

Bring in all the necessary util functions from the asgardex-utils lib so this is a complete package.

such as baseAmount and assetAmount logic.

ADD: getTransactionData(TxId)

Add a function to all clients:

getTransactionData(TxId: string): Promise<TxData>

Queries the provider and returns TxData object. The TxData is the same as that returned in getTransactions()

{ 
    "hash" : "980D9519CCB39DC02F8B0208A4D181125EE8A2678B280AF70666288B62957DAE",
    "from" : "34xp4vRoCGJym3xR7yCVPFHoCNxv4Twseo",
    "to" : 34vRoCGJym3xR7yCVPFHoCNxv4Twseoxp4,
    "amount": 100000000,
    "asset" : "BTC.BTC",
    "fee" : 2500,
    "memo" : "transfer"
    "date" : "2020-10-04T06:24:36.548Z"
   }

ToDo List

  • XChainClient Definition DONE w/ #63

  • Bitcoin

  • Binance Chain DONE w/ #63

  • Ethereum

  • THORChain DONE w/ #63

  • Cosmos

Provide `getDefaultFees` for all clients

If getFees might fail, a front-end should still have an option to get default (hard-coded) fees.

TODO

(1) Add getDefaultFees to interface XChainClient

getDefaultFees(): Fees

(2) Implement getDefaultFees for each client to return default fees.

Default fees (TBD):

  • Binance
average: 0.000375 BNB
fast: 0.000375 BNB
fastest: 0.000375 BNB
  • BTC
average: 10 sats/byte
fast: 20 sats/byte
fastest: 50 sats/byte
  • Cosmos
average: ???
fast: ???
fastest: ???
  • Polkadot
average: ???
fast: ???
fastest: ???
  • Thorchain
average: ???
fast: ???
fastest: ???

FIX: getSeed and BIP39

Fix these:

-crypto

  • remove the phrase length check in getSeed() Done #108
  • add a BIP39.validatePhrase(phrase) in getSeed()
  • add a BIP39.validatePhrase(phrase) in encryptToKeystore()
  • remove getAddress()
  • remove getPublicKeyPair()
  • remove pub keys from keystore meta-data

Downstream Clients

  • remove BIP39 imports - Done in *bitcoin #106
  • call xchain.getSeed() when getting seed

[xchain-binance] Provide method to get single and multi fee at once

To get single and multi fees, two (same) request are made behind the scenes:

Provide another method getSingleAndMultiFees to get both fees with one method + one request only:

getSingleAndMultiFees(): Promise<{single: Fees, multi: Fees}>

xchain-bitcoin: Add `getFeeRates`

Information about fee rates seems to be get lost while migrating asgardex-bitcoin into xchain-bitcoin. Let's bring it back by providing a getFeeRates method in client.ts

DEPRECATE: deposit() function

Since XChainJS is intended to be blockchain agnostic, there is no need to have a Thorchain specific function.

Devs should use transfer() function to make the deposit, or that does not work for the chain, use a specific extended function.

  • Bitcoin
  • Binance
  • Ether

Update `getFees`

Need to update fee handling in xchain-cosmos and xchain-thorchain.

[xchain-cosmos] Timeout by running tests

yarn test                                                                   
yarn run v1.22.5
$ jest
 PASS  __tests__/util.test.ts
 PASS  __tests__/client.test.ts (6.685 s)
 FAIL  __tests__/sdk-client.test.ts (63.705 s)
  ● SDK Client Test › getBalance

    : Timeout - Async callback was not invoked within the 30000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 30000 ms timeout specified by jest.setTimeout.Error:

      94 |   })
      95 | 
    > 96 |   it('getBalance', async () => {
         |   ^
      97 |     let balances = await cosmosMainnetClient.getBalance(cosmos_address)
      98 |     expect(balances).toEqual([])
      99 | 

      at new Spec (../../node_modules/jest-cli/node_modules/jest-jasmine2/build/jasmine/Spec.js:116:22)
      at Suite.<anonymous> (__tests__/sdk-client.test.ts:96:3)

  ● SDK Client Test › transfer

    : Timeout - Async callback was not invoked within the 30000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 30000 ms timeout specified by jest.setTimeout.Error:

      162 |   })
      163 | 
    > 164 |   it('transfer', async () => {
          |   ^
      165 |     const expected_txsPost_result: BroadcastTxCommitResult = {
      166 |       check_tx: {},
      167 |       deliver_tx: {},

      at new Spec (../../node_modules/jest-cli/node_modules/jest-jasmine2/build/jasmine/Spec.js:116:22)
      at Suite.<anonymous> (__tests__/sdk-client.test.ts:164:3)

A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --runInBand --detectOpenHandles to find leaks.
Test Suites: 1 failed, 2 passed, 3 total
Tests:       2 failed, 27 passed, 29 total
Snapshots:   0 total
Time:        64.563 s, estimated 69 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

ADD: BIP44 Spec address derivation

Current

Phrase is used directly for entropy

Desired

BIP 44 compatibility with other wallets. However the client will only use Index 0, but can in future handle multiple indexes at the same time (eg, like using "sub-accounts" in a single wallet).

Hardcode SLIP44 path

Hard code in the SLIP44 path into each client as a private variable
https://github.com/satoshilabs/slips/blob/master/slip-0044.md

Derive key && address using Index 0

getAddress(): Address

This should derive using BIP44, but index 0 only.

Implementation

  • Bitcoin (84/0/0/0)

  • Binance Chain (44/714/0/0)

  • Ethereum (44/30/0/0)

  • THORChain (44/931/0/0)

  • Cosmos ( 44/118/0/0)

FIX: Handle 0 balance for BinanceClient

For Cosmos chains an address with 0 balance will return an error and cause the client to fall over.

It should be caught (use try{}catch(err){}) and return a balance of 0 instead.

ADD: xchain-crypto

Bring in the old asgardex-crypto library and make it a package xchain-cryptoz

Also update imports throughout.

Add `getExplorerUrl`

To get information about current explorer url all clients do need to provide a getExplorerUrl function

[xchain-thorchain] Timeout by running tests

yarn test
yarn run v1.22.5
$ jest
 PASS  __tests__/util.test.ts
(node:17290) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
 FAIL  __tests__/client.test.ts (28.364 s)
  ● Client Test › has no balances

    : Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:

       99 |   })
      100 | 
    > 101 |   it('has no balances', async () => {
          |   ^
      102 |     const result = await thorClient.getBalance()
      103 |     expect(result).toEqual([])
      104 |   })

      at new Spec (../../node_modules/jest-cli/node_modules/jest-jasmine2/build/jasmine/Spec.js:116:22)
      at Suite.<anonymous> (__tests__/client.test.ts:101:3)

  ● Client Test › has an empty tx history

    : Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:

      113 |   })
      114 | 
    > 115 |   it('has an empty tx history', async () => {
          |   ^
      116 |     const expected: TxsPage = {
      117 |       total: 0,
      118 |       txs: [],

      at new Spec (../../node_modules/jest-cli/node_modules/jest-jasmine2/build/jasmine/Spec.js:116:22)
      at Suite.<anonymous> (__tests__/client.test.ts:115:3)

  ● Client Test › transfer

    : Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:

      165 |   })
      166 | 
    > 167 |   it('transfer', async () => {
          |   ^
      168 |     const to_address = 'tthor19kacmmyuf2ysyvq3t9nrl9495l5cvktj5c4eh4'
      169 |     const send_amount: BaseAmount = baseAmount(10000, 6)
      170 |     const memo = 'transfer'

      at new Spec (../../node_modules/jest-cli/node_modules/jest-jasmine2/build/jasmine/Spec.js:116:22)
      at Suite.<anonymous> (__tests__/client.test.ts:167:3)

  ● Client Test › deposit

    : Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:

      201 |   })
      202 | 
    > 203 |   it('deposit', async () => {
          |   ^
      204 |     const to_address = 'tthor19kacmmyuf2ysyvq3t9nrl9495l5cvktj5c4eh4'
      205 |     const send_amount: BaseAmount = baseAmount(10000, 6)
      206 |     const memo = 'deposit'

      at new Spec (../../node_modules/jest-cli/node_modules/jest-jasmine2/build/jasmine/Spec.js:116:22)
      at Suite.<anonymous> (__tests__/client.test.ts:203:3)

A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --runInBand --detectOpenHandles to find leaks.
Test Suites: 1 failed, 1 passed, 2 total
Tests:       4 failed, 12 passed, 16 total
Snapshots:   0 total
Time:        29.205 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

It seems very similar to #49

ADD: Polkadot

Do research on the best remote service to use to get polkadot data

Update `xchain-ethereum` to implement `XChainClient` interface

  • Implement XChainClient interface
  • Remove static methods generatePhrase + validatePhrase
  • Use helpers of xchain-crypto (instead of 'bip39')
  • Upgrade to latest xchain-client
  • Check other methods, we might not need all such as getBlockNumber, getTransactionCount or others
  • Fix rollup warning by running yarn build: (!) Unresolved dependencies by adding events to external of rollup config
  • Fix rollup warning by running yarn build: Circular dependencies

ADD: Call()

Extend xchain-ethereum to include

.call(address, abi, function, params) , which means, you can pass an arbitrary contract address, with it's arbitratry abi, then call an arbitrary function, with arbitrary params.

In the case for THORChain vault contract, it would be:

call(vault_address, vault_abi, deposit, [asset, amount]) the params are ordered in their correct order for the function.

Update `Fees`

Make values for fast and fastest necessary (not optional). If there is any chain, which provides one fee only, we will set same value for average, fast, fastest.

HAVE

export type Fees = {
  type: FeeType
  fastest?: BaseAmount
  fast?: BaseAmount
  average: BaseAmount
}

WANT

type Fees = {
    type: FeeType
    fastest: BaseAmount
    fast: BaseAmount
    average: BaseAmount
}

FIX: Transfer Function

  1. transfer ether is no issue, just send it, encode the memo in the data field. It's just a standard tx. The asset should be as 0x000..000 , so use an IF statement to know the user wishes to send Ether.
  2. If asset != 0x000..000 then it is an ERC20. Thus you must have the ERC20 ABI loaded into the client, like const ERC20_ABI = require('/ERC20_ABI.json)` . Get this ABI from the open-zeppelin librarary, in fact any ERC20 ABI will do.
  • Then you must do a smart contract call, loading the contract like let tokenContract = new ethers.Contract( address , abi , signerOrProvider )
    https://docs.ethers.io/v5/api/contract/contract/#Contract-connect

  • You must also figure out who is responsible for handling decimals - is it the wallet or the client? If the wallet always passes in 10**8, then you need to convert this to the token's decimals, because token could be decimals 0-18, you can find out like let decimals = await tokenContract.decimals() then converting
    https://docs.ethers.io/v5/api/contract/contract/#Contract-functionsCall

  • then let tx = await tokenContract.functions.transfer(recipient, amount) , noting you cannot do anything with the memo.

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.