Skip to content

Commit

Permalink
843 update docs (#844)
Browse files Browse the repository at this point in the history
  • Loading branch information
hippocampus-web3 authored Oct 2, 2023
1 parent 65d0449 commit 4860de1
Show file tree
Hide file tree
Showing 9 changed files with 105 additions and 12 deletions.
2 changes: 1 addition & 1 deletion packages/xchain-client/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# XChainJS Wallet Client Interface

A specification for a generalised interface for crypto wallets clients, to be used by XChainJS implementations. The client should not have any functionality to generate a key, instead, the `asgardex-crypto` library should be used to ensure cross-chain compatible keystores are handled. The client is only ever passed a master BIP39 phrase, from which a temporary key and address is decoded.
A specification for a generalised interface for crypto wallets clients, to be used by XChainJS implementations. The client should not have any functionality to generate a key, instead, the `xchain-crypto` library should be used to ensure cross-chain compatible keystores are handled. The client is only ever passed a master BIP39 phrase, from which a temporary key and address is decoded.

## Documentation

Expand Down
47 changes: 45 additions & 2 deletions packages/xchain-cosmos-sdk/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export type CosmosSdkClientParams = XChainClientParams & {
}

/**
* Cosmos-sdk client
* Generic implementation of the XChainClient interface chains built with cosmos-sdk (https://docs.cosmos.network/) using the dependencies of the official @cosmjs monorepo.
*/
export default abstract class Client extends BaseXChainClient implements XChainClient {
private readonly startgateClient: CachedValue<StargateClient>
Expand All @@ -48,6 +48,8 @@ export default abstract class Client extends BaseXChainClient implements XChainC
protected readonly baseDenom: string
/**
* Constructor
* @constructor
* @param {CosmosSdkClientParams} params client configuration (prefix, decimal, fees, urls...)
*/
constructor(params: CosmosSdkClientParams) {
super(params.chain, params)
Expand All @@ -70,7 +72,10 @@ export default abstract class Client extends BaseXChainClient implements XChainC
}

/**
* Give 300000uatom return { amount: 300000, denom: uatom }
* @private
* Split on amount and denom strings with format 300000uatom
* @param {string[]} amountsAndDenoms strings with format 3000uatom
* @returns {Array} array of strings splitted { amount: 300000, denom: uatom }
*/
private splitAmountAndDenom(amountsAndDenoms: string[]) {
const amounAndDenomParsed: { amount: string; denom: string }[] = []
Expand All @@ -87,6 +92,12 @@ export default abstract class Client extends BaseXChainClient implements XChainC
return amounAndDenomParsed
}

/**
* @private
* Function that transforms the transaction type returned by cosmjs to the transaction type used by xchainjs.
* @param {IndexedTx} indexedTx transaction to transform
* @returns {Tx} transaction with xchainjs format
*/
private async mapIndexedTxToTx(indexedTx: IndexedTx): Promise<Tx> {
const mapTo: Map<Address, { amount: BaseAmount; asset: Asset | undefined }> = new Map()
const mapFrom: Map<Address, { amount: BaseAmount; asset: Asset | undefined }> = new Map()
Expand Down Expand Up @@ -181,6 +192,11 @@ export default abstract class Client extends BaseXChainClient implements XChainC
}
}

/**
* This function returns the fee object in a generalised way for a simple transfer function. In this case this funcion use the default fee
* defined in the constructor.
* @returns {Fees} fees estimation for average, fast and fastests scenarios.
*/
getFees(): Promise<Fees> {
return Promise.resolve(singleFee(FeeType.FlatFee, this.defaultFee))
}
Expand All @@ -194,6 +210,11 @@ export default abstract class Client extends BaseXChainClient implements XChainC
}
}

/**
* Get an address derived from the phrase defined in the constructor.
* @param {number | undefined} walletIndex derivation path index of address that will be generated
* @returns {string} user address at index defined on walletIndex
*/
public getAddress(walletIndex?: number | undefined): string {
const seed = xchainCrypto.getSeed(this.phrase)
const node = BIP32.fromSeed(seed)
Expand All @@ -209,6 +230,11 @@ export default abstract class Client extends BaseXChainClient implements XChainC
return address
}

/**
* Validate the address format.
* @param {string} address address to be validated
* @returns {boolean} represents whether the address is valid or invalid
*/
public validateAddress(address: string): boolean {
try {
const { prefix: decodedPrefix } = fromBech32(address)
Expand All @@ -221,6 +247,13 @@ export default abstract class Client extends BaseXChainClient implements XChainC
}
}

