Git Product home page Git Product logo

irishub-sdk-js's Introduction

irishub-sdk-js

Banner License Version

The IRISnet JavaScript SDK allows browsers and Node.js clients to interact with IRISnet. Core functionality and examples are in the test folder.

  • client - client that implements IRISnet transactions types, such as for transfers and staking,etc.
  • crypto - core cryptographic functions.
  • accounts - management of accounts and wallets, including seed and encrypted mnemonic generation, recover account by mnemonic or keystore, etc.

Installation

Install the package via npm.

npm install https://github.com/irisnet/irishub-sdk-js.git

Config

interface ClientConfig {
    node: string,//address of a rpc node on IRISnet
    chainNetwork: consts.ChainNetwork; // IRISHUB = 0, Cosmos = 1, Akash = 2
    chainId: string,
    gas?: string,
    fee?: {
        denom: string;
        amount: string;
    }, //default fee for transactions
    keyDAO: KeyDAO,//key manager for wallet, which must be implemented
    bech32Prefix?: {
        AccAddr: string,
        AccPub: string,
        ValAddr: string,
        ValPub: string,
        ConsAddr: string,
        ConsPub: string,
    },
    rpcConfig?: AxiosRequestConfig// axios request config
}

Client Setup

First you should implement your KeyDAO like follows:

class KeyDAO {
    /**
     * save private key to client
     * @param name for account you generated, which will be use to query private key and other account info
     * @param wallet: {address: string,privateKey: string,publicKey: string,mnemonic: string}
     * @throws error if save failed
     */
    write(name, wallet):void {
        localStorage.setItem(name, JSON.stringify(wallet));
    }

    /**
     * save walet in client
     * @param name
     * @throws error if read failed
     */
    read(name):wallet{
        const wallet = localStorage.getItem(name);
        if(wallet) {
            return JSON.parse(wallet);
        }
        throw new Error(`no wallet was found`)
    }

    /**
     * encrypt your private key before save to client
     * @param private key
     * @param password for encrypt private key
     */
    encrypt?(privateKey, password): string {
        return CryptoJS.AES.encrypt(msg, password).toString();
    }

    /**
     * decrypto your private key with password
     * @param encrypted private key
     * @param password that can decrypto private key ecrypted
     */
    decrypt?(encryptedPrivateKey, password): string {
        const bytes = CryptoJS.AES.decrypt(encryptedPrivateKey, password);
        const privateKey = bytes.toString(CryptoJS.enc.Utf8);
        if (privateKey) {
            return privateKey
        } else {
            throw new Error('can not decrypto the private key');
        }

    }

}
import {newClient as irisSdkClient} from 'irishub-sdk-js';

const client = irisSdkClient(ClientConfig)
    .withKeyDAO(new KeyDAO())
    .withRpcConfig({timeout: 15000});

Client Usage

The following selected examples demonstrate basic client usage.

  • create account
const account: { address: string, mnemonic: string } = client.keys.add(`wallet name`, 'wallet password');
  • recover account by mnemonic
const account: string = client.keys.recover(`wallet name`, 'wallet password', `mnemonic`);
  • recover account by keystore
const account: string = client.keys.recover(`wallet name`, 'wallet password', `keystore`);
  • transfer example
const res = await client.bank.send({
    to:`iaa1eqvkfthtrr93g4p9qspp54w6dtjtrn27ar7rpw`,
    amount:[{
        denom:`uiris`,
        amount:`1000000`
    }],
    baseTx:{
        from:`wallet name`,
        password:`wallet password`,
        gas:50000,
        fee:{
            denom:`uiris`,
            amount:`500000`
        }
    }
})

auth src/modules/auth.ts

  • newStdTx
  • queryAccount
  • queryAccounts
  • queryParams

bank src/modules/bank.ts

  • send
  • multiSend
  • queryBalance
  • queryAllBalances
  • queryTotalSupply
  • querySupplyOf
  • queryDenomMetadata
  • queryDenomsMetadata
  • queryParams

coinswap src/modules/coinswap.ts

  • addLiquidity
  • removeLiquidity
  • swapOrder
  • queryLiquidity