/**
* Obtains all the balances of the address passed as parameter for all the assets of the network. For the moment for this client the assets parameter is ignored.
* Do not hesitate to open a PR if you need it and it is not yet available.
* @param {string} address address to be validated
* @param {Asset[] | undefined} _assets IGNORED FOR THIS IMPLEMENTATION
* @returns {Balance[]} array of balances
*/
public async getBalance(address: string, _assets?: Asset[] | undefined): Promise<Balance[]> {
const client = await this.startgateClient.getValue()
const result = await client.getAllBalances(address)
Expand All @@ -238,6 +271,11 @@ export default abstract class Client extends BaseXChainClient implements XChainC
return balances
}

/**
* Get transactions filtered using params
* @param {TxHistoryParams | undefined} params Only param address IS SUPPORTED FOR THIS CLIENT, new feature will be added in the future
* @returns {TxsPage} array of balances
*/
public async getTransactions(params?: TxHistoryParams | undefined): Promise<TxsPage> {
// TODO: Use all filters
if (params?.startTime || params?.limit || params?.offset) {
Expand Down Expand Up @@ -271,6 +309,11 @@ export default abstract class Client extends BaseXChainClient implements XChainC
}
}

/**
* Get transaction info using txId
* @param {string} txId Idetifier of transaction
* @returns {Tx} Transaction data
*/
public async getTransactionData(txId: string, _assetAddress?: string | undefined): Promise<Tx> {
const client = await this.startgateClient.getValue()
const tx = await client.getTx(txId)
Expand Down
2 changes: 1 addition & 1 deletion packages/xchain-evm-providers/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# XChainJS API UTXO providers Interface

A specification for a generalised interface for api providers, to be used by XChainJS implementations. The providers should not have any functionality to generate a key, instead, the `asgardex-crypto` library should be used to ensure cross-chain compatible keystores are handled. The providers is only ever passed a master BIP39 phrase, from which a temporary key and address is decoded.
A specification for a generalised interface for api providers, to be used by XChainJS implementations. The providers should not have any functionality to generate a key, instead, the `xchain-crypto` library should be used to ensure cross-chain compatible keystores are handled. The providers is only ever passed a master BIP39 phrase, from which a temporary key and address is decoded.

## Documentation

Expand Down
15 changes: 13 additions & 2 deletions packages/xchain-midgard-query/src/midgard-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const MILLISECOND_CACHE_SAVERS = 5000
const defaultMidgard = new Midgard()

/**
* This class manages retrieving information from Midgard API and cached it
* This class retrieves raw information from Midgard API and cached it
*/
export class MidgardCache {
readonly midgard: Midgard
Expand All @@ -18,7 +18,7 @@ export class MidgardCache {
/**
* Constructor to create a ThorchainCache
*
* @param midgard - an instance of the midgard API (could be pointing to stagenet,testnet,mainnet)
* @param {Midgard} midgard - an instance of the midgard API (could be pointing to stagenet,testnet,mainnet)
* @returns MidgardCache
*/
constructor(midgard = defaultMidgard) {
Expand All @@ -27,10 +27,21 @@ export class MidgardCache {
this.cachedSavers = new CachedValue<SaverDetails>(() => this.midgard.getSavers(''), MILLISECOND_CACHE_SAVERS)
}

/**
* Get info about existing pools in the protocol from Midgard API
*
* @returns {PoolDetail[]} Array of pools
*/
public async getPools(): Promise<PoolDetail[]> {
return this.cachedPools.getValue()
}

/**
* Returns the information of all the positions of a set of addresses in the THORChain savers product.
*
* @param {String} address Comma separated list of addresses
* @returns {SaverDetails} Array of savers positions
*/
public async getSavers(address: string): Promise<SaverDetails> {
return this.cachedSavers.getValue(address)
}
Expand Down
25 changes: 22 additions & 3 deletions packages/xchain-midgard-query/src/midgard-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,28 @@ const DEFAULT_THORCHAIN_DECIMALS = 8
const defaultCache = new MidgardCache()

/**
* THORChain Class for getting data from Midgard API (THORChain L2 Api).
* Class for getting data and process from Midgard API using MidgardCache for optimize request number (THORChain L2 Api).
*/
export class MidgardQuery {
readonly midgardCache: MidgardCache

/**
* Contructor to create a ThorchainAMM
* Contructor to create a MidgardQuery
*
* @param midgardCache - an instance of the midgardCache (could be pointing to stagenet,testnet,mainnet)
* @returns ThorchainAMM
* @returns MidgardQuery
*/
constructor(midgardCache = defaultCache) {
this.midgardCache = midgardCache
}

/**
* Get pool by asset
*
* @param {string} asset In example: BTC.BTC
* @returns {PoolDetail} Details of selected pool
* @throws {Error} Can't find pool for asset
*/
private async getPool(asset: string): Promise<PoolDetail> {
const pools = await this.midgardCache.getPools()
const pool = pools.find((pool) => pool.asset === asset)
Expand All @@ -34,6 +41,12 @@ export class MidgardQuery {
return pool
}

/**
* Get saver positions by array of saver descriptions
*
* @param {getSaver[]} params array of search conditions
* @returns {SaversPosition[]} Information on the positions found
*/
public async getSaverPositions(params: getSaver[]): Promise<SaversPosition[]> {
const addresses: Set<string> = new Set<string>()
params.forEach((param) => addresses.add(param.address))
Expand Down Expand Up @@ -72,6 +85,12 @@ export class MidgardQuery {
return saversPositions
}

/**
* Returns number of decimals by asset
*
* @param {Asset} asset asset for getting decimals
* @returns {number} Number of decimals from Midgard https://gitlab.com/thorchain/midgard#refresh-native-decimals
*/
public async getDecimalForAsset(asset: Asset): Promise<number> {
if (!isAssetRuneNative(asset)) {
const pool = await this.getPool(assetToString(asset))
Expand Down
3 changes: 3 additions & 0 deletions packages/xchain-midgard-query/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { Address, Asset, CryptoAmount } from '@xchainjs/xchain-util'

/**
* Search parameters to search for positions within the THORChain SAVER investment product trunks.
*/
export type getSaver = {
asset: Asset
address: Address
Expand Down
4 changes: 2 additions & 2 deletions packages/xchain-midgard-query/src/utils/midgard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export class Midgard {
const saverDetails = (await api.getSaverDetail(address)).data
return saverDetails
} catch (e) {
//console.error(e)
// console.error(e)
}
}
throw Error(`Midgard not responding`)
Expand All @@ -67,7 +67,7 @@ export class Midgard {
try {
return (await api.getPools()).data
} catch (e) {
//console.error(e)
// console.error(e)
}
}
throw new Error(`Midgard not responding`)
Expand Down
17 changes: 17 additions & 0 deletions packages/xchain-util/src/cached-value.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,37 @@
/* eslint-disable @typescript-eslint/no-explicit-any */

/**
* Utility class for caching stable data
*/
export class CachedValue<T> {
private cachedValue: T | undefined
private cacheTimestamp: Date | undefined
private cacheMaxAge: number
private refreshData: (params?: any) => Promise<T>
private refreshPromise: Promise<T> | null = null

/**
* @constructor
* @param refreshData function that refresh and return the data
* @param {number|undefined} cacheMaxAge time in millisecond to expire cache
*/
constructor(refreshData: (params?: any) => Promise<T>, cacheMaxAge?: number) {
this.cacheMaxAge = cacheMaxAge || Infinity
this.refreshData = refreshData
}

/**
* @private
* Validates if internal cache is valid or expired
*/
private isCacheValid() {
return Boolean(this.cacheTimestamp && new Date().getTime() - this.cacheTimestamp.getTime() < this.cacheMaxAge)
}

/**
* Returns cached data if valid or request fresh data if cache is invalid
* @param params use this params to request data if cache is expired
*/
async getValue(params?: any): Promise<T> {
if (this.isCacheValid()) {
return this.cachedValue as T
Expand Down
2 changes: 1 addition & 1 deletion packages/xchain-utxo-providers/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# XChainJS API UTXO providers Interface

A specification for a generalised interface for api providers, to be used by XChainJS implementations. The providers should not have any functionality to generate a key, instead, the `asgardex-crypto` library should be used to ensure cross-chain compatible keystores are handled. The providers is only ever passed a master BIP39 phrase, from which a temporary key and address is decoded.
A specification for a generalised interface for api providers, to be used by XChainJS implementations. The providers should not have any functionality to generate a key, instead, the `xchain-crypto` library should be used to ensure cross-chain compatible keystores are handled. The providers is only ever passed a master BIP39 phrase, from which a temporary key and address is decoded.

## Documentation

Expand Down

0 comments on commit 4860de1

Please sign in to comment.