distribution src/modules/distribution.ts

  • setWithdrawAddr
  • withdrawRewards
  • withdrawValidatorCommission
  • fundCommunityPool
  • queryParams
  • queryValidatorOutstandingRewards
  • queryValidatorCommission
  • queryValidatorSlashes
  • queryDelegationRewards
  • queryDelegationTotalRewards
  • queryDelegatorValidators
  • queryDelegatorWithdrawAddress
  • queryCommunityPool

farm src/modules/farm.ts

  • stakeLp
  • unStakeLp
  • harvestReward
  • queryFarmPools
  • queryFarmPool
  • queryFarmer
  • queryParams

gov src/modules/gov.ts

  • queryProposal
  • queryProposals
  • queryVote
  • queryVotes
  • queryDeposit
  • queryDeposits
  • queryTally
  • submitParameterChangeProposal
  • submitPlainTextProposal
  • submitCommunityTaxUsageProposal
  • deposit
  • vote
  • voteWeighted

htlc src/modules/htlc.ts

  • createHTLC
  • claimHTLC
  • queryHTLC
  • queryAssetSupply
  • queryAssetSupplies
  • queryParams

ibc src/modules/ibc/ibc.ts

  • transfer
  • queryDenomTrace
  • queryDenomTraces
  • queryParams
  • queryChannels

ibc-nft-transfer src/modules/ibc/ibc-nft-transfer.ts

  • transfer
  • queryClassTrace
  • queryClassTraces
  • queryClassHash
  • queryEscrowAddress
  • queryParams

keys src/modules/keys.ts

  • add
  • recover
  • import
  • importPrivateKey
  • export
  • delete
  • show

nft src/modules/nft.ts

  • issueDenom
  • mintNft
  • editNft
  • transferNft
  • burnNft
  • querySupply
  • queryOwner
  • queryCollection
  • queryDenom
  • queryDenoms
  • queryNFT

oracle src/modules/oracle.ts

  • queryFeed
  • queryFeeds
  • queryFeedValue

protobuf src/modules/protobuf.ts

  • deserializeTx
  • unpackMsg
  • deserializeSignDoc
  • deserializeTxRaw
  • deserializeSigningInfo
  • deserializePubkey

random src/modules/random.ts

  • queryRandom
  • queryRequest
  • request

service src/modules/service.ts

  • queryDefinition
  • queryBinding
  • queryBindings
  • queryRequest
  • queryRequests
  • queryRequestsByReqCtx
  • queryRequestContext
  • queryResponse
  • queryResponses
  • queryFees
  • defineService
  • bindService
  • updateServiceBinding
  • disableServiceBinding
  • enableServiceBinding
  • invokeService
  • setWithdrawAddress
  • refundServiceDeposit
  • startRequestContext
  • pauseRequestContext
  • killRequestContext
  • updateRequestContext
  • withdrawEarnedFees
  • withdrawTax

slashing src/modules/slashing.ts

  • queryParams
  • querySigningInfo
  • unjail

staking src/modules/staking.ts

  • delegate
  • undelegate
  • redelegate
  • queryDelegation
  • queryDelegations
  • queryUnbondingDelegation
  • queryDelegatorUnbondingDelegations
  • queryRedelegation
  • queryDelegatorValidators
  • queryDelegatorValidator
  • queryHistoricalInfo
  • queryValidatorDelegations
  • queryValidatorUnbondingDelegations
  • queryValidator
  • queryValidators
  • queryPool
  • queryParams
  • appendZero
  • createValidator

tendermint src/modules/tendermint.ts

  • queryBlock
  • queryBlockResult
  • queryTx
  • queryValidators
  • searchTxs
  • queryNetInfo
  • queryGlobalAccountNumber

token src/modules/token.ts

  • issueToken
  • editToken
  • mintToken
  • transferTokenOwner
  • queryTokens
  • queryToken
  • queryFees
  • queryParameters

tx src/modules/tx.ts

  • buildTx
  • newStdTxFromProtoTxModel
  • buildAndSend
  • broadcast
  • sign
  • sign_signDoc
  • broadcastTxAsync
  • broadcastTxSync
  • broadcastTxCommit
  • broadcastTx
  • newTxResult
  • createMsg

irishub-sdk-js's People

Contributors

chengwenxi avatar dependabot[bot] avatar dreamer-zq avatar duanjie-cmd avatar hangts avatar lavender66 avatar marshallbao avatar oncloudit avatar zhangjinbiao746 avatar zhangyelong avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

irishub-sdk-js's Issues

Gov Module

  • query-proposal Query details of a single proposal
  • query-proposals Query proposals with optional filters
  • query-vote Query vote
  • query-votes Query votes on a proposal
  • query-deposit Query details of a deposit
  • query-deposits Query deposits on a proposal
  • query-tally Get the tally of a proposal vote
  • submit-proposal Submit a proposal along with an initial deposit
  • deposit Deposit tokens for activing proposal
  • vote Vote for an active proposal, options: Yes/No/NoWithVeto/Abstain

EventListener Framework

Ref: #22

Develop EventListener Framework:

  • connect: init ws client
  • disconnect: destroy ws client
  • onError: callback on error

Subscribe Tx

Ref: #22

Provide a Subscribe Tx function which accepts user defined query params.

Tendermint Query Methods Implementation

  • queryBlock(height?: number)
  • queryBlockResult(height?: number)
  • queryTx(hash: string)
  • searchTxs(query: QueryBuilder, page?: number, size?: number)
  • queryValidators(height?: number)

Business logic layer listeners

In general, we may need the following event listeners:

  1. Transfers - used to monitor transfers to a certain address, etc.
  2. Validator Info - used to monitor whether the validator has changed the commission ratio, etc.
  3. Validator Status - used to monitor whether the status of the validator is abnormal or the voting power has changed significantly
  4. Service - Invocation and callback notification
  5. Coinswap - Liquidity monitoring

Ref: #22

SDK Structure

Initialize sdk instance in some ways like:

let sdk = iris.newSdk(config: SdkConfig)
  • SdkConfig *:SDK default configs
    • node *:irishub full node addr
    • network:mainnet / testnet(default: mainnet)
    • chainId:Identity of the chain(default: irishub)
    • gas:default gas limit(default: 100000)
    • fee:default fee(default: 0.6iris)
    • keyDAO:Keys Data Access Object,to be implemented by Apps
      • write(param:TBD):save the Keystore to Apps
      • read(name: string):read Keystore from Apps
        • name: Key name

Key Management

Implement the Keys Module:

  • Add a new Key
  • Recover an existing Key by seed phrase
  • Add Ledger Support
  • Import from Keystore
  • Export Keystore
  • Delete Keys
  • Show Keys
  • HD Wallet Support

Subscribe NewBlockHeader

Ref: #22

Provide a Subscribe NewBlockHeader function, and convert ProposerAddress in Header to bech32 encoded.

Bank Module

Implement Bank Module:

  • Get CoinType
  • Get Token Stats
  • Get Account Info
  • Send Coins
  • Burn Coins
  • Set Memo Regexp

Blocked by #14, #15

Project Init

Initialize irishub-sdk-js, using Yarn + Typescript + Jest

Store account pubkey locally

For offline signing and new account signing, we can not obtain the account pubkey from the blockchain, so we need to store/get the account pubkey locally.

Staking Module

  • queryDelegation
  • queryDelegations
  • queryUnbondingDelegation
  • queryUnbondingDelegations
  • queryRedelegation
  • queryRedelegations
  • queryDelegationsTo
  • queryUnbondingDelegationsFrom
  • queryRedelegationsFrom
  • queryValidator
  • queryValidators
  • queryPool
  • queryParams
  • delegate
  • unbond
  • redelegate

Docs CI

Add CI/CD config for TypeDoc

Unit Conversion

  • Auto convert input coins to min unit (irishub api only accepts min unit)
  • Do not convert output coins (for performance and precision purpose)
  • Users can use the separated methods toMinCoin and toMainCoin to convert coin units

Distribution Module

  • queryRewards
  • setWithdrawAddr
  • withdrawRewards
    • withdrawValidatorRewardsAll
    • withdrawDelegatorReward
    • withdrawDelegatorRewardsAll

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.