From 9ba87488a0d1b1b672238e68f57327af9651493d Mon Sep 17 00:00:00 2001 From: ottebrut Date: Thu, 16 Jun 2022 16:51:42 +0300 Subject: [PATCH 01/13] Update readme --- README.md | 581 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 337 insertions(+), 244 deletions(-) diff --git a/README.md b/README.md index 1add3e4b5e..1380593820 100644 --- a/README.md +++ b/README.md @@ -17,79 +17,78 @@ - [Get started with tokens](#get-started-with-tokens) - [API](#api) - [Core](#core) - - [SDK.createSDK static method](#sdkcreatesdk-static-method) - - [sdk.updateConfiguration method](#sdkupdateconfiguration-method) - - [sdk.instantTrades readonly field](#sdkinstanttrades-readonly-field) - - [sdk.crossChain readonly field](#sdkcrosschain-readonly-field) - - [sdk.crossChainSymbiosisManger readonly field](#sdkcrosschainsymbiosismanager-readonly-field) - - [sdk.tokens readonly field](#sdktokens-readonly-field) - - [sdk.web3PublicService readonly field](#sdkweb3publicservice-readonly-field) - - [sdk.web3Private readonly field](#sdkweb3private-readonly-field) - - [sdk.gasPriceApi readonly field](#sdkgaspriceapi-readonly-field) - - [sdk.cryptoPriceApi readonly field](#sdkcryptopriceapi-readonly-field) + - [createSDK](#sdkcreatesdk-static-method) + - [updateConfiguration](#sdkupdateconfiguration-method) + - [instantTrades](#sdkinstanttrades-readonly-field) + - [crossChain](#sdkcrosschain-readonly-field) + - [crossChainSymbiosisManger](#sdkcrosschainsymbiosismanager-readonly-field) + - [tokens](#sdktokens-readonly-field) + - [web3PublicService](#sdkweb3publicservice-readonly-field) + - [web3Private](#sdkweb3private-readonly-field) + - [gasPriceApi](#sdkgaspriceapi-readonly-field) + - [cryptoPriceApi](#sdkcryptopriceapi-readonly-field) - [Instant Trades Manager](#instant-trades-manager) - - [sdk.instantTrades.calculateTrade method](#sdkinstanttradescalculatetrade-method) - - [sdk.instantTrades.blockchainTradeProviders readonly field](#sdkinstanttradesblockchaintradeproviders-readonly-field) + - [calculateTrade](#instanttradescalculatetrade-method) + - [blockchainTradeProviders](#instanttradesblockchaintradeproviders-readonly-field) - [Instant Trade](#instant-trade) - - [instantTrade.swap method](#instanttradeswap-method) - - [instantTrade.encode method](#instanttradeencode-method) - - [instantTrade.needApprove method](#instanttradeneedapprove-method) - - [instantTrade.type readonly field](#instanttradetype-readonly-field) - - [instantTrade.from readonly field](#instanttradefrom-readonly-field) - - [instantTrade.to readonly field](#instanttradeto-readonly-field) - - [instantTrade.gasFeeInfo mutable field](#instanttradegasfeeinfo-mutable-field) - - [instantTrade.slippageTolerance mutable field](#instanttradeslippagetolerance-mutable-field) - - [instantTrade.toTokenAmountMin getter](#instanttradetotokenamountmin-getter) - - [instantTrade.deadlineMinutes mutable field](#instanttradedeadlineminutes-mutable-field) - - [instantTrade.path readonly field](#instanttradepath-readonly-field) - - [isUniswapV2LikeTrade function](#isuniswapv2liketrade-function) - - [isUniswapV3LikeTrade function](#isuniswapv3liketrade-function) - - [isOneInchLikeTrade function](#isoneinchliketrade-function) - - [isZrxLikeTradeLikeTrade function](#iszrxliketradeliketrade-function) + - [swap](#instanttradeswap-method) + - [encode](#instanttradeencode-method) + - [needApprove](#instanttradeneedapprove-method) + - [type](#instanttradetype-readonly-field) + - [from](#instanttradefrom-readonly-field) + - [to](#instanttradeto-readonly-field) + - [gasFeeInfo](#instanttradegasfeeinfo-mutable-field) + - [slippageTolerance](#instanttradeslippagetolerance-mutable-field) + - [toTokenAmountMin](#instanttradetotokenamountmin-getter) + - [deadlineMinutes](#instanttradedeadlineminutes-mutable-field) + - [path](#instanttradepath-readonly-field) + - [isUniswapV2LikeTrade](#isuniswapv2liketrade-function) + - [isUniswapV3LikeTrade](#isuniswapv3liketrade-function) + - [isOneInchLikeTrade](#isoneinchliketrade-function) + - [isZrxLikeTradeLikeTrade](#iszrxliketradeliketrade-function) + - [isAlgebraTrade](#isalgebratrade-function) - [Cross Chain Manager](#cross-chain-manager) - - [sdk.crossChain.calculateTrade method](#sdkcrosschaincalculatetrade-method) + - [calculateTrade](#crosschaincalculatetrade-method) - [Wrapped Cross Chain Trade](#wrapped-cross-chain-trade) - [Cross Chain Trade](#cross-chain-trade) - - [crossChainTrade.swap method](#crosschaintradeswap-method) - - [crossChainTrade.needAapprove method](#crosschaintradeneedapprove-method) - - [crossChainTrade.approve method](#crosschaintradeapprove-method) - - [crossChainTrade.from readonly field](#crosschaintradefrom-readonly-field) - - [crossChainTrade.to readonly field](#crosschaintradeto-readonly-field) - - [crossChainTrade.toTokenAmountMin readonly field](#crosschaintradetotokenamountmin-readonly-field) - - [crossChainTrade.estimatedGas getter](#crosschaintradeestimatedgas-getter) - - [Celer Cross Chain Trade and Rubic Cross Chain Trade](#celer-cross-chain-trade-and-rubic-cross-chain-trade) - - [crossChainTrade.priceImpactData getter](#crosschaintradepriceimpactdata-getter) - - [Symbiosis Cross Chain Trade](#symbiosis-cross-chain-trade) - - [crossChainTrade.priceImpact readonly field](#crosschaintradepriceimpact-readonly-field) + - [swap](#crosschaintradeswap-method) + - [needApprove](#crosschaintradeneedapprove-method) + - [approve](#crosschaintradeapprove-method) + - [from](#crosschaintradefrom-readonly-field) + - [to](#crosschaintradeto-readonly-field) + - [toTokenAmountMin](#crosschaintradetotokenamountmin-readonly-field) + - [estimatedGas](#crosschaintradeestimatedgas-getter) + - [priceImpactData](#crosschaintradepriceimpactdata-getter) + - [priceImpact readonly](#crosschaintradepriceimpact-readonly-field) - [Cross Chain Symbiosis Manager](#cross-chain-symbiosis-manager) - - [crossChainTrade.getUserTrades method](#crosschainsymbiosismanagergetusertrades-method) - - [crossChainTrade.revertTrade method](#crosschainsymbiosismanagerreverttrade-method) + - [getUserTrades](#crosschainsymbiosismanagergetusertrades-method) + - [revertTrade](#crosschainsymbiosismanagerreverttrade-method) - [Tokens](#tokens-manager) - [Tokens Manager](#tokens-manager) - - [tokensManager.createTokenFromStruct method](#tokensmanagercreatetokenfromstruct-method) - - [tokensManager.createToken method](#tokensmanagercreatetoken-method) - - [tokensManager.createTokensFromStructs method](#tokensmanagercreatetokensfromstructs-method) - - [tokensManager.createTokens method](#tokensmanagercreatetokens-method) - - [tokensManager.createPriceTokenFromStruct method](#tokensmanagercreatepricetokenfromstruct-method) - - [tokensManager.createPriceToken method](#tokensmanagercreatepricetoken-method) - - [tokensManager.createPriceTokenAmountFromStruct method](#tokensmanagercreatepricetokenamountfromstruct-method) - - [tokensManager.createPriceTokenAmount method](#tokensmanagercreatepricetokenamount-method) + - [createTokenFromStruct](#tokensmanagercreatetokenfromstruct-method) + - [createToken](#tokensmanagercreatetoken-method) + - [createTokensFromStructs](#tokensmanagercreatetokensfromstructs-method) + - [createTokens](#tokensmanagercreatetokens-method) + - [createPriceTokenFromStruct](#tokensmanagercreatepricetokenfromstruct-method) + - [createPriceToken](#tokensmanagercreatepricetoken-method) + - [createPriceTokenAmountFromStruct](#tokensmanagercreatepricetokenamountfromstruct-method) + - [createPriceTokenAmount](#tokensmanagercreatepricetokenamount-method) - [Token](#token) - [token fields](#token-fields) - - [token.isNative method](#tokenisnative-method) - - [token.isEqualTo method](#tokenisequalto-method) - - [token.clone method](#tokenclone-method) + - [isNative](#tokenisnative-getter) + - [isEqualTo](#tokenisequalto-method) + - [clone](#tokenclone-method) - [PriceToken](#pricetoken) - - [priceToken.asStruct getter](#pricetokenasstruct-getter) - - [priceToken.getAndUpdateTokenPrice method](#pricetokengetandupdatetokenprice-method) - - [priceToken.cloneAndCreate](#pricetokencloneandcreate) + - [asStruct](#pricetokenasstruct-getter) + - [getAndUpdateTokenPrice](#pricetokengetandupdatetokenprice-method) + - [cloneAndCreate](#pricetokencloneandcreate) - [PriceTokenAmount](#pricetokenamount) - - [priceTokenAmount.weiAmount getter](#pricetokenamountweiamount-getter) - - [priceTokenAmount.stringWeiAmount getter](#pricetokenamountstringweiamount-getter) - - [priceTokenAmount.tokenAmount getter](#pricetokenamounttokenamount-getter) - - [priceTokenAmount.weiAmountMinusSlippage method](#pricetokenamountweiamountminusslippage-method) - - [priceTokenAmount.weiAmountPlusSlippage method](#pricetokenamountweiamountplusslippage-method) - - [priceTokenAmount.calculatePriceImpactPercent method](#pricetokenamountcalculatepriceimpactpercent-method) + - [weiAmount](#pricetokenamountweiamount-getter) + - [stringWeiAmount](#pricetokenamountstringweiamount-getter) + - [tokenAmount](#pricetokenamounttokenamount-getter) + - [weiAmountMinusSlippage](#pricetokenamountweiamountminusslippage-method) + - [weiAmountPlusSlippage](#pricetokenamountweiamountplusslippage-method) + - [calculatePriceImpactPercent](#pricetokenamountcalculatepriceimpactpercent-method) ## Description In dApps a lot of business logic is often concentrated on the frontend for interacting with the blockchain. This SDK is built on the basis of [Rubic](https://github.com/Cryptorubic/rubic-app) multichain DeFi frontend part. SDK is a library for interacting with various dexes, as well as Rubic cross-chain swaps. It also includes a number of utilities useful when working with Ethereum. @@ -411,18 +410,19 @@ console.log(token.stringWeiAmount); // 1000000 ## API -### Core +## Core + +### SDK.createSDK static method -#### SDK.createSDK static method ```typescript SDK.createSDK(configuration: Configuration): Promise ``` Creates new sdk instance. Changes dependencies of all sdk entities according to new configuration (even for entities created with other previous sdk instances). -| Parameter | Type | Description | -|---------------|---------------|------------------------------------------------------------------------------------| -| configuration | Configuration | Object contains main sdk settings like .env: rpc providers links, wallet object... | +| Parameter | Type | Description | +|---------------|---------------|---------------------------------------------------------------------------------------| +| configuration | Configuration | Object contains main sdk settings like .env: rpc providers links, wallet object, etc. | Configuration structure ```typescript @@ -448,11 +448,11 @@ interface WalletProvider { **Configuration description:** -| Property | Type | Description | Default | -|-----------------|-------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------| -| rpcProviders | `Partial>` | Rpc data to connect to blockchains you will use. You have to pass rpcProvider for each blockchain you will use with sdk. | Not set. | -| walletProvider? | `WalletProvider` | Required to use `swap`, `approve` and other methods which sends transactions. But you can calculate and encode trades without `walletProvider`. Pass it when user connects wallet. Please note that address and chainId must match account address and selected chainId in the user wallet. | Not set. | -| httpClient? | `HttpClient` | You can pass you own httpClient (e.g. HttpClient in Angular) if you have it to not duplicate http clients and decrease bundle size. Please note that default axios or native js fetch clients can't be used as `HttpClient` without modifications. Your http client must return promise which will resolve with parsed response body (like Angular httpClient). See interface below. | Lazy loading axios with interceptor. | +| Property | Type | Description | Default | +|-----------------|-------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------| +| rpcProviders | `Partial>` | Rpc data to connect to blockchains you will use. You have to pass rpcProvider for each blockchain you will use with sdk. | Not set. | +| walletProvider? | `WalletProvider` | Required to use `swap`, `approve` and other methods which sends transactions. But you can calculate and encode trades without `walletProvider`. Pass it when user connects wallet. Please note that `address` and `chainId` must match account address and selected chain id in a user's wallet. | Not set. | +| httpClient? | `HttpClient` | You can pass your own http client (e.g. HttpClient in Angular) if you have it, to not duplicate http clients and decrease bundle size. Please note that default axios or native js fetch clients can't be used as `HttpClient` without modifications. Your http client must return promise which will resolve with parsed response body (like Angular HttpClient). See interface below. | Lazy loading axios with interceptor. | **HttpClient interface:** @@ -481,24 +481,24 @@ interface HttpClient { | Property | Type | Description | Default | |---------------------|----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------| -| mainRpc | `string` | Rpc link. Copy it from your rpc provider (like Infura, Quicknode, Getblock, Moralis, ...) website. | Not set. | +| mainRpc | `string` | Rpc link. Copy it from your rpc provider (like Infura, Quicknode, Getblock, Moralis, etc.) website. | Not set. | | spareRpc? | `string` | Same as `mainRpc`. Will be used instead `mainRpc` if mainRpc is out of timeout = `mainPrcTimeout`. | Not set. | | mainPrcTimeout? | number | Specifies timeout **in ms** after that `mainRpc` will be replaced with `spareRpc` (if `spareRpc` is defined) | 10_000 | | healthCheckTimeout? | number | Before the `mainRpc` link is applied to the sdk, all the `mainRpc` links will be checked for operability by receiving from the blockchain and verifying the predefined data. If an error occurs during the request, the received data does not match the specified one, or the timeout is exceeded, the `mainRpc` will be replaced with a spare one. This `healthCheckTimeout` parameter allows you to set the maximum allowable timeout when checking the `mainRpc`. | 4_000 | --- -#### sdk.updateConfiguration method +### sdk.updateConfiguration method ```typescript sdk.updateConfiguration(configuration: Configuration): Promise ``` -Updates sdk configuration and sdk entities dependencies. Call it if user connects wallet, or user changes network or account in him wallet. +Updates sdk configuration and sdk entities dependencies. Call it if user connects wallet or changes network or account in their wallet. --- -#### sdk.instantTrades readonly field +### sdk.instantTrades readonly field ```typescript sdk.instantTrades: InstantTradesManager @@ -508,7 +508,7 @@ Instant trades manager object. Use it to calculate and create instant trades. [S --- -#### sdk.crossChain readonly field +### sdk.crossChain readonly field ```typescript sdk.crossChain: CrossChainManager @@ -518,45 +518,46 @@ Cross-chain trades manager object. Use it to calculate and create cross-chain tr --- -#### sdk.crossChainSymbiosisManager readonly field +### sdk.crossChainSymbiosisManager readonly field ```typescript sdk.crossChainSymbiosisManager: CrossChainSymbiosisManager ``` -Cross-chain symbiosis manager object. Use it to get pending trades and symbiosis and revert them. [See more.](#cross-chain-symbiosis-manager) +Cross-chain symbiosis manager object. Use it to get pending trades in symbiosis and revert them. [See more.](#cross-chain-symbiosis-manager) --- -#### sdk.tokens readonly field +### sdk.tokens readonly field ```typescript sdk.tokens: TokensManager ``` -Tokens manager object. Use it to fetch tokens data, to create new `Token`, `PriceToken`, `PriceTokenAmount` objects. [See more.](#tokens) +Tokens manager object. Use it to fetch tokens data, to create new `Token`, `PriceToken`, `PriceTokenAmount` objects. [See more.](#tokens-manager) --- -#### sdk.web3PublicService readonly field +### sdk.web3PublicService readonly field ```typescript sdk.web3PublicService: Web3PublicService ``` -Use it to get `Web3Public` instance by blockchain name to get read information from blockchain. +Use it to get `Web3Public` instance by blockchain name to get public information from blockchain. ```typescript const web3Public = sdk.web3PublicService.getWeb3Public(BLOCKCHAIN_NAME.ETHEREUM); const ethBalance = await web3Public.getBalance(''); const tokenBalance = await web3Public.getBalance('', ''); +... ``` Explore Web3Public class to see available methods. --- -#### sdk.web3Private readonly field +### sdk.web3Private readonly field ```typescript sdk.web3Private: Web3Private @@ -567,13 +568,14 @@ Use it to send transactions and execute smart contracts methods. ```typescript const web3Private = sdk.web3Private; const transacionReceipt = await web3Private.transferTokens('', ',toAddress>', 1000); +... ``` Explore Web3Private class to see available methods. --- -#### sdk.gasPriceApi readonly field +### sdk.gasPriceApi readonly field ```typescript sdk.gasPriceApi: GasPriceApi @@ -584,13 +586,14 @@ Use it to get gas price information. ```typescript const gasPriceApi = sdk.gasPriceApi; const gasPrice = await gasPriceApi.getGasPrice(BLOCKCHAIN_NAME.ETHEREUM); +... ``` Explore GasPriceApi class to see available methods. --- -#### sdk.cryptoPriceApi readonly field +### sdk.cryptoPriceApi readonly field ```typescript sdk.cryptoPriceApi: CoingeckoApi @@ -601,15 +604,16 @@ Use it to get crypto price information. ```typescript const cryptoPriceApi = sdk.cryptoPriceApi; const tokenUSDPrice = await cryptoPriceApi.getErc20TokenPrice('', ''); +... ``` Explore CoingeckoApi class to see available methods. --- -### Instant Trades Manager +## Instant Trades Manager -#### sdk.instantTrades.calculateTrade method +### instantTrades.calculateTrade method ```typescript sdk.instantTrades.calculateTrade( @@ -629,38 +633,37 @@ sdk.instantTrades.calculateTrade( Method calculates instant trades parameters and estimated output amount. -**sdk.instantTrades.calculateTrade method parameters:** +**Method parameters:** -| Parameter | Type | Description | -|------------|--------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------| -| fromToken | `Token` | `{ address: string; blockchain: BLOCKCHAIN_NAME;}` | Token sell. | -| fromAmount | `string` | `number` | Amount in token units (**not in wei!**) to swap. | -| toToken | `Token` | `string` | Token to get. You can pass Token object, or string token address. Must has same blockchain as fromToken if passed as Token. | -| options? | `SwapManagerCalculationOptions` | Swap calculation options. | +| Parameter | Type | Description | +|------------|--------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------| +| fromToken | `Token` | `{ address: string; blockchain: BLOCKCHAIN_NAME;}` | Token to sell. | +| fromAmount | `string` | `number` | Amount in token units (**not in wei**) to swap. | +| toToken | `Token` | `string` | Token to get. You can pass Token object, or string token address. It must have same blockchain as `fromToken` if passed as Token. | +| options? | `SwapManagerCalculationOptions` | Swap calculation options. | **SwapManagerCalculationOptions description:** -| Option | Type | Description | Default | -|--------------------|----------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------| -| timeout? | `number` | Specify trade calculation timeout in ms (same timeout for every provider separately). | 3000 | -| disabledProviders? | `TradeType[]` | Specify providers which must be ignored. | [] | -| gasCalculation? | `'disabled'` | `'calculate'` | `'rubicOptimisation'` | Disable estimated gas calculation, or use rubic gas optimisation to consider the gas fee when calculating route profit (works only for UniswapV2-like and UniswapV3-like providers.). | 'calculate' | -| disableMultihops? | `boolean` | Disable not direct swap routes. It can help to reduce gas fee, but can worsen the exchange rate. Better use `gasCalculation = 'rubicOptimisation'` when it is possible. | false | -| slippageTolerance? | `number` | Swap slippage in range 0 to 1. Defines minimum amount that you can get after swap. Can be changed after trade calculation for every trade separately (excluding 0x trade). | 0.02 | +| Option | Type | Description | Default | +|--------------------|----------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------| +| timeout? | `number` | Specify trade calculation timeout in ms (same timeout for every provider separately). | 3000 | +| disabledProviders? | `TradeType[]` | Specify providers which must be ignored. | [] | +| gasCalculation? | `'disabled'` | `'calculate'` | `'rubicOptimisation'` | Disable estimated gas calculation, or use rubic gas optimisation to consider the gas fee when calculating route profit (works only for UniswapV2-like and UniswapV3-like providers.). | 'calculate' | +| disableMultihops? | `boolean` | Disable indirect swap routes. It can help to reduce gas fee, but can worsen the exchange rate. Better use `gasCalculation = 'rubicOptimisation'` when it is possible. | false | +| slippageTolerance? | `number` | Swap slippage in range 0 to 1. Defines minimum amount that you can get after swap. Can be changed after trade calculation for every trade separately (excluding 0x trade). | 0.02 | | deadlineMinutes? | `number` | Transaction deadline in minutes (countdown from the transaction sending date). Will be applied only for UniswapV2-like and UniswapV3-like trades. Can be changed after trade calculation for every trade separately. | 20 | **Returns** `Promise` -- list of successful calculated trades. --- -#### sdk.instantTrades.blockchainTradeProviders readonly field +### instantTrades.blockchainTradeProviders readonly field ```typescript readonly sdk.instantTrades.blockchainTradeProviders: Readonly> ``` -If you need to calculate trade with the special provider options, you can get needed provider instance in `sdk.instantTrades.blockchainTradeProviders` -and calculate trade directly via this instance. +If you need to calculate trade with the special provider options, you can get needed provider instance and calculate trade directly via this instance. ```typescript // calculate trade with exact output @@ -670,9 +673,9 @@ const trade = await sdk.instantTrades.blockchainTradeProviders[BLOCKCHAIN_NAME.E --- -### Instant Trade +## Instant Trade -#### instantTrade.swap method +### instantTrade.swap method ```typescript instantTrade.swap(options?: SwapTransactionOptions): Promise @@ -680,11 +683,11 @@ instantTrade.swap(options?: SwapTransactionOptions): Promise > ℹī¸ī¸ You have to set up **wallet provider 👛** for network in which you will execute trade swap. -Method checks balance, network id correctness, and executes swap transaction. -A transaction confirmation window will open in the connected user's wallet. +Method checks balance, network id correctness and executes swap transaction. +A transaction confirmation window will be opened in the connected user's wallet. If user has not enough allowance, the method will automatically send approve transaction before swap transaction. -**instantTrade.swap method parameters:** +**Method parameters:** | Parameter | Type | Description | |-----------|--------------------------|--------------------------------------| @@ -703,7 +706,7 @@ If user has not enough allowance, the method will automatically send approve tra --- -#### instantTrade.encode method +### instantTrade.encode method ```typescript instantTrade.encode(options?: EncodeTransactionOptions): Promise @@ -711,10 +714,10 @@ instantTrade.encode(options?: EncodeTransactionOptions): Promise ℹī¸ī¸ You have to set up **rpc provider 🌐** for trade network for which you will call encode. -If you don't want to execute transaction instantly (e.g. if you use SDK in the server-side), you can get full transaction data -to pass it to the transaction when you need to send it, you can use `instantTrade.encode` method. +If you don't want to execute transaction instantly (e.g. if you use SDK on server-side), you can get full transaction data +to pass it to the transaction when you need to send it. -**instantTrade.encode method parameters:** +**Method parameters:** | Parameter | Type | Description | |-----------|----------------------------|------------------------------------------------------------------------------------------------------------------| @@ -722,17 +725,17 @@ to pass it to the transaction when you need to send it, you can use `instantTrad **EncodeTransactionOptions description:** -| Option | Type | Description | Default | -|-------------|----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------| -| fromAddress | `string` | Not needed for uniswapV3-like and 0x trades, but required for uniswapV2-like and 1inch trades. Address of account which will executes swap transaction by encoded data. This address must has enough allowance to successfully encode. | Not set. | -| gasPrice? | `string` | Specifies gas price **in wei** for **swap and approve** transactions. Set this parameter only if you know exactly what you are doing. | The value obtained during the calculation of the trade. If value wasn't calculated, it will calculates automatically by user's wallet. | -| gasLimit? | `string` | Specifies gas limit for **swap and approve** transactions. Set this parameter only if you know exactly what you are doing. | The value obtained during the calculation of the trade. If value wasn't calculated, it will calculates automatically by user's wallet. | +| Option | Type | Description | Default | +|-------------|----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------| +| fromAddress | `string` | Not needed for uniswapV3-like and 0x trades, but required for uniswapV2-like and 1inch trades. Address of account which will execute swap transaction by encoded data. This address must has enough allowance to successfully encode. | Not set. | +| gasPrice? | `string` | Specifies gas price **in wei** for **swap and approve** transactions. Set this parameter only if you know exactly what you are doing. | The value obtained during the calculation of the trade. If value wasn't calculated, it will calculates automatically by user's wallet. | +| gasLimit? | `string` | Specifies gas limit for **swap and approve** transactions. Set this parameter only if you know exactly what you are doing. | The value obtained during the calculation of the trade. If value wasn't calculated, it will calculates automatically by user's wallet. | **Returns** `Promise` -- web3 transaction structure to send. --- -#### instantTrade.needApprove method +### instantTrade.needApprove method ```typescript instantTrade.needApprove(): Promise @@ -742,13 +745,13 @@ instantTrade.needApprove(): Promise > ℹī¸ī¸ You have to set up **rpc provider 🌐** for trade network for which you will call needApprove. Swap method will automatically call approve if needed, but you can use methods pair `needApprove`-`approve` -if you want to know if approve is needed before execute swap to show user double button, or swap stages in UI. +if you want to know if approve is needed before executing swap. -**instantTrade.needApprove Returns** `Promise` -- True if approve required, that is user has not enough allowance. Otherwise false. +**Returns** `Promise` -- `true` if approve required, that is user has not enough allowance. Otherwise, `false`. --- -#### instantTrade.approve method +### instantTrade.approve method ```typescript instantTrade.approve(options?: BasicTransactionOptions): Promise @@ -756,9 +759,9 @@ instantTrade.approve(options?: BasicTransactionOptions): Promise ℹī¸ī¸ You have to set up **wallet provider 👛** for network in which you will execute trade swap. -Use `approve` if you want to show swap stages in UI after allowance check via `needApprove` method. +Sends transaction to approve tokens for user. -**instantTrade.approve method parameters:** +**Method parameters:** | Parameter | Type | Description | |-----------|---------------------------|---------------------------------| @@ -776,17 +779,17 @@ Use `approve` if you want to show swap stages in UI after allowance check via `n --- -#### instantTrade.type readonly field +### instantTrade.type readonly field ```typescript readonly instantTrade.type: TradeType ``` -Instant trade type (like `TRADE_TYPE.UNISWAP_V2`, `TRADE_TYPE.QUICK_SWAP`, ...). +Instant trade type (like `TRADE_TYPE.UNISWAP_V2`, `TRADE_TYPE.QUICK_SWAP`, etc.). Check `TRADE_TYPE` interface to see all providers. --- -#### instantTrade.from readonly field +### instantTrade.from readonly field ```typescript readonly instantTrade.from: PriceTokenAmount @@ -796,7 +799,7 @@ Token to sell with price in USD per 1 token unit and selling amount. --- -#### instantTrade.to readonly field +### instantTrade.to readonly field ```typescript readonly instantTrade.to: PriceTokenAmount @@ -806,7 +809,17 @@ Token to buy with price in USD per 1 token unit and estimated get amount (not to --- -#### instantTrade.gasFeeInfo mutable field +### instantTrade.toTokenAmountMin getter + +```typescript +instantTrade.toTokenAmountMin: PriceTokenAmount +``` + +Minimum amount of tokens that user can get. Is same as `instantTrade.to`, but amount less than `instantTrade.to` by `(instantTrade.slippageTolerance * 100)` percent. + +--- + +### instantTrade.gasFeeInfo mutable field ```typescript instantTrade.gasFeeInfo: GasFeeInfo | null @@ -829,7 +842,7 @@ Can be changed: just modify gasFeeInfo field. --- -#### instantTrade.slippageTolerance mutable field +### instantTrade.slippageTolerance mutable field ```typescript instantTrade.slippageTolerance: number @@ -839,18 +852,7 @@ Swap slippage in range 0 to 1. Defines minimum amount that you can get after swa --- -#### instantTrade.toTokenAmountMin getter - -```typescript -instantTrade.toTokenAmountMin: PriceTokenAmount -``` - -Is same as `instantTrade.to`, but amount less than `instantTrade.to` by `(instantTrade.slippageTolerance * 100)` percent. - - ---- - -#### instantTrade.deadlineMinutes mutable field +### instantTrade.deadlineMinutes mutable field ```typescript instantTrade.deadlineMinutes: number @@ -862,7 +864,7 @@ Transaction deadline in minutes (countdown from the transaction sending date). C --- -#### instantTrade.path readonly field +### instantTrade.path readonly field ```typescript instantTrade.path: ReadonlyArray @@ -872,11 +874,12 @@ instantTrade.path: ReadonlyArray Swap path. E.g. if you change ETH to LINK path might be [ETH, USDT, LINK]. Path elements is `Token`, so you can get address, symbol and other properties of each element. -If you sell, or get native coin (like ETH, BNB, MATIC, ...) in swap, `path[0]` or `path[path.length -1]` **won't** be wrapped tokens like WETH, but will be native tokens. +If you sell, or get native coin (like ETH, BNB, MATIC, etc.) in swap, `path[0]` or `path[path.length -1]` **won't** be wrapped tokens like WETH, but will be native tokens. --- -#### isUniswapV2LikeTrade function +### isUniswapV2LikeTrade function + ```typescript function isUniswapV2LikeTrade(trade: InstantTrade): trade is UniswapV2AbstractTrade ``` @@ -903,7 +906,8 @@ List of uniswapV2LikeTrades/Providers: --- -#### isUniswapV3LikeTrade function +### isUniswapV3LikeTrade function + ```typescript function isUniswapV3LikeTrade(trade: InstantTrade): trade is UniSwapV3Trade ``` @@ -911,46 +915,62 @@ function isUniswapV3LikeTrade(trade: InstantTrade): trade is UniSwapV3Trade Type guard checks that trade is UniSwapV3Trade. Use it to parse result of `sdk.instantTrades.calculateTrade` and show specific UniSwapV3 trade data, or use its specific methods. -List of uniswapV2LikeTrades/Providers: -- UniSwapV3 -- (Algebra and UniSwapV3 Polygon soon!) +List of uniswapV3LikeTrades/Providers: +- UniSwapV3 Ethereum +- UniSwapV3 Polygon +- UniSwapV3 Arbitrum --- -#### isOneInchLikeTrade function +### isOneInchLikeTrade function + ```typescript function isOneInchLikeTrade(trade: InstantTrade): trade is OneinchTrade ``` Type guard checks that trade is OneinchTrade. Use it to parse result of `sdk.instantTrades.calculateTrade` and -show specific OneinchTrade trade data, or use its specific methods. +show specific Oneinch trade data, or use its specific methods. List of OneinchTrade/Providers: - OneInch Ethereum - OneInch Bsc - OneInch Polygon +- OneInch Avalanche +- OneInch Arbitrum --- -#### isZrxLikeTradeLikeTrade function +### isZrxLikeTradeLikeTrade function + ```typescript function isZrxLikeTradeLikeTrade(trade: InstantTrade): trade is ZrxTrade ``` Type guard checks that trade is 0x Trade. Use it to parse result of `sdk.instantTrades.calculateTrade` and -show specific 0x Trade trade data, or use its specific methods. +show specific 0x trade data, or use its specific methods. -List of OneinchTrade/Providers: +List of ZrxTrade/Providers: - 0x Ethereum -- (other blockchains for 0x soon!) --- -### Cross Chain Manager +### isAlgebraTrade function + +```typescript +function isAlgebraTrade(trade: InstantTrade): trade is AlgebraTrade +``` + +Type guard checks that trade is Algebra Trade. Use it to parse result of `sdk.instantTrades.calculateTrade` and +show specific Algebra trade data, or use its specific methods. + +List of AlgebraTrade/Providers: +- Algebra -> ⚠ī¸ **Danger:** Currently, Cross Chain Manager uses dev-mode contracts. Its' logic is the same as of prod-mode contracts, but settings (such as minimum amount of tokens to sell) are different. +--- + +## Cross Chain Manager -#### sdk.crossChain.calculateTrade method +### crossChain.calculateTrade method ```typescript sdk.crossChain.calculateTrade( @@ -973,32 +993,32 @@ sdk.crossChain.calculateTrade( > ℹī¸ī¸ You have to set up **rpc provider 🌐** for network in which you will calculate trade. -Method calculates [WrappedCrossChainTrade](#wrapped-cross-chain-trade). +Method calculates [WrappedCrossChainTrade](#wrapped-cross-chain-trade), which contains best cross chain provider with estimated output amount. -**sdk.crossChain.calculateTrade method parameters:** +**Method parameters:** -| Parameter | Type | Description | -|------------|--------------------------------------------------------------------|--------------------------------------------------| -| fromToken | `Token` | `{ address: string; blockchain: BLOCKCHAIN_NAME;}` | Token to sell. | -| fromAmount | `string` | `number` | Amount in token units (**not in wei!**) to swap. | -| toToken | `Token` | `{ address: string; blockchain: BLOCKCHAIN_NAME;}` | Token to get. | -| options? | `CrossChainOptions` | Swap calculation options. | +| Parameter | Type | Description | +|------------|--------------------------------------------------------------------|-------------------------------------------------| +| fromToken | `Token` | `{ address: string; blockchain: BLOCKCHAIN_NAME;}` | Token to sell. | +| fromAmount | `string` | `number` | Amount in token units (**not in wei**) to swap. | +| toToken | `Token` | `{ address: string; blockchain: BLOCKCHAIN_NAME;}` | Token to get. | +| options? | `CrossChainOptions` | Swap calculation options. | **CrossChainOptions description:** -| Option | Type | Description | Default | -|-----------------------|---------------------------------|-----------------------------------------------------------------------------------------------------------------------------------|--------------------------| -| fromSlippageTolerance | `number` | Swap slippage in range 0 to 1. Defines minimum amount after swap in **first blockchain** (for Celer and Rubic). | 0.02 | -| toSlippageTolerance | `number` | Swap slippage in range 0 to 1. Defines minimum amount that you can get after swap in **second blockchain** (for Celer and Rubic). | 0.02 | -| slippageTolerance | `number` | Swap slippage in range 0 to 1. Defines minimum amount that you can get after swap (for Symbiosis). | 0.04 | -| fromAddress | `string` | User wallet address to calculate trade for (for Symbiosis). | Connected wallet address | -| deadline | `number` | Deadline of the trade in minutes (for Symbiosis). | 20 | -| gasCalculation | `'enabled'` | `'disabled'` | Disables or enables gas limit and gas price calclation. | 'enabled' | -| disabledProviders | `CrossChainTradeType[]` | Disables passed providers. | [] | +| Option | Type | Description | Default | +|-----------------------|---------------------------------|-----------------------------------------------------------------------------------------------------------------------------------|---------------------------| +| fromSlippageTolerance | `number` | Swap slippage in range 0 to 1. Defines minimum amount after swap in **first blockchain** (for Celer and Rubic). | 0.02 | +| toSlippageTolerance | `number` | Swap slippage in range 0 to 1. Defines minimum amount that you can get after swap in **second blockchain** (for Celer and Rubic). | 0.02 | +| slippageTolerance | `number` | Swap slippage in range 0 to 1. Defines minimum amount that you can get after swap (for Symbiosis). | 0.04 | +| fromAddress | `string` | User wallet address to calculate trade for (for Symbiosis). | Connected wallet address. | +| deadline | `number` | Deadline of the trade in minutes (for Symbiosis). | 20 | +| gasCalculation | `'enabled'` | `'disabled'` | Disables or enables calculation of gas limit and gas price. | 'enabled' | +| disabledProviders | `CrossChainTradeType[]` | Disables passed providers. | [] | --- -### Wrapped Cross Chain Trade +## Wrapped Cross Chain Trade ```typescript interface WrappedCrossChainTrade { @@ -1008,16 +1028,16 @@ interface WrappedCrossChainTrade { } ``` -Wraps cross chain trade and possible min max amount errors. If `minAmountError` or `maxAmountError` are not empty, then you must display an error, because [`swap`](#crosschaintradeswap-method) method will return error. +Wraps best calculated cross chain trade and possible min max amount errors. If `minAmountError` or `maxAmountError` are not undefined, then you must display an error, because [`swap`](#crosschaintradeswap-method) method will return error. --- -### Cross Chain Trade +## Cross Chain Trade -Stores information about trade and provides method to make swap. -Extends to types: `CelerCrossChainTrade`, `RubicCrossChainTrade`, `SymbiosisCrossChainTrade`. +Stores information about trade and provides method to make swap or encode. +Extends to classes: `CelerCrossChainTrade`, `RubicCrossChainTrade`, `SymbiosisCrossChainTrade`. -#### crossChainTrade.swap method +### crossChainTrade.swap method ```typescript crossChainTrade.swap(options?: SwapTransactionOptions): Promise @@ -1029,7 +1049,7 @@ Method checks balance, network id correctness, cross-chain contracts state and e A transaction confirmation window will open in the connected user's wallet. If user has not enough allowance, the method will automatically send approve transaction before swap transaction. -**crossChainTrade.swap method parameters:** +**Method parameters:** | Parameter | Type | Description | |-----------|--------------------------|--------------------------------------| @@ -1048,23 +1068,51 @@ If user has not enough allowance, the method will automatically send approve tra --- -#### crossChainTrade.needApprove method +### crossChainTrade.encode method ```typescript -crossChainTrade.needApprove(): Promise +crossChainTrade.encode(options?: EncodeTransactionOptions): Promise ``` +> ℹī¸ī¸ You have to set up **rpc provider 🌐** for trade network for which you will call encode. + +If you don't want to execute transaction instantly (e.g. if you use SDK on server-side), you can get full transaction data +to pass it to the transaction when you need to send it. + +**Method parameters:** + +| Parameter | Type | Description | +|-----------|----------------------------|------------------------------------------------------------------------------------------------------------------| +| options | `EncodeTransactionOptions` | Additional options. Optional for uniswapV3-like and 0x trades, but required for uniswapV2-like and 1inch trades. | + +**EncodeTransactionOptions description:** + +| Option | Type | Description | Default | +|-------------|----------|----------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------| +| fromAddress | `string` | Address of account which will execute swap transaction by encoded data. This address must has enough allowance to successfully encode. | Not set. | +| gasPrice? | `string` | Specifies gas price **in wei** for **swap and approve** transactions. Set this parameter only if you know exactly what you are doing. | The value obtained during the calculation of the trade. If value wasn't calculated, it will calculates automatically by user's wallet. | +| gasLimit? | `string` | Specifies gas limit for **swap and approve** transactions. Set this parameter only if you know exactly what you are doing. | The value obtained during the calculation of the trade. If value wasn't calculated, it will calculates automatically by user's wallet. | + +**Returns** `Promise` -- web3 transaction structure to send. + +--- + +### crossChainTrade.needApprove method + +```typescript +crossChainTrade.needApprove(): Promise +``` > ℹī¸ī¸ You have to set up **rpc provider 🌐** for trade network for which you will call needApprove. Swap method will automatically call approve if needed, but you can use methods pair `needApprove`-`approve` -if you want to know if approve is needed before execute swap to show user double button, or swap stages in UI. +if you want to know if approve is needed before execute swap. -**crossChainTrade.needApprove Returns** `Promise` -- True if approve is required, that is user doesn't have enough allowance. Otherwise, false. +**Returns** `Promise` -- `true` if approve is required, that is user doesn't have enough allowance. Otherwise, `false`. --- -#### crossChainTrade.approve method +### crossChainTrade.approve method ```typescript crossChainTrade.approve(options?: BasicTransactionOptions): Promise @@ -1072,7 +1120,7 @@ crossChainTrade.approve(options?: BasicTransactionOptions): Promise ℹī¸ī¸ You have to set up **wallet provider 👛** for network in which you will execute trade swap. -Use `approve` if you want to show swap stages in UI after allowance check via `needApprove` method. +Sends transaction to approve tokens for user. **crossChainTrade.approve method parameters:** @@ -1092,7 +1140,7 @@ Use `approve` if you want to show swap stages in UI after allowance check via `n --- -#### crossChainTrade.from readonly field +### crossChainTrade.from readonly field ```typescript readonly crossChainTrade.from: PriceTokenAmount @@ -1102,27 +1150,27 @@ Token to sell with price in USD per 1 token unit and selling amount. --- -#### crossChainTrade.to readonly field +### crossChainTrade.to readonly field ```typescript readonly crossChainTrade.to: PriceTokenAmount ``` -Token to buy with price in USD per 1 token unit and estimated output amount. +Token to buy with price in USD per 1 token unit and estimated output amount (not to be confused with `crossChainTrade.toTokenAmountMin`). --- -#### crossChainTrade.toTokenAmountMin readonly field +### crossChainTrade.toTokenAmountMin readonly field ```typescript readonly crossChainTrade.to: PriceTokenAmount ``` -Is same as `crossChainTrade.to`, but amount less than `crossChainTrade.to` by `(toSlippageTolerance * 100)` percent. +Minimum amount of tokens that user can get. Is same as `crossChainTrade.to`, but amount less than `crossChainTrade.to` by `(toSlippageTolerance * 100)` percent. --- -#### crossChainTrade.estimatedGas getter +### crossChainTrade.estimatedGas getter ```typescript crossChainTrade.estimateGas(): GasFeeInfo | null @@ -1132,11 +1180,9 @@ Gets gasFee, that is gasLimit * gasPrice. Equals `null` if gas couldn't be calcu --- -### Celer Cross Chain Trade and Rubic Cross Chain Trade +### crossChainTrade.priceImpactData getter -Extend `CrossChainTrade` class. - -#### crossChainTrade.priceImpactData getter +> ⚠ī¸ Is available only in Celer and Rubic trades. ```typescript crossChainTrade.priceImpactData(): { @@ -1149,11 +1195,9 @@ Returns price impact in first and second blockchains, based on tokens usd prices --- -### Symbiosis Cross Chain Trade - -Extends `CrossChainTrade` class. +### crossChainTrade.priceImpact readonly field -#### crossChainTrade.priceImpact readonly field +> ⚠ī¸ Is available only in Symbiosis trade. ```typescript crossChainTrade.priceImpact: number @@ -1163,30 +1207,30 @@ Returns overall price impact, based on symbiosis api. --- -### Cross Chain Symbiosis Manager +## Cross Chain Symbiosis Manager -Contains methods to work with pending user trades and revert them. +Contains methods to work with pending user's trades and revert them. -#### crossChainSymbiosisManager.getUserTrades method +### crossChainSymbiosisManager.getUserTrades method ```typescript -crossChainSymbiosisManager.getUserTrades(fromAddress?: string): Promise +sdk.crossChainSymbiosisManager.getUserTrades(fromAddress?: string): Promise ``` -Returns pending request for `fromAddress` if provided, otherwise for connected wallet address. +Returns pending trades for `fromAddress` if provided, otherwise for connected wallet address. --- -#### crossChainSymbiosisManager.revertTrade method +### crossChainSymbiosisManager.revertTrade method ```typescript -crossChainSymbiosisManager.revertTrade( +sdk.crossChainSymbiosisManager.revertTrade( revertTransactionHash: string, options?: SwapTransactionOptions ): Promise ``` -Reverts trade, which transaction hash is `revertTransactionHash` for connected wallet address. +Sends transaction to revert trade, which transaction hash is `revertTransactionHash` for connected wallet address. **SwapTransactionOptions description:** @@ -1198,9 +1242,10 @@ Reverts trade, which transaction hash is `revertTransactionHash` for connected w --- -### Tokens Manager +## Tokens Manager + +### tokensManager.createTokenFromStruct method -#### tokensManager.createTokenFromStruct method ```typescript tokensManager.createTokenFromStruct(tokenStruct: TokenStruct): Token ``` @@ -1209,35 +1254,39 @@ Creates `Token` instance by full token data struct. --- -#### tokensManager.createToken method +### tokensManager.createToken method + ```typescript tokensManager.createToken(tokenBaseStruct: TokenBaseStruct): Promise ``` -Fetches token data and creates `Token` by token address and token blockchain. +Fetches token data and creates `Token` by token's address and blockchain. --- -#### tokensManager.createTokensFromStructs method +### tokensManager.createTokensFromStructs method + ```typescript tokensManager.createTokensFromStructs(tokensStructs: TokenStruct[]): Token[] ``` -Same as `tokensManager.createTokenFromStruct` for multiple token structs. +Same as `tokensManager.createTokenFromStruct` for multiple tokens structs. --- -#### tokensManager.createTokens method +### tokensManager.createTokens method + ```typescript tokensManager.createTokens(addresses: string[], blockchain: BLOCKCHAIN_NAME): Promise ``` -Same as `tokensManager.createToken` for multiple token structs. But using multicall for data fetching, so makes only one rpc request. +Same as `tokensManager.createToken` for multiple tokens structs. But using multicall for data fetching, so makes only one rpc request. Use this method to crate tokens list instead of `Promise.all` and `tokensManager.createToken`. --- -#### tokensManager.createPriceTokenFromStruct method +### tokensManager.createPriceTokenFromStruct method + ```typescript tokensManager.createPriceTokenFromStruct(priceTokenStruct: PriceTokenStruct): PriceToken ``` @@ -1246,7 +1295,8 @@ Creates price token from full price token struct including price. --- -#### tokensManager.createPriceToken method +### tokensManager.createPriceToken method + ```typescript tokensManager.createPriceToken(token: TokenBaseStruct | TokenStruct): Promise ``` @@ -1255,7 +1305,8 @@ Creates price token from full token struct (without price) or from token address --- -#### tokensManager.createPriceTokenAmountFromStruct method +### tokensManager.createPriceTokenAmountFromStruct method + ```typescript tokensManager.createPriceTokenAmountFromStruct(priceTokenAmountStruct: PriceTokenAmountStruct): PriceTokenAmount ``` @@ -1264,7 +1315,8 @@ Creates price token amount from full price token amount struct. --- -#### tokensManager.createPriceTokenAmount method +### tokensManager.createPriceTokenAmount method + ```typescript tokensManager.createPriceTokenAmount( priceTokenAmountStruct: @@ -1277,9 +1329,10 @@ Creates price token amount from token struct (without price) and amount or from --- -### Token +## Token + +### token fields -#### token fields ```typescript readonly blockchain: BLOCKCHAIN_NAME; @@ -1294,21 +1347,29 @@ readonly decimals: number; --- -#### token.isNative method -Use `token.isNative` to detect native coins like ETH, BNB, MATIC, ... instead of comparing token address with 0x000...0. +### token.isNative getter + +```typescript +token.isNative(): boolean +``` + +Use `token.isNative` to detect native coins like ETH, BNB, MATIC, etc. --- -#### token.isEqualTo method +### token.isEqualTo method + ```typescript token.isEqualTo(token: TokenBaseStruct): boolean ``` + Use it to check that two tokens have equal blockchains and addresses (in any case: lower/upper/mixed). -Token is TokenBaseStruct so you can pass Token instance to `token.isEqualTo`. +Token is `TokenBaseStruct`, so you can pass Token instance to `token.isEqualTo`. --- -#### token.clone method +### token.clone method + ```typescript token.clone(replaceStruct?: Partial): Token ``` @@ -1317,20 +1378,32 @@ Use it to deep clone token object and replace some properties. --- -### PriceToken +## PriceToken + Extends `Token`. -#### priceToken.price getter -Returns last set token price as `BigNumber`. +### priceToken.price getter + +```typescript +priceToken.price(): BigNumber +``` + +Returns last set token price. --- -#### priceToken.asStruct getter +### priceToken.asStruct getter + +```typescript +priceToken.asStruct(): PriceTokenStruct +``` + Serializes priceToken and its price to struct object. --- -#### priceToken.getAndUpdateTokenPrice method +### priceToken.getAndUpdateTokenPrice method + ```typescript priceToken.getAndUpdateTokenPrice(): Promise ``` @@ -1339,7 +1412,8 @@ Fetches current token price and saves it into token. --- -#### priceToken.cloneAndCreate +### priceToken.cloneAndCreate + ```typescript priceToken.cloneAndCreate(tokenStruct?: Partial): Promise ``` @@ -1348,25 +1422,42 @@ Same as `token.clone` but fetches new price for new `PriceToken`. --- -### PriceTokenAmount +## PriceTokenAmount + Extends `PriceToken`. -#### priceTokenAmount.weiAmount getter -Returns saved token amount in wei as `BigNumber` (weiAmount = tokenAmount * (10 ** token.decimals)). +### priceTokenAmount.weiAmount getter + +```typescript +priceTokenAmount.weiAmount(): BigNumber +``` + +Returns saved token amount in wei (weiAmount = tokenAmount * (10 ** token.decimals)). --- -#### priceTokenAmount.stringWeiAmount getter +### priceTokenAmount.stringWeiAmount getter + +```typescript +priceTokenAmount.stringWeiAmount(): string +``` + Returns saved token amount in wei as string. --- -#### priceTokenAmount.tokenAmount getter -Returns saved token amount in human-readable token units as `BigNumber` (tokenAmount = weiAmount / (10 ** token.decimals)). +### priceTokenAmount.tokenAmount getter + +```typescript +priceTokenAmount.tokenAmount(): BigNumber +``` + +Returns saved token amount in human-readable token units (tokenAmount = weiAmount / (10 ** token.decimals)). --- -#### priceTokenAmount.weiAmountMinusSlippage method +### priceTokenAmount.weiAmountMinusSlippage method + ```typescript priceTokenAmount.weiAmountMinusSlippage(slippage: number): BigNumber ``` @@ -1375,7 +1466,8 @@ Returns wei amount decreased by (1 - slippage) times. Slippage is in range from --- -#### priceTokenAmount.weiAmountPlusSlippage method +### priceTokenAmount.weiAmountPlusSlippage method + ```typescript priceTokenAmount.weiAmountPlusSlippage(slippage: number): BigNumber ``` @@ -1384,7 +1476,8 @@ Returns wei amount increased by (1 - slippage) times. Slippage is in range from --- -#### priceTokenAmount.calculatePriceImpactPercent method +### priceTokenAmount.calculatePriceImpactPercent method + ```typescript calculatePriceImpactPercent(toToken: PriceTokenAmount): number | null ``` From c7eb5f3e0fb418e6051a45bf32ddb4f4f339ac4a Mon Sep 17 00:00:00 2001 From: ottebrut Date: Thu, 16 Jun 2022 19:02:47 +0300 Subject: [PATCH 02/13] Install typedoc --- .gitignore | 2 ++ package.json | 2 +- typedoc.json | 7 +++++++ yarn.lock | 42 +++++++++++++++++------------------------- 4 files changed, 27 insertions(+), 26 deletions(-) create mode 100644 typedoc.json diff --git a/.gitignore b/.gitignore index 229b1bb1e7..df1747b649 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,5 @@ /cache/ /scripts/node.log /docker-compose.yml + +/docs/ diff --git a/package.json b/package.json index b040c36a5d..bf94a93d19 100644 --- a/package.json +++ b/package.json @@ -96,7 +96,7 @@ "ts-loader": "^9.3.0", "tsconfig-paths-webpack-plugin": "^3.5.2", "tscpaths": "^0.0.9", - "typedoc": "^0.22.15", + "typedoc": "^0.22.17", "typescript": "^4.7.2", "webpack": "^5.65.0", "webpack-bundle-analyzer": "^4.5.0", diff --git a/typedoc.json b/typedoc.json new file mode 100644 index 0000000000..e3e124b09d --- /dev/null +++ b/typedoc.json @@ -0,0 +1,7 @@ +{ + "entryPoints": ["src/index.ts"], + "excludeInternal": true, + "excludePrivate": true, + "intentionallyNotExported": ["src/fetch-impl.ts:default"], + "out": "doc" +} diff --git a/yarn.lock b/yarn.lock index 5e8b725e52..4fcec7c432 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3625,17 +3625,16 @@ glob@^7.1.1, glob@^7.1.2, glob@^7.1.3, glob@^7.1.4: once "^1.3.0" path-is-absolute "^1.0.0" -glob@^7.2.0: - version "7.2.3" - resolved "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz" - integrity sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q== +glob@^8.0.3: + version "8.0.3" + resolved "https://registry.yarnpkg.com/glob/-/glob-8.0.3.tgz#415c6eb2deed9e502c68fa44a272e6da6eeca42e" + integrity sha512-ull455NHSHI/Y1FqGaaYFaLGkNMMJbavMrEGFXG/PGrg6y7sutWHUHrz6gy6WEBH6akM1M414dWKCNs+IhKdiQ== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" inherits "2" - minimatch "^3.1.1" + minimatch "^5.0.1" once "^1.3.0" - path-is-absolute "^1.0.0" global@~4.4.0: version "4.4.0" @@ -5082,10 +5081,10 @@ map-visit@^1.0.0: dependencies: object-visit "^1.0.0" -marked@^4.0.12: - version "4.0.16" - resolved "https://registry.npmjs.org/marked/-/marked-4.0.16.tgz" - integrity sha512-wahonIQ5Jnyatt2fn8KqF/nIqZM8mh3oRu2+l5EANGMhu6RFjiSG52QNE2eWzFMI94HqYSgN184NurgNG6CztA== +marked@^4.0.16: + version "4.0.17" + resolved "https://registry.yarnpkg.com/marked/-/marked-4.0.17.tgz#1186193d85bb7882159cdcfc57d1dfccaffb3fe9" + integrity sha512-Wfk0ATOK5iPxM4ptrORkFemqroz0ZDxp5MWfYA7H/F+wO17NRWV5Ypxi6p3g2Xmw2bKeiYOl6oVnLHKxBA0VhA== md5.js@^1.3.4: version "1.3.5" @@ -5207,14 +5206,7 @@ minimatch@^3.0.4: dependencies: brace-expansion "^1.1.7" -minimatch@^3.1.1: - version "3.1.2" - resolved "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz" - integrity sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw== - dependencies: - brace-expansion "^1.1.7" - -minimatch@^5.0.1: +minimatch@^5.0.1, minimatch@^5.1.0: version "5.1.0" resolved "https://registry.npmjs.org/minimatch/-/minimatch-5.1.0.tgz" integrity sha512-9TPBGGak4nHfGZsPBohm9AWg6NoT7QTCehS3BIJABslyZbzxfV78QM2Y6+i741OPZIafFAaiiEMh5OyIrJPgtg== @@ -6917,15 +6909,15 @@ typedarray-to-buffer@^3.1.5: dependencies: is-typedarray "^1.0.0" -typedoc@^0.22.15: - version "0.22.15" - resolved "https://registry.npmjs.org/typedoc/-/typedoc-0.22.15.tgz" - integrity sha512-CMd1lrqQbFvbx6S9G6fL4HKp3GoIuhujJReWqlIvSb2T26vGai+8Os3Mde7Pn832pXYemd9BMuuYWhFpL5st0Q== +typedoc@^0.22.17: + version "0.22.17" + resolved "https://registry.yarnpkg.com/typedoc/-/typedoc-0.22.17.tgz#bc51cc95f569040112504300831cdac4f8089b7b" + integrity sha512-h6+uXHVVCPDaANzjwzdsj9aePBjZiBTpiMpBBeyh1zcN2odVsDCNajz8zyKnixF93HJeGpl34j/70yoEE5BfNg== dependencies: - glob "^7.2.0" + glob "^8.0.3" lunr "^2.3.9" - marked "^4.0.12" - minimatch "^5.0.1" + marked "^4.0.16" + minimatch "^5.1.0" shiki "^0.10.1" typescript@^4.7.2: From 20a98e1b3cf8bd8a7b2c30c653a5af08c5324999 Mon Sep 17 00:00:00 2001 From: ottebrut Date: Fri, 17 Jun 2022 12:54:44 +0300 Subject: [PATCH 03/13] Add classes documentation --- README.md | 29 ++++++++---- .../cross-chain-is-unavailable.error.ts | 3 ++ ...-to-check-for-transaction-receipt.error.ts | 4 ++ src/common/http/coingecko-api.ts | 3 ++ src/common/http/gas-price-api.ts | 15 ++++--- src/core/blockchain/blockchains-info.ts | 13 ++++++ .../models/basic-transaction-options.ts | 12 +++++ src/core/index.ts | 1 - .../cross-chain/cross-chain-manager.ts | 15 ++++++- .../cross-chain/models/cross-chain-options.ts | 27 ++++++++++++ .../swap-manager-cross-chain-options.ts | 7 +++ .../celer-cross-chain-trade-provider.ts | 2 +- .../celer-cross-chain-trade.ts | 10 ++++- .../celer-rubic-cross-chain-trade.ts | 33 +++++++++++--- .../common/cross-chain-trade-provider.ts | 2 +- .../providers/common/cross-chain-trade.ts | 44 ++++++++++++++++++- .../rubic-cross-chain-trade-provider.ts | 2 +- .../rubic-cross-chain-trade.ts | 5 ++- .../symbiosis-cross-chain-trade.ts | 6 ++- .../models/encode-transaction-options.ts | 13 +++++- .../models/swap-transaction-options.ts | 18 +++++++- typedoc.json | 2 +- 22 files changed, 230 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 1380593820..444cee8c4a 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,7 @@ - [to](#crosschaintradeto-readonly-field) - [toTokenAmountMin](#crosschaintradetotokenamountmin-readonly-field) - [estimatedGas](#crosschaintradeestimatedgas-getter) + - [type](#crosschaintradeestimatedgas-getter) - [priceImpactData](#crosschaintradepriceimpactdata-getter) - [priceImpact readonly](#crosschaintradepriceimpact-readonly-field) - [Cross Chain Symbiosis Manager](#cross-chain-symbiosis-manager) @@ -1006,15 +1007,15 @@ Method calculates [WrappedCrossChainTrade](#wrapped-cross-chain-trade), which co **CrossChainOptions description:** -| Option | Type | Description | Default | -|-----------------------|---------------------------------|-----------------------------------------------------------------------------------------------------------------------------------|---------------------------| -| fromSlippageTolerance | `number` | Swap slippage in range 0 to 1. Defines minimum amount after swap in **first blockchain** (for Celer and Rubic). | 0.02 | -| toSlippageTolerance | `number` | Swap slippage in range 0 to 1. Defines minimum amount that you can get after swap in **second blockchain** (for Celer and Rubic). | 0.02 | -| slippageTolerance | `number` | Swap slippage in range 0 to 1. Defines minimum amount that you can get after swap (for Symbiosis). | 0.04 | -| fromAddress | `string` | User wallet address to calculate trade for (for Symbiosis). | Connected wallet address. | -| deadline | `number` | Deadline of the trade in minutes (for Symbiosis). | 20 | -| gasCalculation | `'enabled'` | `'disabled'` | Disables or enables calculation of gas limit and gas price. | 'enabled' | -| disabledProviders | `CrossChainTradeType[]` | Disables passed providers. | [] | +| Option | Type | Description | Default | +|-----------------------|---------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------| +| fromSlippageTolerance | `number` | Swap slippage in range 0 to 1. Defines minimum amount after swap in **first blockchain** (for Celer and Rubic). | 0.02 | +| toSlippageTolerance | `number` | Swap slippage in range 0 to 1. Defines minimum amount that you can get after swap in **second blockchain** (for Celer and Rubic). | 0.02 | +| slippageTolerance | `number` | Swap slippage in range 0 to 1. Defines minimum amount that you can get after swap (for Symbiosis). | 0.04 | +| fromAddress | `string` | User wallet address to calculate trade for (necessary for Symbiosis). You can use fake address to get output amount, but you must recalculate trade when user is connected. | Connected wallet address. | +| deadline | `number` | Deadline of the trade in minutes (for Symbiosis). | 20 | +| gasCalculation | `'enabled'` | `'disabled'` | Disables or enables calculation of gas limit and gas price. | 'enabled' | +| disabledProviders | `CrossChainTradeType[]` | Disables passed providers. | [] | --- @@ -1180,6 +1181,16 @@ Gets gasFee, that is gasLimit * gasPrice. Equals `null` if gas couldn't be calcu --- +### crossChainTrade.type readonly field + +```typescript +crossChainTrade.type: CrossChainTradeType +``` + +Cross-chain trade type (`CROSS_CHAIN_TRADE_TYPE.CELER`, `CROSS_CHAIN_TRADE_TYPE.SYMBIOSIS`, `CROSS_CHAIN_TRADE_TYPE.SYMBIOSIS`). Check `CROSS_CHAIN_TRADE_TYPE` interface to see all providers. + +--- + ### crossChainTrade.priceImpactData getter > ⚠ī¸ Is available only in Celer and Rubic trades. diff --git a/src/common/errors/cross-chain/cross-chain-is-unavailable.error.ts b/src/common/errors/cross-chain/cross-chain-is-unavailable.error.ts index 48d539688a..e69be9d13d 100644 --- a/src/common/errors/cross-chain/cross-chain-is-unavailable.error.ts +++ b/src/common/errors/cross-chain/cross-chain-is-unavailable.error.ts @@ -1,3 +1,6 @@ import { RubicSdkError } from '@common/errors/rubic-sdk.error'; +/** + * Thrown, when cross chain contracts are on pause or there is not enough crypto balance. + */ export class CrossChainIsUnavailableError extends RubicSdkError {} diff --git a/src/common/errors/swap/failed-to-check-for-transaction-receipt.error.ts b/src/common/errors/swap/failed-to-check-for-transaction-receipt.error.ts index 278ae7376a..18e2552dee 100644 --- a/src/common/errors/swap/failed-to-check-for-transaction-receipt.error.ts +++ b/src/common/errors/swap/failed-to-check-for-transaction-receipt.error.ts @@ -1,3 +1,7 @@ import { RubicSdkError } from '@common/errors/rubic-sdk.error'; +/** + * @internal + * Thrown, when transaction is passed, but web3 cannot retrieve transaction receipt. + */ export class FailedToCheckForTransactionReceiptError extends RubicSdkError {} diff --git a/src/common/http/coingecko-api.ts b/src/common/http/coingecko-api.ts index 0c78c624d8..ebbe8bfcda 100644 --- a/src/common/http/coingecko-api.ts +++ b/src/common/http/coingecko-api.ts @@ -23,6 +23,9 @@ type SupportedBlockchain = typeof supportedBlockchains[number]; const API_BASE_URL = 'https://api.coingecko.com/api/v3/'; +/** + * Works with coingecko api to get tokens prices in usd. + */ export class CoingeckoApi { private static isSupportedBlockchain( blockchain: BlockchainName diff --git a/src/common/http/gas-price-api.ts b/src/common/http/gas-price-api.ts index b7b8be4f93..7a5a7c6405 100644 --- a/src/common/http/gas-price-api.ts +++ b/src/common/http/gas-price-api.ts @@ -6,6 +6,9 @@ import BigNumber from 'bignumber.js'; import { HttpClient } from '@common/models/http-client'; import { Web3Pure } from '@core/blockchain/web3-pure/web3-pure'; +/** + * Uses different api or web3 to retrieve current gas price. + */ export class GasPriceApi { /** * Gas price request interval in seconds. @@ -15,9 +18,8 @@ export class GasPriceApi { constructor(private readonly httpClient: HttpClient) {} /** - * Gas price in Wei for selected blockchain. + * Gets gas price in Wei for selected blockchain. * @param blockchain Blockchain to get gas price from. - * @return Promise Average gas price in Wei. */ public getGasPrice(blockchain: BlockchainName): Promise { if (blockchain === BLOCKCHAIN_NAME.ETHEREUM) { @@ -27,9 +29,8 @@ export class GasPriceApi { } /** - * Gas price in Eth units for selected blockchain. + * Gets gas price in Eth units for selected blockchain. * @param blockchain Blockchain to get gas price from. - * @return Promise Average gas price in Eth units. */ public async getGasPriceInEthUnits(blockchain: BlockchainName): Promise { return Web3Pure.fromWei(await this.getGasPrice(blockchain)); @@ -37,7 +38,7 @@ export class GasPriceApi { /** * Gets Ethereum gas price from different APIs, sorted by priority. - * @return Promise Average gas price in Wei. + * @returns Average gas price in Wei. */ @Cache({ maxAge: GasPriceApi.requestInterval @@ -66,8 +67,8 @@ export class GasPriceApi { } /** - * Gets Avalanche gas price. - * @return Promise Average gas price in Wei. + * Gets gas price from web3. + * @returns Average gas price in Wei. */ @Cache({ maxAge: GasPriceApi.requestInterval diff --git a/src/core/blockchain/blockchains-info.ts b/src/core/blockchain/blockchains-info.ts index ab3b4f40a8..d8ea6a703f 100644 --- a/src/core/blockchain/blockchains-info.ts +++ b/src/core/blockchain/blockchains-info.ts @@ -3,14 +3,27 @@ import { Blockchain } from '@core/blockchain/models/blockchain'; import { BlockchainName } from '@core/blockchain/models/blockchain-name'; import BigNumber from 'bignumber.js'; +/** + * Works with list of all used in project blockchains. + * Contains method to find info about certain blockchain. + */ export class BlockchainsInfo { + /** + * An array of all blockchains, used in project. + */ public static readonly blockchains: ReadonlyArray = blockchains; + /** + * Finds blockchain object, based on provided chain id. + */ public static getBlockchainById(chainId: string | number): Blockchain | undefined { const chainIdNumber = new BigNumber(chainId).toNumber(); return BlockchainsInfo.blockchains.find(blockchain => blockchain.id === chainIdNumber); } + /** + * Finds blockchain object, based on provided blockchain name. + */ public static getBlockchainByName(blockchainName: BlockchainName): Blockchain { return BlockchainsInfo.blockchains.find(blockchain => blockchain.name === blockchainName)!; } diff --git a/src/core/blockchain/models/basic-transaction-options.ts b/src/core/blockchain/models/basic-transaction-options.ts index e754fd2f9e..1196210a0b 100644 --- a/src/core/blockchain/models/basic-transaction-options.ts +++ b/src/core/blockchain/models/basic-transaction-options.ts @@ -1,5 +1,17 @@ export type BasicTransactionOptions = { + /** + * Callback to be called, when user confirm swap transaction. + * @param hash Transaction hash. + */ onTransactionHash?: (hash: string) => void; + + /** + * Transaction gas limit. + */ gasLimit?: string; + + /** + * Transaction gas price. + */ gasPrice?: string; }; diff --git a/src/core/index.ts b/src/core/index.ts index 3771cd13d4..392016f6da 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -3,7 +3,6 @@ export { Web3Public } from './blockchain/web3-public/web3-public'; export { Web3Private } from './blockchain/web3-private/web3-private'; export { Web3Pure } from './blockchain/web3-pure/web3-pure'; export { BlockchainsInfo } from './blockchain/blockchains-info'; -export { blockchains } from './blockchain/constants/blockchains'; export { BlockchainName, BLOCKCHAIN_NAME } from './blockchain/models/blockchain-name'; export type { Token } from './blockchain/tokens/token'; diff --git a/src/features/cross-chain/cross-chain-manager.ts b/src/features/cross-chain/cross-chain-manager.ts index cfa8dfa343..332905937d 100644 --- a/src/features/cross-chain/cross-chain-manager.ts +++ b/src/features/cross-chain/cross-chain-manager.ts @@ -27,8 +27,11 @@ import { RubicCrossChainTradeProvider } from './providers/rubic-trade-provider/r type RequiredSwapManagerCalculationOptions = Required; +/** + * Contains method to calculate best cross chain trade. + */ export class CrossChainManager { - public static readonly defaultCalculationTimeout = 360_000; + private static readonly defaultCalculationTimeout = 15_000; private static readonly defaultSlippageTolerance = 0.02; @@ -46,6 +49,14 @@ export class CrossChainManager { constructor(private readonly providerAddress: string) {} + /** + * Calculates best cross chain trade, based on course. + * @param fromToken Token to sell. + * @param fromAmount Amount to sell. + * @param toToken Token to get. + * @param options Additional options. + * @returns Wrapped cross chain trade, with possible min or max amount errors. + */ public async calculateTrade( fromToken: | Token @@ -60,7 +71,7 @@ export class CrossChainManager { address: string; blockchain: BlockchainName; }, - options?: SwapManagerCrossChainCalculationOptions + options?: Omit ): Promise { if (toToken instanceof Token && fromToken.blockchain === toToken.blockchain) { throw new RubicSdkError('Blockchains of from and to tokens must be different.'); diff --git a/src/features/cross-chain/models/cross-chain-options.ts b/src/features/cross-chain/models/cross-chain-options.ts index d707397562..baa6f4f394 100644 --- a/src/features/cross-chain/models/cross-chain-options.ts +++ b/src/features/cross-chain/models/cross-chain-options.ts @@ -1,10 +1,37 @@ export interface CrossChainOptions { + /** + * Slippage in source network (for Celer and Rubic). + */ fromSlippageTolerance?: number; + + /** + * Slippage in target network (for Celer and Rubic). + */ toSlippageTolerance?: number; + + /** + * Enables or disables gas fee calculation. + */ gasCalculation?: 'enabled' | 'disabled'; + + /** + * Integrator address. + */ providerAddress?: string; + + /** + * Deadline for transaction (for Symbiosis). + */ deadline?: number; + + /** + * Overall slippage (for Symbiosis). + */ slippageTolerance?: number; + + /** + * Address to send transaction, otherwise connected wallet is used (necessary for Symbiosis). + */ fromAddress?: string; } diff --git a/src/features/cross-chain/models/swap-manager-cross-chain-options.ts b/src/features/cross-chain/models/swap-manager-cross-chain-options.ts index 2ae583731e..f5803e1f5d 100644 --- a/src/features/cross-chain/models/swap-manager-cross-chain-options.ts +++ b/src/features/cross-chain/models/swap-manager-cross-chain-options.ts @@ -2,6 +2,13 @@ import { CrossChainTradeType } from 'src/features'; import { CrossChainOptions } from '@features/cross-chain/models/cross-chain-options'; export interface SwapManagerCrossChainCalculationOptions extends CrossChainOptions { + /** + * Timeout for each cross chain provider. Calculation for provider is cancelled, after timeout is passed. + */ readonly timeout?: number; + + /** + * An array of disabled cross chain providers. + */ readonly disabledProviders?: CrossChainTradeType[]; } diff --git a/src/features/cross-chain/providers/celer-trade-provider/celer-cross-chain-trade-provider.ts b/src/features/cross-chain/providers/celer-trade-provider/celer-cross-chain-trade-provider.ts index f2b3712108..f439cf0010 100644 --- a/src/features/cross-chain/providers/celer-trade-provider/celer-cross-chain-trade-provider.ts +++ b/src/features/cross-chain/providers/celer-trade-provider/celer-cross-chain-trade-provider.ts @@ -31,7 +31,7 @@ export class CelerCrossChainTradeProvider extends CelerRubicCrossChainTradeProvi ); } - public type = CROSS_CHAIN_TRADE_TYPE.CELER; + public readonly type = CROSS_CHAIN_TRADE_TYPE.CELER; protected contracts = getCelerCrossChainContract; diff --git a/src/features/cross-chain/providers/celer-trade-provider/celer-cross-chain-trade.ts b/src/features/cross-chain/providers/celer-trade-provider/celer-cross-chain-trade.ts index 22cd6848a9..812568a0a0 100644 --- a/src/features/cross-chain/providers/celer-trade-provider/celer-cross-chain-trade.ts +++ b/src/features/cross-chain/providers/celer-trade-provider/celer-cross-chain-trade.ts @@ -19,8 +19,13 @@ import { } from '@features/cross-chain/providers/celer-trade-provider/constants/celer-cross-chain-fee-multipliers'; import { CelerCrossChainContractTrade } from '@features/cross-chain/providers/celer-trade-provider/celer-cross-chain-contract-trade/celer-cross-chain-contract-trade'; import { CelerItCrossChainContractTrade } from '@features/cross-chain/providers/celer-trade-provider/celer-cross-chain-contract-trade/celer-it-cross-chain-contract-trade/celer-it-cross-chain-contract-trade'; +import { CROSS_CHAIN_TRADE_TYPE } from 'src/features'; +/** + * Calculated Celer cross chain trade. + */ export class CelerCrossChainTrade extends CelerRubicCrossChainTrade { + /** @internal */ public static async getGasData( fromTrade: CrossChainContractTrade, toTrade: CrossChainContractTrade, @@ -74,7 +79,9 @@ export class CelerCrossChainTrade extends CelerRubicCrossChainTrade { } } - private readonly transitFeeToken: PriceTokenAmount; + public readonly type = CROSS_CHAIN_TRADE_TYPE.CELER; + + public readonly transitFeeToken: PriceTokenAmount; public readonly from: PriceTokenAmount; @@ -136,6 +143,7 @@ export class CelerCrossChainTrade extends CelerRubicCrossChainTrade { await Promise.all([ this.checkContractsState(), this.checkToBlockchainGasPrice(), + this.checkToContractBalance(), this.checkUserBalance() ]); } diff --git a/src/features/cross-chain/providers/common/celer-rubic/celer-rubic-cross-chain-trade.ts b/src/features/cross-chain/providers/common/celer-rubic/celer-rubic-cross-chain-trade.ts index c3cfa8fed5..1a464e4850 100644 --- a/src/features/cross-chain/providers/common/celer-rubic/celer-rubic-cross-chain-trade.ts +++ b/src/features/cross-chain/providers/common/celer-rubic/celer-rubic-cross-chain-trade.ts @@ -6,9 +6,13 @@ import { Injector } from '@core/sdk/injector'; import { BLOCKCHAIN_NAME } from '@core/blockchain/models/blockchain-name'; import { CrossChainTrade } from '@features/cross-chain/providers/common/cross-chain-trade'; +/** + * Contains common for Celer and Rubic trades methods and fields. + */ export abstract class CelerRubicCrossChainTrade extends CrossChainTrade { - public abstract readonly toTokenAmountMin: BigNumber; - + /** + * Gets price impact in source and target blockchains, based on tokens usd prices. + */ @Cache public get priceImpactData(): { priceImpactFrom: number | null; @@ -24,11 +28,30 @@ export abstract class CelerRubicCrossChainTrade extends CrossChainTrade { }; } - protected abstract readonly fromTrade: CrossChainContractTrade; + /** + * Wrapped instant trade in source blockchain. + */ + public abstract readonly fromTrade: CrossChainContractTrade; + + /** + * Wrapped instant trade in target blockchain. + */ + public abstract readonly toTrade: CrossChainContractTrade; + + /** + * Minimum amount of output token user will get. + */ + public abstract readonly toTokenAmountMin: BigNumber; - protected abstract readonly toTrade: CrossChainContractTrade; + /** + * Native token in source blockchain, taken as fee. + */ + public abstract readonly cryptoFeeToken: PriceTokenAmount; - protected abstract readonly cryptoFeeToken: PriceTokenAmount; + /** + * Transit token in source blockchain, taken as fee. + */ + public abstract readonly transitFeeToken: PriceTokenAmount; protected abstract readonly toWeb3Public: Web3Public; diff --git a/src/features/cross-chain/providers/common/cross-chain-trade-provider.ts b/src/features/cross-chain/providers/common/cross-chain-trade-provider.ts index d6d65da01c..7e07bd75c2 100644 --- a/src/features/cross-chain/providers/common/cross-chain-trade-provider.ts +++ b/src/features/cross-chain/providers/common/cross-chain-trade-provider.ts @@ -5,7 +5,7 @@ import { PriceToken } from '@core/blockchain/tokens/price-token'; import { WrappedCrossChainTrade } from '@features/cross-chain/providers/common/models/wrapped-cross-chain-trade'; export abstract class CrossChainTradeProvider { - public abstract type: CrossChainTradeType; + public abstract readonly type: CrossChainTradeType; public abstract calculate( from: PriceTokenAmount, diff --git a/src/features/cross-chain/providers/common/cross-chain-trade.ts b/src/features/cross-chain/providers/common/cross-chain-trade.ts index b4c8bdb50f..1ca52a9868 100644 --- a/src/features/cross-chain/providers/common/cross-chain-trade.ts +++ b/src/features/cross-chain/providers/common/cross-chain-trade.ts @@ -8,18 +8,39 @@ import { import { GasData } from '@features/cross-chain/models/gas-data'; import { Injector } from '@core/sdk/injector'; import BigNumber from 'bignumber.js'; -import { EncodeTransactionOptions, SwapTransactionOptions } from 'src/features'; +import { + CrossChainTradeType, + EncodeTransactionOptions, + SwapTransactionOptions +} from 'src/features'; import { UnnecessaryApprove, WalletNotConnectedError, WrongNetworkError } from 'src/common'; import { TransactionReceipt } from 'web3-eth'; import { ContractParams } from '@features/cross-chain/models/contract-params'; import { TransactionConfig } from 'web3-core'; +/** + * Abstract class for all cross chain providers' trades. + */ export abstract class CrossChainTrade { + /** + * Type of calculated cross chain trade. + */ + public abstract readonly type: CrossChainTradeType; + + /** + * Token to get with output amount. + */ public abstract readonly to: PriceTokenAmount; + /** + * Token to sell with input amount. + */ public abstract readonly from: PriceTokenAmount; - protected abstract readonly gasData: GasData | null; + /** + * Gas fee info in source blockchain. + */ + public abstract readonly gasData: GasData | null; protected abstract readonly fromWeb3Public: Web3Public; @@ -29,6 +50,9 @@ export abstract class CrossChainTrade { return Injector.web3Private.address; } + /** + * Gets gas fee in source blockchain. + */ public get estimatedGas(): BigNumber | null { if (!this.gasData) { return null; @@ -38,10 +62,18 @@ export abstract class CrossChainTrade { protected constructor(protected readonly providerAddress: string) {} + /** + * Sends swap transaction with connected wallet. + * If user has not enough allowance, then approve transaction will be called first. + * @param options Transaction options. + */ public abstract swap(options?: SwapTransactionOptions): Promise; protected abstract getContractParams(fromAddress?: string): Promise; + /** + * Returns true, if allowance is not enough. + */ public async needApprove(): Promise { this.checkWalletConnected(); @@ -57,6 +89,10 @@ export abstract class CrossChainTrade { return this.from.weiAmount.gt(allowance); } + /** + * Sends approve transaction with connected wallet. + * @param options Transaction options. + */ public async approve(options: BasicTransactionOptions): Promise { if (!(await this.needApprove())) { throw new UnnecessaryApprove(); @@ -95,6 +131,10 @@ export abstract class CrossChainTrade { ); } + /** + * Builds transaction config, with encoded data. + * @param options Encode transaction options. + */ public async encode(options: EncodeTransactionOptions): Promise { const { gasLimit, gasPrice } = options; diff --git a/src/features/cross-chain/providers/rubic-trade-provider/rubic-cross-chain-trade-provider.ts b/src/features/cross-chain/providers/rubic-trade-provider/rubic-cross-chain-trade-provider.ts index 03d35f4a4c..0baa113a2c 100644 --- a/src/features/cross-chain/providers/rubic-trade-provider/rubic-cross-chain-trade-provider.ts +++ b/src/features/cross-chain/providers/rubic-trade-provider/rubic-cross-chain-trade-provider.ts @@ -27,7 +27,7 @@ export class RubicCrossChainTradeProvider extends CelerRubicCrossChainTradeProvi ); } - public type = CROSS_CHAIN_TRADE_TYPE.RUBIC; + public readonly type = CROSS_CHAIN_TRADE_TYPE.RUBIC; protected readonly contracts = getRubicCrossChainContract; diff --git a/src/features/cross-chain/providers/rubic-trade-provider/rubic-cross-chain-trade.ts b/src/features/cross-chain/providers/rubic-trade-provider/rubic-cross-chain-trade.ts index 2cdc9a812a..bf5ff355c3 100644 --- a/src/features/cross-chain/providers/rubic-trade-provider/rubic-cross-chain-trade.ts +++ b/src/features/cross-chain/providers/rubic-trade-provider/rubic-cross-chain-trade.ts @@ -15,6 +15,7 @@ import { CrossChainContractTrade } from '@features/cross-chain/providers/common/ import { ContractParams } from '@features/cross-chain/models/contract-params'; import { LowSlippageDeflationaryTokenError, RubicSdkError } from 'src/common'; import { TOKEN_WITH_FEE_ERRORS } from '@features/cross-chain/constants/token-with-fee-errors'; +import { CROSS_CHAIN_TRADE_TYPE } from 'src/features'; export class RubicCrossChainTrade extends CelerRubicCrossChainTrade { public static async getGasData( @@ -69,7 +70,9 @@ export class RubicCrossChainTrade extends CelerRubicCrossChainTrade { } } - private readonly transitFeeToken: PriceTokenAmount; + public readonly type = CROSS_CHAIN_TRADE_TYPE.RUBIC; + + public readonly transitFeeToken: PriceTokenAmount; public readonly from: PriceTokenAmount; diff --git a/src/features/cross-chain/providers/symbiosis-trade-provider/symbiosis-cross-chain-trade.ts b/src/features/cross-chain/providers/symbiosis-trade-provider/symbiosis-cross-chain-trade.ts index 2294b0b9ba..2a8e63197b 100644 --- a/src/features/cross-chain/providers/symbiosis-trade-provider/symbiosis-cross-chain-trade.ts +++ b/src/features/cross-chain/providers/symbiosis-trade-provider/symbiosis-cross-chain-trade.ts @@ -1,4 +1,4 @@ -import { SwapTransactionOptions } from 'src/features'; +import { CROSS_CHAIN_TRADE_TYPE, SwapTransactionOptions } from 'src/features'; import { CrossChainTrade } from '@features/cross-chain/providers/common/cross-chain-trade'; import { TransactionRequest } from '@ethersproject/providers'; import { PriceTokenAmount, Web3Public, Web3Pure } from 'src/core'; @@ -64,13 +64,15 @@ export class SymbiosisCrossChainTrade extends CrossChainTrade { } } + public readonly type = CROSS_CHAIN_TRADE_TYPE.SYMBIOSIS; + public readonly from: PriceTokenAmount; public readonly to: PriceTokenAmount; public readonly priceImpact: number; - protected readonly gasData: GasData | null; + public readonly gasData: GasData | null; private readonly transactionRequest: TransactionRequest; diff --git a/src/features/instant-trades/models/encode-transaction-options.ts b/src/features/instant-trades/models/encode-transaction-options.ts index fe9e2014c7..3d403dee5a 100644 --- a/src/features/instant-trades/models/encode-transaction-options.ts +++ b/src/features/instant-trades/models/encode-transaction-options.ts @@ -1,5 +1,16 @@ export interface EncodeTransactionOptions { + /** + * User wallet address to send swap transaction. + */ + fromAddress: string; + + /** + * Transaction gas price. + */ gasPrice?: string; + + /** + * Transaction gas limit. + */ gasLimit?: string; - fromAddress: string; } diff --git a/src/features/instant-trades/models/swap-transaction-options.ts b/src/features/instant-trades/models/swap-transaction-options.ts index 69deece026..83d3f02c61 100644 --- a/src/features/instant-trades/models/swap-transaction-options.ts +++ b/src/features/instant-trades/models/swap-transaction-options.ts @@ -1,7 +1,23 @@ export interface SwapTransactionOptions { + /** + * Callback to be called, when user confirm swap transaction. + * @param hash Transaction hash. + */ onConfirm?: (hash: string) => void; + + /** + * Callback to be called, when user confirm approve transaction. + * @param hash Transaction hash. + */ onApprove?: (hash: string | null) => void; + + /** + * Transaction gas limit. + */ gasPrice?: string; + + /** + * Transaction gas price. + */ gasLimit?: string; - fromAddress?: string; } diff --git a/typedoc.json b/typedoc.json index e3e124b09d..0a1287eb40 100644 --- a/typedoc.json +++ b/typedoc.json @@ -2,6 +2,6 @@ "entryPoints": ["src/index.ts"], "excludeInternal": true, "excludePrivate": true, - "intentionallyNotExported": ["src/fetch-impl.ts:default"], + "excludeProtected": true, "out": "doc" } From 6e21619694f2359a4a100f3d9dec051870735bc5 Mon Sep 17 00:00:00 2001 From: ottebrut Date: Fri, 17 Jun 2022 16:45:02 +0300 Subject: [PATCH 04/13] Add classes documentation --- .../errors/blockchain/healthcheck.error.ts | 4 ++ src/common/errors/blockchain/low-gas.error.ts | 3 ++ ...nsufficient-funds-gas-price-value.error.ts | 3 ++ .../max-gas-price-overflow.error.ts | 4 ++ .../swap/insufficient-funds-oneinch.error.ts | 3 ++ .../errors/swap/insufficient-funds.error.ts | 3 ++ .../swap/insufficient-liquidity.error.ts | 3 ++ .../low-slippage-deflationary-token.error.ts | 3 ++ src/common/errors/swap/low-slippage.error.ts | 3 ++ .../errors/swap/not-supported-blockchain.ts | 4 ++ .../cross-chain/cross-chain-manager.ts | 2 +- .../cross-chain/models/cross-chain-options.ts | 3 ++ .../providers/common/cross-chain-trade.ts | 8 ++-- .../oneinch-abstract-provider.ts | 6 +++ .../common/oneinch-common/oneinch-trade.ts | 12 +++++- .../uniswap-v2-abstract-provider.ts | 12 ++++++ .../uniswap-v3-algebra-abstract-provider.ts | 12 ++++++ .../instant-trades/instant-trade-provider.ts | 16 +++++++- src/features/instant-trades/instant-trade.ts | 40 +++++++++++++++++++ .../instant-trades/instant-trades-manager.ts | 14 +++++++ .../models/swap-calculation-options.ts | 20 +++++++++- .../instant-trades/models/swap-options.ts | 7 ++++ 22 files changed, 177 insertions(+), 8 deletions(-) diff --git a/src/common/errors/blockchain/healthcheck.error.ts b/src/common/errors/blockchain/healthcheck.error.ts index 46fb027242..c6971ce7b4 100644 --- a/src/common/errors/blockchain/healthcheck.error.ts +++ b/src/common/errors/blockchain/healthcheck.error.ts @@ -1,3 +1,7 @@ import { RubicSdkError } from '@common/errors/rubic-sdk.error'; +/** + * @internal + * Thrown, if rpc provider has not passed healthcheck. + */ export class HealthcheckError extends RubicSdkError {} diff --git a/src/common/errors/blockchain/low-gas.error.ts b/src/common/errors/blockchain/low-gas.error.ts index 74fc42ca2f..31c1598471 100644 --- a/src/common/errors/blockchain/low-gas.error.ts +++ b/src/common/errors/blockchain/low-gas.error.ts @@ -1,3 +1,6 @@ import { RubicSdkError } from '@common/errors/rubic-sdk.error'; +/** + * Thrown, when gas price is too low. + */ export class LowGasError extends RubicSdkError {} diff --git a/src/common/errors/cross-chain/insufficient-funds-gas-price-value.error.ts b/src/common/errors/cross-chain/insufficient-funds-gas-price-value.error.ts index 527309fa3c..96bcec0c5c 100644 --- a/src/common/errors/cross-chain/insufficient-funds-gas-price-value.error.ts +++ b/src/common/errors/cross-chain/insufficient-funds-gas-price-value.error.ts @@ -1,3 +1,6 @@ import { RubicSdkError } from '@common/errors/rubic-sdk.error'; +/** + * Thrown, when user doesn't have enough native token balance for gas fee plus `value`. + */ export class InsufficientFundsGasPriceValueError extends RubicSdkError {} diff --git a/src/common/errors/cross-chain/max-gas-price-overflow.error.ts b/src/common/errors/cross-chain/max-gas-price-overflow.error.ts index 560db1d8f4..14ab1c06d8 100644 --- a/src/common/errors/cross-chain/max-gas-price-overflow.error.ts +++ b/src/common/errors/cross-chain/max-gas-price-overflow.error.ts @@ -1,3 +1,7 @@ import { RubicSdkError } from '@common/errors/rubic-sdk.error'; +/** + * Thrown, when current gas price is higher, than max gas price on cross chain contract + * in target network. + */ export class MaxGasPriceOverflowError extends RubicSdkError {} diff --git a/src/common/errors/swap/insufficient-funds-oneinch.error.ts b/src/common/errors/swap/insufficient-funds-oneinch.error.ts index 3551183838..eff70644a6 100644 --- a/src/common/errors/swap/insufficient-funds-oneinch.error.ts +++ b/src/common/errors/swap/insufficient-funds-oneinch.error.ts @@ -1,3 +1,6 @@ import { RubicSdkError } from '@common/errors/rubic-sdk.error'; +/** + * Thrown by 1inch, if user doesn't have enough balance. + */ export class InsufficientFundsOneinchError extends RubicSdkError {} diff --git a/src/common/errors/swap/insufficient-funds.error.ts b/src/common/errors/swap/insufficient-funds.error.ts index 22bce62c70..f9e0292acf 100644 --- a/src/common/errors/swap/insufficient-funds.error.ts +++ b/src/common/errors/swap/insufficient-funds.error.ts @@ -1,3 +1,6 @@ import { RubicSdkError } from '@common/errors/rubic-sdk.error'; +/** + * Thrown, when user doesn't have enough balance. + */ export class InsufficientFundsError extends RubicSdkError {} diff --git a/src/common/errors/swap/insufficient-liquidity.error.ts b/src/common/errors/swap/insufficient-liquidity.error.ts index 4857e169e2..971255ff1f 100644 --- a/src/common/errors/swap/insufficient-liquidity.error.ts +++ b/src/common/errors/swap/insufficient-liquidity.error.ts @@ -1,3 +1,6 @@ import { RubicSdkError } from '@common/errors/rubic-sdk.error'; +/** + * Thrown, when tokens' pair doesn't have enough liquidity. + */ export class InsufficientLiquidityError extends RubicSdkError {} diff --git a/src/common/errors/swap/low-slippage-deflationary-token.error.ts b/src/common/errors/swap/low-slippage-deflationary-token.error.ts index 5492cfd332..5d15787318 100644 --- a/src/common/errors/swap/low-slippage-deflationary-token.error.ts +++ b/src/common/errors/swap/low-slippage-deflationary-token.error.ts @@ -1,3 +1,6 @@ import { RubicSdkError } from '@common/errors/rubic-sdk.error'; +/** + * Thrown, when user is selling deflationary token with too low slippage. + */ export class LowSlippageDeflationaryTokenError extends RubicSdkError {} diff --git a/src/common/errors/swap/low-slippage.error.ts b/src/common/errors/swap/low-slippage.error.ts index 53c6c626b7..8123cbcdba 100644 --- a/src/common/errors/swap/low-slippage.error.ts +++ b/src/common/errors/swap/low-slippage.error.ts @@ -1,3 +1,6 @@ import { RubicSdkError } from '@common/errors/rubic-sdk.error'; +/** + * Thrown, when token cannot be swapped with provided options. + */ export class LowSlippageError extends RubicSdkError {} diff --git a/src/common/errors/swap/not-supported-blockchain.ts b/src/common/errors/swap/not-supported-blockchain.ts index e048a6fc3d..51e9bb4e60 100644 --- a/src/common/errors/swap/not-supported-blockchain.ts +++ b/src/common/errors/swap/not-supported-blockchain.ts @@ -1,3 +1,7 @@ import { RubicSdkError } from '@common/errors/rubic-sdk.error'; +/** + * @internal + * Thrown, when provider does not support provided blockchain. + */ export class NotSupportedBlockchain extends RubicSdkError {} diff --git a/src/features/cross-chain/cross-chain-manager.ts b/src/features/cross-chain/cross-chain-manager.ts index 332905937d..9f474473ae 100644 --- a/src/features/cross-chain/cross-chain-manager.ts +++ b/src/features/cross-chain/cross-chain-manager.ts @@ -50,7 +50,7 @@ export class CrossChainManager { constructor(private readonly providerAddress: string) {} /** - * Calculates best cross chain trade, based on course. + * Calculates best cross chain trade, based on calculated courses. * @param fromToken Token to sell. * @param fromAmount Amount to sell. * @param toToken Token to get. diff --git a/src/features/cross-chain/models/cross-chain-options.ts b/src/features/cross-chain/models/cross-chain-options.ts index baa6f4f394..9608710de3 100644 --- a/src/features/cross-chain/models/cross-chain-options.ts +++ b/src/features/cross-chain/models/cross-chain-options.ts @@ -1,11 +1,13 @@ export interface CrossChainOptions { /** * Slippage in source network (for Celer and Rubic). + * Takes value from 0 to 1. */ fromSlippageTolerance?: number; /** * Slippage in target network (for Celer and Rubic). + * Takes value from 0 to 1. */ toSlippageTolerance?: number; @@ -26,6 +28,7 @@ export interface CrossChainOptions { /** * Overall slippage (for Symbiosis). + * Takes value from 0 to 1. */ slippageTolerance?: number; diff --git a/src/features/cross-chain/providers/common/cross-chain-trade.ts b/src/features/cross-chain/providers/common/cross-chain-trade.ts index 1ca52a9868..a5e7f0ef79 100644 --- a/src/features/cross-chain/providers/common/cross-chain-trade.ts +++ b/src/features/cross-chain/providers/common/cross-chain-trade.ts @@ -28,14 +28,14 @@ export abstract class CrossChainTrade { public abstract readonly type: CrossChainTradeType; /** - * Token to get with output amount. + * Token to sell with input amount. */ - public abstract readonly to: PriceTokenAmount; + public abstract readonly from: PriceTokenAmount; /** - * Token to sell with input amount. + * Token to get with output amount. */ - public abstract readonly from: PriceTokenAmount; + public abstract readonly to: PriceTokenAmount; /** * Gas fee info in source blockchain. diff --git a/src/features/instant-trades/dexes/common/oneinch-common/oneinch-abstract-provider.ts b/src/features/instant-trades/dexes/common/oneinch-common/oneinch-abstract-provider.ts index 942610e0ab..c1c346203f 100644 --- a/src/features/instant-trades/dexes/common/oneinch-common/oneinch-abstract-provider.ts +++ b/src/features/instant-trades/dexes/common/oneinch-common/oneinch-abstract-provider.ts @@ -68,6 +68,12 @@ export abstract class OneinchAbstractProvider extends InstantTradeProvider { return response.address; } + /** + * Calculates input amount, based on amount, user wants to get. + * @param from Token to sell. + * @param to Token to get with output amount. + * @param options Additional options. + */ public async calculateExactOutputAmount( from: PriceToken, to: PriceTokenAmount, diff --git a/src/features/instant-trades/dexes/common/oneinch-common/oneinch-trade.ts b/src/features/instant-trades/dexes/common/oneinch-common/oneinch-trade.ts index 8a835199d2..52baa61f01 100644 --- a/src/features/instant-trades/dexes/common/oneinch-common/oneinch-trade.ts +++ b/src/features/instant-trades/dexes/common/oneinch-common/oneinch-trade.ts @@ -43,6 +43,7 @@ export class OneinchTrade extends InstantTrade { [BLOCKCHAIN_NAME.POLYGON]: TRADE_TYPE.ONE_INCH_POLYGON } as const; + /** @internal */ public static async checkIfNeedApproveAndThrowError( from: PriceTokenAmount ): Promise { @@ -56,6 +57,7 @@ export class OneinchTrade extends InstantTrade { private readonly httpClient = Injector.httpClient; + /** @internal */ public readonly contractAddress: string; public readonly from: PriceTokenAmount; @@ -64,7 +66,7 @@ export class OneinchTrade extends InstantTrade { private readonly nativeSupportedFrom: PriceTokenAmount; - public readonly nativeSupportedTo: PriceTokenAmount; + private readonly nativeSupportedTo: PriceTokenAmount; public gasFeeInfo: GasFeeInfo | null; @@ -72,10 +74,18 @@ export class OneinchTrade extends InstantTrade { private readonly disableMultihops: boolean; + /** + * Path, through which tokens will be converted. + */ public readonly path: ReadonlyArray; + /** + * @internal + * Path with wrapped native address. + */ public readonly wrappedPath: ReadonlyArray; + /** @internal */ public readonly transactionData: string | null; public get type(): TradeType { diff --git a/src/features/instant-trades/dexes/common/uniswap-v2-abstract/uniswap-v2-abstract-provider.ts b/src/features/instant-trades/dexes/common/uniswap-v2-abstract/uniswap-v2-abstract-provider.ts index ac6873ed92..bb3b50c53a 100644 --- a/src/features/instant-trades/dexes/common/uniswap-v2-abstract/uniswap-v2-abstract-provider.ts +++ b/src/features/instant-trades/dexes/common/uniswap-v2-abstract/uniswap-v2-abstract-provider.ts @@ -45,6 +45,12 @@ export abstract class UniswapV2AbstractProvider< return this.calculateDifficultTrade(from, to, from.weiAmount, 'input', options); } + /** + * Calculates trade, based on amount, user wants to get. + * @param from Token to sell. + * @param to Token to get with output amount. + * @param options Additional options. + */ public async calculateExactOutput( from: PriceToken, to: PriceTokenAmount, @@ -53,6 +59,12 @@ export abstract class UniswapV2AbstractProvider< return this.calculateDifficultTrade(from, to, to.weiAmount, 'output', options); } + /** + * Calculates input amount, based on amount, user wants to get. + * @param from Token to sell. + * @param to Token to get with output amount. + * @param options Additional options. + */ public async calculateExactOutputAmount( from: PriceToken, to: PriceTokenAmount, diff --git a/src/features/instant-trades/dexes/common/uniswap-v3-algebra-abstract/uniswap-v3-algebra-abstract-provider.ts b/src/features/instant-trades/dexes/common/uniswap-v3-algebra-abstract/uniswap-v3-algebra-abstract-provider.ts index 2bf329d35c..a1ed315774 100644 --- a/src/features/instant-trades/dexes/common/uniswap-v3-algebra-abstract/uniswap-v3-algebra-abstract-provider.ts +++ b/src/features/instant-trades/dexes/common/uniswap-v3-algebra-abstract/uniswap-v3-algebra-abstract-provider.ts @@ -59,6 +59,12 @@ export abstract class UniswapV3AlgebraAbstractProvider< return this.calculateDifficultTrade(from, toToken, 'input', from.weiAmount, options); } + /** + * Calculates trade, based on amount, user wants to get. + * @param fromToken Token to sell. + * @param to Token to get with output amount. + * @param options Additional options. + */ public async calculateExactOutput( fromToken: PriceToken, to: PriceTokenAmount, @@ -67,6 +73,12 @@ export abstract class UniswapV3AlgebraAbstractProvider< return this.calculateDifficultTrade(fromToken, to, 'output', to.weiAmount, options); } + /** + * Calculates input amount, based on amount, user wants to get. + * @param fromToken Token to sell. + * @param to Token to get with output amount. + * @param options Additional options. + */ public async calculateExactOutputAmount( fromToken: PriceToken, to: PriceTokenAmount, diff --git a/src/features/instant-trades/instant-trade-provider.ts b/src/features/instant-trades/instant-trade-provider.ts index 57579a4060..f636b93610 100644 --- a/src/features/instant-trades/instant-trade-provider.ts +++ b/src/features/instant-trades/instant-trade-provider.ts @@ -11,17 +11,31 @@ import BigNumber from 'bignumber.js'; import { GasFeeInfo } from '@features/instant-trades/models/gas-fee-info'; import { TradeType } from 'src/features'; +/** + * Abstract class for all instant trade providers. + */ export abstract class InstantTradeProvider { + /** + * Provider blockchain. + */ public abstract readonly blockchain: BlockchainName; protected abstract readonly gasMargin: number; + /** + * Type of provider. + */ public abstract get type(): TradeType; protected get web3Public(): Web3Public { return Injector.web3PublicService.getWeb3Public(this.blockchain); } - + /** + * Calculates best instant trade, based on course. + * @param from Token to sell with input amount. + * @param to Token to get. + * @param options Additional options. + */ public abstract calculate( from: PriceTokenAmount, to: PriceToken, diff --git a/src/features/instant-trades/instant-trade.ts b/src/features/instant-trades/instant-trade.ts index d3b4460d6e..79394ba2ca 100644 --- a/src/features/instant-trades/instant-trade.ts +++ b/src/features/instant-trades/instant-trade.ts @@ -16,21 +16,42 @@ import { OptionsGasParams, TransactionGasParams } from '@features/instant-trades import { Cache } from 'src/common'; import { TradeType } from 'src/features'; +/** + * Abstract class for all instant trade providers' trades. + */ export abstract class InstantTrade { + /** + * Token to sell with input amount. + */ public abstract readonly from: PriceTokenAmount; + /** + * Token to get with output amount. + */ public abstract readonly to: PriceTokenAmount; + /** + * Gas fee info, including gas limit and gas price. + */ public abstract gasFeeInfo: GasFeeInfo | null; + /** + * Slippage tolerance. Can be mutated after calculation, except for Zrx. + */ public abstract slippageTolerance: number; protected abstract contractAddress: string; // not static because https://github.com/microsoft/TypeScript/issues/34516 protected readonly web3Public: Web3Public; + /** + * Type of instant trade provider. + */ public abstract get type(): TradeType; + /** + * Minimum amount of output token user can get. + */ public get toTokenAmountMin(): PriceTokenAmount { const weiAmountOutMin = this.to.weiAmountMinusSlippage(this.slippageTolerance); return new PriceTokenAmount({ ...this.to.asStruct, weiAmount: weiAmountOutMin }); @@ -40,6 +61,9 @@ export abstract class InstantTrade { return Injector.web3Private.address; } + /** + * Price impact, based on tokens' usd prices. + */ @Cache public get priceImpact(): number | null { return this.from.calculatePriceImpactPercent(this.to); @@ -49,6 +73,9 @@ export abstract class InstantTrade { this.web3Public = Injector.web3PublicService.getWeb3Public(blockchain); } + /** + * Returns true, if allowance is not enough. + */ public async needApprove(fromAddress?: string): Promise { if (!fromAddress) { this.checkWalletConnected(); @@ -66,6 +93,10 @@ export abstract class InstantTrade { return allowance.lt(this.from.weiAmount); } + /** + * Sends approve transaction with connected wallet. + * @param options Transaction options. + */ public async approve(options?: BasicTransactionOptions): Promise { const needApprove = await this.needApprove(); @@ -108,8 +139,17 @@ export abstract class InstantTrade { ); } + /** + * Sends swap transaction with connected wallet. + * If user has not enough allowance, then approve transaction will be called first. + * @param options Transaction options. + */ public abstract swap(options?: SwapTransactionOptions): Promise; + /** + * Builds transaction config, with encoded data. + * @param options Encode transaction options. + */ public abstract encode(options: EncodeTransactionOptions): Promise; protected async checkWalletState(): Promise { diff --git a/src/features/instant-trades/instant-trades-manager.ts b/src/features/instant-trades/instant-trades-manager.ts index 5be2a7100c..5ebd90a2f1 100644 --- a/src/features/instant-trades/instant-trades-manager.ts +++ b/src/features/instant-trades/instant-trades-manager.ts @@ -26,6 +26,9 @@ export type RequiredSwapManagerCalculationOptions = MarkRequired< 'timeout' | 'disabledProviders' >; +/** + * Contains methods to calculate instant trades. + */ export class InstantTradesManager { public static readonly defaultCalculationTimeout = 3_000; @@ -56,6 +59,9 @@ export class InstantTradesManager { return acc; }, {} as Mutable); + /** + * List of all instant trade providers, combined by blockchains. + */ public readonly blockchainTradeProviders: Readonly< Record> > = Object.entries(this.tradeProviders).reduce( @@ -66,6 +72,14 @@ export class InstantTradesManager { {} as Record> ); + /** + * Calculates instant trades. + * @param fromToken Token to sell. + * @param fromAmount Amount to sell. + * @param toToken Token to get. + * @param options Additional options. + * @returns List of calculated instant trades. + */ public async calculateTrade( fromToken: | Token diff --git a/src/features/instant-trades/models/swap-calculation-options.ts b/src/features/instant-trades/models/swap-calculation-options.ts index 918478eb37..7480e00de9 100644 --- a/src/features/instant-trades/models/swap-calculation-options.ts +++ b/src/features/instant-trades/models/swap-calculation-options.ts @@ -1,8 +1,26 @@ import { SwapOptions } from '@features/instant-trades/models/swap-options'; export interface SwapCalculationOptions extends SwapOptions { + /** + * Disabled or enables gas fee calculation. + * `rubicOptimisation` options means, that gas fee is converted into usd + * and subtracted from output token amount, also converted in usd. + */ readonly gasCalculation?: 'disabled' | 'calculate' | 'rubicOptimisation'; + + /** + * If true, then only direct token pairs can be used in calculation. + */ readonly disableMultihops?: boolean; - readonly wrappedAddress?: string; + + /** + * User wallet address, from which transaction will be sent. + */ readonly fromAddress?: string; + + /** + * @internal + * Wrapped native address. + */ + readonly wrappedAddress?: string; } diff --git a/src/features/instant-trades/models/swap-options.ts b/src/features/instant-trades/models/swap-options.ts index 047d45d456..2f31703cc4 100644 --- a/src/features/instant-trades/models/swap-options.ts +++ b/src/features/instant-trades/models/swap-options.ts @@ -1,4 +1,11 @@ export interface SwapOptions { + /** + * Takes value from 0 to 1. + */ readonly slippageTolerance?: number; + + /** + * Transaction deadline, passed in minutes. + */ readonly deadlineMinutes?: number; } From 82dabd7a0eefecec46c237b3b81c58d5d6fbe1df Mon Sep 17 00:00:00 2001 From: ottebrut Date: Mon, 20 Jun 2022 16:25:32 +0300 Subject: [PATCH 05/13] Add classes documentation --- README.md | 12 +- .../blockchain/transaction-reverted.error.ts | 3 + .../errors/blockchain/user-reject.error.ts | 3 + .../cross-chain-max-amount-error.ts | 9 - .../cross-chain-min-amount-error.ts | 9 - src/common/errors/index.ts | 2 +- .../errors/provider/wrong-chain-id.error.ts | 3 + src/common/errors/rubic-sdk.error.ts | 3 + .../errors/swap/unnecessary-approve.error.ts | 6 + src/common/errors/swap/unnecessary-approve.ts | 3 - .../errors/swap/wallet-not-connected.error.ts | 4 + src/common/errors/swap/wrong-network.error.ts | 4 + .../blockchain/models/transaction-options.ts | 17 ++ .../blockchain/tokens/price-token-amount.ts | 36 +++ src/core/blockchain/tokens/price-token.ts | 20 ++ src/core/blockchain/tokens/token.ts | 13 + .../web3-private/web3-private-factory.ts | 4 +- .../blockchain/web3-private/web3-private.ts | 224 ++++-------------- .../blockchain/web3-public/web3-public.ts | 209 ++++++---------- src/core/blockchain/web3-pure/web3-pure.ts | 58 ++--- src/core/sdk/models/configuration.ts | 50 ++++ src/core/sdk/sdk.ts | 38 +++ .../cross-chain/models/cross-chain-options.ts | 1 + .../providers/common/cross-chain-trade.ts | 4 +- .../rubic-cross-chain-trade.ts | 4 + .../symbiosis-cross-chain-trade.ts | 7 + .../oneinch-abstract-provider.ts | 2 +- .../uniswap-v2-abstract-provider.ts | 10 + .../uniswap-v2-abstract-trade.ts | 22 ++ .../uniswap-v3-quoter-controller.ts | 2 +- .../algebra-quoter-controller.ts | 2 +- .../instant-trades/instant-trade-provider.ts | 2 +- src/features/tokens/tokens-manager.ts | 38 +++ 33 files changed, 445 insertions(+), 379 deletions(-) delete mode 100644 src/common/errors/cross-chain/cross-chain-max-amount-error.ts delete mode 100644 src/common/errors/cross-chain/cross-chain-min-amount-error.ts create mode 100644 src/common/errors/swap/unnecessary-approve.error.ts delete mode 100644 src/common/errors/swap/unnecessary-approve.ts diff --git a/README.md b/README.md index 444cee8c4a..a42262d1e0 100644 --- a/README.md +++ b/README.md @@ -480,12 +480,12 @@ interface HttpClient { **RpcProvider description:** -| Property | Type | Description | Default | -|---------------------|----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------| -| mainRpc | `string` | Rpc link. Copy it from your rpc provider (like Infura, Quicknode, Getblock, Moralis, etc.) website. | Not set. | -| spareRpc? | `string` | Same as `mainRpc`. Will be used instead `mainRpc` if mainRpc is out of timeout = `mainPrcTimeout`. | Not set. | -| mainPrcTimeout? | number | Specifies timeout **in ms** after that `mainRpc` will be replaced with `spareRpc` (if `spareRpc` is defined) | 10_000 | -| healthCheckTimeout? | number | Before the `mainRpc` link is applied to the sdk, all the `mainRpc` links will be checked for operability by receiving from the blockchain and verifying the predefined data. If an error occurs during the request, the received data does not match the specified one, or the timeout is exceeded, the `mainRpc` will be replaced with a spare one. This `healthCheckTimeout` parameter allows you to set the maximum allowable timeout when checking the `mainRpc`. | 4_000 | +| Property | Type | Description | Default | +|---------------------|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------| +| mainRpc | `string` | Rpc link. Copy it from your rpc provider (like Infura, Quicknode, Getblock, Moralis, etc.) website. | Not set. | +| spareRpc? | `string` | Same as `mainRpc`. Will be used instead `mainRpc` if mainRpc is out of timeout = `mainPrcTimeout`. | Not set. | +| mainPrcTimeout? | number | Specifies timeout **in ms** after which `mainRpc` will be replaced with `spareRpc` (if `spareRpc` is defined) | 10_000 | +| healthCheckTimeout? | number | Before the `mainRpc` link is applied to the sdk, all the `mainRpc` links will be health-checked by receiving from the blockchain and verifying the predefined data. If an error occurs during the request, the received data does not match the specified one, or the timeout is exceeded, the `mainRpc` will be replaced with a spare one. This `healthCheckTimeout` parameter allows you to set the maximum allowable timeout when checking the `mainRpc`. | 4_000 | --- diff --git a/src/common/errors/blockchain/transaction-reverted.error.ts b/src/common/errors/blockchain/transaction-reverted.error.ts index b4755320bb..2782c2ee81 100644 --- a/src/common/errors/blockchain/transaction-reverted.error.ts +++ b/src/common/errors/blockchain/transaction-reverted.error.ts @@ -1,3 +1,6 @@ import { RubicSdkError } from '@common/errors/rubic-sdk.error'; +/** + * Thrown, if transaction was reverted without specified error. + */ export class TransactionRevertedError extends RubicSdkError {} diff --git a/src/common/errors/blockchain/user-reject.error.ts b/src/common/errors/blockchain/user-reject.error.ts index a693f44402..e9ebd14a45 100644 --- a/src/common/errors/blockchain/user-reject.error.ts +++ b/src/common/errors/blockchain/user-reject.error.ts @@ -1,3 +1,6 @@ import { RubicSdkError } from '@common/errors/rubic-sdk.error'; +/** + * Thrown, when user cancels transaction. + */ export class UserRejectError extends RubicSdkError {} diff --git a/src/common/errors/cross-chain/cross-chain-max-amount-error.ts b/src/common/errors/cross-chain/cross-chain-max-amount-error.ts deleted file mode 100644 index 8a5a8c3d4d..0000000000 --- a/src/common/errors/cross-chain/cross-chain-max-amount-error.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { RubicSdkError } from '@common/errors/rubic-sdk.error'; -import BigNumber from 'bignumber.js'; - -export class CrossChainMaxAmountError extends RubicSdkError { - constructor(maxAmount: BigNumber, tokenSymbol: string) { - super(`Max amount is ${maxAmount.toFixed()} ${tokenSymbol}`); - Object.setPrototypeOf(this, CrossChainMaxAmountError.prototype); - } -} diff --git a/src/common/errors/cross-chain/cross-chain-min-amount-error.ts b/src/common/errors/cross-chain/cross-chain-min-amount-error.ts deleted file mode 100644 index a5b5276061..0000000000 --- a/src/common/errors/cross-chain/cross-chain-min-amount-error.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { RubicSdkError } from '@common/errors/rubic-sdk.error'; -import BigNumber from 'bignumber.js'; - -export class CrossChainMinAmountError extends RubicSdkError { - constructor(minAmount: BigNumber, tokenSymbol: string) { - super(`Min amount is ${minAmount.toFixed()} ${tokenSymbol}`); - Object.setPrototypeOf(this, CrossChainMinAmountError.prototype); - } -} diff --git a/src/common/errors/index.ts b/src/common/errors/index.ts index 72d701a84f..bb5d0f5545 100644 --- a/src/common/errors/index.ts +++ b/src/common/errors/index.ts @@ -6,7 +6,7 @@ export { InsufficientLiquidityError } from './swap/insufficient-liquidity.error' export { LowSlippageError } from './swap/low-slippage.error'; export { LowSlippageDeflationaryTokenError } from './swap/low-slippage-deflationary-token.error'; export { NotSupportedBlockchain } from './swap/not-supported-blockchain'; -export { UnnecessaryApprove } from './swap/unnecessary-approve'; +export { UnnecessaryApproveError } from 'src/common/errors/swap/unnecessary-approve.error'; export { WalletNotConnectedError } from './swap/wallet-not-connected.error'; export { WrongNetworkError } from './swap/wrong-network.error'; export { WrongChainIdError } from './provider/wrong-chain-id.error'; diff --git a/src/common/errors/provider/wrong-chain-id.error.ts b/src/common/errors/provider/wrong-chain-id.error.ts index 5033eddf79..db9d1bbb7b 100644 --- a/src/common/errors/provider/wrong-chain-id.error.ts +++ b/src/common/errors/provider/wrong-chain-id.error.ts @@ -1,3 +1,6 @@ import { RubicSdkError } from '@common/errors/rubic-sdk.error'; +/** + * Thrown, when provided chain id does not match real one, set in wallet. + */ export class WrongChainIdError extends RubicSdkError {} diff --git a/src/common/errors/rubic-sdk.error.ts b/src/common/errors/rubic-sdk.error.ts index 593312840a..98ae73aa65 100644 --- a/src/common/errors/rubic-sdk.error.ts +++ b/src/common/errors/rubic-sdk.error.ts @@ -1 +1,4 @@ +/** + * Base class for all errors that can be thrown in sdk. + */ export class RubicSdkError extends Error {} diff --git a/src/common/errors/swap/unnecessary-approve.error.ts b/src/common/errors/swap/unnecessary-approve.error.ts new file mode 100644 index 0000000000..c86e92effa --- /dev/null +++ b/src/common/errors/swap/unnecessary-approve.error.ts @@ -0,0 +1,6 @@ +import { RubicSdkError } from '@common/errors/rubic-sdk.error'; + +/** + * Thrown, when approve method is called, but there is enough allowance. + */ +export class UnnecessaryApproveError extends RubicSdkError {} diff --git a/src/common/errors/swap/unnecessary-approve.ts b/src/common/errors/swap/unnecessary-approve.ts deleted file mode 100644 index 0e71aeee67..0000000000 --- a/src/common/errors/swap/unnecessary-approve.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { RubicSdkError } from '@common/errors/rubic-sdk.error'; - -export class UnnecessaryApprove extends RubicSdkError {} diff --git a/src/common/errors/swap/wallet-not-connected.error.ts b/src/common/errors/swap/wallet-not-connected.error.ts index 53e6e1845d..69cfbe6f15 100644 --- a/src/common/errors/swap/wallet-not-connected.error.ts +++ b/src/common/errors/swap/wallet-not-connected.error.ts @@ -1,3 +1,7 @@ import { RubicSdkError } from '@common/errors/rubic-sdk.error'; +/** + * Thrown, when method, which requires connected wallet, is called without + * wallet being connected. + */ export class WalletNotConnectedError extends RubicSdkError {} diff --git a/src/common/errors/swap/wrong-network.error.ts b/src/common/errors/swap/wrong-network.error.ts index ffe218b551..767b7cc276 100644 --- a/src/common/errors/swap/wrong-network.error.ts +++ b/src/common/errors/swap/wrong-network.error.ts @@ -1,3 +1,7 @@ import { RubicSdkError } from '@common/errors/rubic-sdk.error'; +/** + * Thrown during swap, if user's selected network does not match source blockchain + * in swap parameters. + */ export class WrongNetworkError extends RubicSdkError {} diff --git a/src/core/blockchain/models/transaction-options.ts b/src/core/blockchain/models/transaction-options.ts index 5d500a2e5e..7be70226bb 100644 --- a/src/core/blockchain/models/transaction-options.ts +++ b/src/core/blockchain/models/transaction-options.ts @@ -1,9 +1,26 @@ import BigNumber from 'bignumber.js'; export type TransactionOptions = { + /** + * Callback to execute when transaction enters the mempool. + * @param hash Transaction hash. + */ onTransactionHash?: (hash: string) => void; + + /** + * Encoded data, which will be executed in transaction. + */ data?: string; + + /** + * Gas limit. + */ gas?: BigNumber | string; + gasPrice?: BigNumber | string; + + /** + * Native token amount in wei. + */ value?: BigNumber | string; }; diff --git a/src/core/blockchain/tokens/price-token-amount.ts b/src/core/blockchain/tokens/price-token-amount.ts index 01610ba46e..34833b126e 100644 --- a/src/core/blockchain/tokens/price-token-amount.ts +++ b/src/core/blockchain/tokens/price-token-amount.ts @@ -17,7 +17,14 @@ export type PriceTokenAmountStruct = ConstructorParameters[nu export type PriceTokenAmountBaseStruct = TokenBaseStruct & ({ weiAmount: BigNumber } | { tokenAmount: BigNumber }); +/** + * Contains token structure with price and amount. + */ export class PriceTokenAmount extends PriceToken { + /** + * Creates PriceTokenAmount based on token's address and blockchain. + * @param tokenAmountBaseStruct Base token structure with amount. + */ public static async createToken( tokenAmountBaseStruct: PriceTokenAmountBaseStruct ): Promise { @@ -28,6 +35,10 @@ export class PriceTokenAmount extends PriceToken { }); } + /** + * Creates PriceTokenAmount, fetching token's price. + * @param tokenAmount Token structure with amount. + */ public static async createFromToken( tokenAmount: TokenStruct & ({ weiAmount: BigNumber } | { tokenAmount: BigNumber }) ): Promise { @@ -40,18 +51,30 @@ export class PriceTokenAmount extends PriceToken { private readonly _weiAmount: BigNumber; + /** + * Gets set amount in wei. + */ get weiAmount(): BigNumber { return new BigNumber(this._weiAmount); } + /** + * Gets set amount in wei and converted to string. + */ get stringWeiAmount(): string { return this._weiAmount.toFixed(0); } + /** + * Gets set amount with decimals. + */ get tokenAmount(): BigNumber { return new BigNumber(this._weiAmount).div(new BigNumber(10).pow(this.decimals)); } + /** + * Serializes priceTokenAmount to struct object. + */ public get asStructWithAmount(): PriceTokenAmountStruct { return { ...this, @@ -71,10 +94,18 @@ export class PriceTokenAmount extends PriceToken { } } + /** + * Returns wei amount decreased by (1 - slippage) times. + * @param slippage Slippage in range from 0 to 1. + */ public weiAmountMinusSlippage(slippage: number): BigNumber { return new BigNumber(this._weiAmount).multipliedBy(new BigNumber(1).minus(slippage)); } + /** + * Returns wei amount increased by (1 - slippage) times. + * @param slippage Slippage in range from 0 to 1. + */ public weiAmountPlusSlippage(slippage: number): BigNumber { return new BigNumber(this._weiAmount).multipliedBy(new BigNumber(1).plus(slippage)); } @@ -94,6 +125,11 @@ export class PriceTokenAmount extends PriceToken { return new PriceTokenAmount({ ...this, ...tokenStruct }); } + /** + * Calculates trade price impact percent if instance token is selling token, and parameter is buying token. + * If selling usd amount is less than buying usd amount, returns 0. + * @param toToken Token to buy. + */ public calculatePriceImpactPercent(toToken: PriceTokenAmount): number | null { if ( !this.price || diff --git a/src/core/blockchain/tokens/price-token.ts b/src/core/blockchain/tokens/price-token.ts index 6fdc8ce8ef..04f34c8703 100644 --- a/src/core/blockchain/tokens/price-token.ts +++ b/src/core/blockchain/tokens/price-token.ts @@ -5,7 +5,14 @@ import BigNumber from 'bignumber.js'; export type PriceTokenStruct = ConstructorParameters[number] & { price: BigNumber }; +/** + * Contains token structure with price in usd per 1 unit. + */ export class PriceToken extends Token { + /** + * Creates PriceToken based on token's address and blockchain. + * @param tokenBaseStruct Base token structure. + */ public static async createToken(tokenBaseStruct: TokenBaseStruct): Promise { const { coingeckoApi } = Injector; @@ -16,6 +23,10 @@ export class PriceToken extends Token { return new PriceToken({ ...results[0], price: results[1] }); } + /** + * Creates PriceToken, fetching token's price. + * @param token Token structure. + */ public static async createFromToken(token: TokenStruct): Promise { const { coingeckoApi } = Injector; @@ -30,6 +41,9 @@ export class PriceToken extends Token { return this._price; } + /** + * Serializes priceToken and its price to struct object. + */ public get asStruct(): PriceTokenStruct { return { ...this, @@ -42,6 +56,9 @@ export class PriceToken extends Token { this._price = tokenStruct.price; } + /** + * Fetches current token price and saves it into token. + */ public async getAndUpdateTokenPrice(): Promise { await this.updateTokenPrice(); return this.price; @@ -52,6 +69,9 @@ export class PriceToken extends Token { this._price = await coingeckoApi.getTokenPrice({ ...this }); } + /** + * Clones token with fetching new price. + */ public async cloneAndCreate(tokenStruct?: Partial): Promise { const { coingeckoApi } = Injector; diff --git a/src/core/blockchain/tokens/token.ts b/src/core/blockchain/tokens/token.ts index c36413c692..350e27255a 100644 --- a/src/core/blockchain/tokens/token.ts +++ b/src/core/blockchain/tokens/token.ts @@ -13,7 +13,14 @@ export type TokenStruct = { decimals: number; }; +/** + * Contains main token's fields. + */ export class Token { + /** + * Creates Token based on token's address and blockchain. + * @param tokenBaseStruct Base token structure. + */ public static async createToken(tokenBaseStruct: TokenBaseStruct): Promise { const web3Public = Injector.web3PublicService.getWeb3Public(tokenBaseStruct.blockchain); const tokenInfo = await web3Public.callForTokenInfo(tokenBaseStruct.address); @@ -30,6 +37,9 @@ export class Token { }); } + /** + * Creates array of Tokens based on tokens' addresses and blockchain. + */ public static async createTokens( tokensAddresses: string[] | ReadonlyArray, blockchain: BlockchainName @@ -61,6 +71,9 @@ export class Token { }); } + /** + * Maps provided tokens to their addresses. + */ public static tokensToAddresses(tokens: Token[]): string[] { return tokens.map(token => token.address); } diff --git a/src/core/blockchain/web3-private/web3-private-factory.ts b/src/core/blockchain/web3-private/web3-private-factory.ts index 700c723da1..d0f99d1432 100644 --- a/src/core/blockchain/web3-private/web3-private-factory.ts +++ b/src/core/blockchain/web3-private/web3-private-factory.ts @@ -53,7 +53,7 @@ export class Web3PrivateFactory { constructor( private readonly core: provider | Web3, - private readonly walletAddrrss: string, + private readonly walletAddress: string, private readonly chainId: number ) {} @@ -95,7 +95,7 @@ export class Web3PrivateFactory { throw new RubicSdkError('Web3 is not initialized'); } - this.address = this.web3.utils.toChecksumAddress(this.walletAddrrss); + this.address = this.web3.utils.toChecksumAddress(this.walletAddress); } private createWeb3PrivateInstance(): Web3Private { diff --git a/src/core/blockchain/web3-private/web3-private.ts b/src/core/blockchain/web3-private/web3-private.ts index 1b5da2c7f4..af5e34fa08 100644 --- a/src/core/blockchain/web3-private/web3-private.ts +++ b/src/core/blockchain/web3-private/web3-private.ts @@ -14,13 +14,14 @@ import { FailedToCheckForTransactionReceiptError } from '@common/errors/swap/fai import { Web3Pure } from 'src/core'; /** - * Class containing methods for executing the functions of contracts and sending transactions in order to change the state of the blockchain. + * Class containing methods for executing the functions of contracts + * and sending transactions in order to change the state of the blockchain. * To get information from the blockchain use {@link Web3Public}. */ export class Web3Private { /** - * @description converts number, string or BigNumber value to integer string - * @param amount value to convert + * Converts number, string or BigNumber value to integer string. + * @param amount Value to convert. */ private static stringifyAmount(amount: number | string | BigNumber): string { const bnAmount = new BigNumber(amount); @@ -34,35 +35,35 @@ export class Web3Private { private readonly APPROVE_GAS_LIMIT = 60_000; /** - * @description instance of web3, initialized with ethereum wallet, e.g. Metamask, WalletConnect + * Instance of web3, initialized with ethereum wallet, e.g. Metamask, WalletConnect. */ private readonly web3: Web3; /** - * @description current wallet provider address + * Current wallet provider address. */ public get address(): string { return this.walletConnectionConfiguration.address; } /** - * @description current wallet blockchainName + * Current wallet blockchain name. */ public get blockchainName(): string { return this.walletConnectionConfiguration.blockchainName; } /** - * @param walletConnectionConfiguration provider that implements {@link WalletConnectionConfiguration} interface. - * The provider must contain an instance of web3, initialized with ethereum wallet, e.g. Metamask, WalletConnect + * @param walletConnectionConfiguration Provider that implements {@link WalletConnectionConfiguration} interface. + * The provider must contain an instance of web3, initialized with ethereum wallet, e.g. Metamask, WalletConnect. */ constructor(private readonly walletConnectionConfiguration: WalletConnectionConfiguration) { this.web3 = walletConnectionConfiguration.web3; } /** - * @description parse web3 error by its code - * @param err web3 error to parse + * Parses web3 error by its code. + * @param err Web3 error to parse. */ private static parseError(err: Web3Error): RubicSdkError { if (err.message.includes('Transaction has been reverted by the EVM')) { @@ -87,13 +88,12 @@ export class Web3Private { } /** - * @description sends ERC-20 tokens and resolve the promise when the transaction is included in the block - * @param contractAddress address of the smart-contract corresponding to the token - * @param toAddress token receiver address - * @param amount integer tokens amount to send (pre-multiplied by 10 ** decimals) - * @param [options] additional options - * @param [options.onTransactionHash] callback to execute when transaction enters the mempool - * @return transaction receipt + * Sends ERC-20 tokens and resolves the promise when the transaction is included in the block. + * @param contractAddress Address of the smart-contract corresponding to the token. + * @param toAddress Token receiver address. + * @param amount Integer tokens amount to send in wei. + * @param [options] Additional options. + * @returns Transaction receipt. */ public async transferTokens( contractAddress: string, @@ -123,53 +123,11 @@ export class Web3Private { } /** - * @description sends ERC-20 tokens and resolve the promise without waiting for the transaction to be included in the block - * @param contractAddress address of the smart-contract corresponding to the token - * @param toAddress token receiver address - * @param amount integer tokens amount to send (pre-multiplied by 10 ** decimals) - * @param [options] additional options - * @param [options.onTransactionHash] callback to execute when transaction enters the mempool - * @return transaction hash - */ - public async transferTokensWithOnHashResolve( - contractAddress: string, - toAddress: string, - amount: string | BigNumber, - options: TransactionOptions = {} - ): Promise { - const contract = new this.web3.eth.Contract(ERC20_TOKEN_ABI as AbiItem[], contractAddress); - - return new Promise((resolve, reject) => { - contract.methods - .transfer(toAddress, Web3Private.stringifyAmount(amount)) - .send({ - from: this.address, - ...(options.gas && { gas: Web3Private.stringifyAmount(options.gas) }), - ...(options.gasPrice && { - gasPrice: Web3Private.stringifyAmount(options.gasPrice) - }) - }) - .on('transactionHash', (hash: string) => resolve(hash)) - .on('error', (err: Web3Error) => { - console.error(`Tokens transfer error. ${err}`); - reject(Web3Private.parseError(err)); - }); - }); - } - - /** - * @description tries to send Eth in transaction and resolve the promise when the transaction is included in the block or rejects the error - * @param toAddress Eth receiver address - * @param value amount in Eth units - * @param [options] additional options - * @param [options.onTransactionHash] callback to execute when transaction enters the mempool - * @param [options.inWei = false] boolean flag for determining the input parameter "value" in Wei - * @param [options.data] data for calling smart contract methods. - * Use this field only if you are receiving data from a third-party api. - * When manually calling contract methods, use executeContractMethod() - * @param [options.gas] transaction gas limit in absolute gas units - * @param [options.gasPrice] price of gas unit in wei - * @return transaction receipt + * Tries to send Eth in transaction and resolve the promise when the transaction is included in the block or rejects the error. + * @param toAddress Eth receiver address. + * @param value Native token amount in wei. + * @param [options] Additional options. + * @returns Transaction receipt. */ public async trySendTransaction( toAddress: string, @@ -195,18 +153,11 @@ export class Web3Private { } /** - * @description sends Eth in transaction and resolve the promise when the transaction is included in the block - * @param toAddress Eth receiver address - * @param value amount in Eth units - * @param [options] additional options - * @param [options.onTransactionHash] callback to execute when transaction enters the mempool - * @param [options.inWei = false] boolean flag for determining the input parameter "value" in Wei - * @param [options.data] data for calling smart contract methods. - * Use this field only if you are receiving data from a third-party api. - * When manually calling contract methods, use executeContractMethod() - * @param [options.gas] transaction gas limit in absolute gas units - * @param [options.gasPrice] price of gas unit in wei - * @return transaction receipt + * Sends Eth in transaction and resolve the promise when the transaction is included in the block. + * @param toAddress Eth receiver address. + * @param value Native token amount in wei. + * @param [options] Additional options. + * @returns Transaction receipt. */ public async sendTransaction( toAddress: string, @@ -235,46 +186,12 @@ export class Web3Private { } /** - * @description sends Eth in transaction and resolve the promise without waiting for the transaction to be included in the block - * @param toAddress Eth receiver address - * @param value amount in Eth units - * @param [options] additional options - * @param [options.inWei = false] boolean flag for determining the input parameter "value" in Wei - * @return transaction hash - */ - public async sendTransactionWithOnHashResolve( - toAddress: string, - value: string | BigNumber, - options: TransactionOptions = {} - ): Promise { - return new Promise((resolve, reject) => { - this.web3.eth - .sendTransaction({ - from: this.address, - to: toAddress, - value: Web3Private.stringifyAmount(value), - ...(options.gas && { gas: Web3Private.stringifyAmount(options.gas) }), - ...(options.gasPrice && { - gasPrice: Web3Private.stringifyAmount(options.gasPrice) - }), - ...(options.data && { data: options.data }) - }) - .on('transactionHash', hash => resolve(hash)) - .on('error', err => { - console.error(`Tokens transfer error. ${err}`); - reject(Web3Private.parseError(err as Web3Error)); - }); - }); - } - - /** - * @description executes approve method in ERC-20 token contract - * @param tokenAddress address of the smart-contract corresponding to the token - * @param spenderAddress wallet or contract address to approve - * @param value integer value to approve (pre-multiplied by 10 ** decimals) - * @param [options] additional options - * @param [options.onTransactionHash] callback to execute when transaction enters the mempool - * @return approval transaction receipt + * Executes approve method in ERC-20 token contract. + * @param tokenAddress Address of the smart-contract corresponding to the token. + * @param spenderAddress Wallet or contract address to approve. + * @param value Token amount to approve in wei. + * @param [options] Additional options. + * @returns Approval transaction receipt. */ public async approveTokens( tokenAddress: string, @@ -317,15 +234,13 @@ export class Web3Private { } /** - * @description tries to execute method of smart-contract and resolve the promise when the transaction is included in the block or rejects the error - * @param contractAddress address of smart-contract which method is to be executed - * @param contractAbi abi of smart-contract which method is to be executed - * @param methodName executing method name - * @param methodArguments executing method arguments - * @param [options] additional options - * @param [options.value] amount in Wei amount to be attached to the transaction - * @param [options.gas] gas limit to be attached to the transaction - * @param allowError Check error and decides to execute contact if it needed. + * Tries to execute method of smart-contract and resolve the promise when the transaction is included in the block or rejects the error. + * @param contractAddress Address of smart-contract which method is to be executed. + * @param contractAbi Abi of smart-contract which method is to be executed. + * @param methodName Method name to execute. + * @param methodArguments Method arguments. + * @param [options] Additional options. + * @param allowError Check error and decides to execute contact if error is allowed. */ public async tryExecuteContractMethod( contractAddress: string, @@ -372,15 +287,13 @@ export class Web3Private { } /** - * @description executes method of smart-contract and resolve the promise when the transaction is included in the block - * @param contractAddress address of smart-contract which method is to be executed - * @param contractAbi abi of smart-contract which method is to be executed - * @param methodName executing method name - * @param methodArguments executing method arguments - * @param [options] additional options - * @param [options.onTransactionHash] callback to execute when transaction enters the mempool - * @param [options.value] amount in Wei amount to be attached to the transaction - * @return smart-contract method returned value + * Executes method of smart-contract and resolve the promise when the transaction is included in the block. + * @param contractAddress Address of smart-contract which method is to be executed. + * @param contractAbi Abi of smart-contract which method is to be executed. + * @param methodName Method name to execute. + * @param methodArguments Method arguments. + * @param [options] Additional options. + * @returns Smart-contract method returned value. */ public async executeContractMethod( contractAddress: string, @@ -415,46 +328,9 @@ export class Web3Private { } /** - * @description executes method of smart-contract and resolve the promise without waiting for the transaction to be included in the block - * @param contractAddress address of smart-contract which method is to be executed - * @param contractAbi abi of smart-contract which method is to be executed - * @param methodName executing method name - * @param methodArguments executing method arguments - * @param [options] additional options - * @param [options.onTransactionHash] callback to execute when transaction enters the mempool - * @param [options.value] amount in Wei amount to be attached to the transaction - * @return smart-contract method returned value - */ - public executeContractMethodWithOnHashResolve( - contractAddress: string, - contractAbi: AbiItem[], - methodName: string, - methodArguments: unknown[], - options: TransactionOptions = {} - ): Promise { - const contract = new this.web3.eth.Contract(contractAbi, contractAddress); - - return new Promise((resolve, reject) => { - contract.methods[methodName](...methodArguments) - .send({ - from: this.address, - ...(options.gas && { gas: Web3Private.stringifyAmount(options.gas) }), - ...(options.gasPrice && { - gasPrice: Web3Private.stringifyAmount(options.gasPrice) - }) - }) - .on('transactionHash', resolve) - .on('error', (err: Web3Error) => { - console.error(`Tokens approve error. ${err}`); - reject(Web3Private.parseError(err)); - }); - }); - } - - /** - * @description removes approval for token use - * @param tokenAddress tokenAddress address of the smart-contract corresponding to the token - * @param spenderAddress wallet or contract address to approve + * Removes approval for token. + * @param tokenAddress Address of the smart-contract corresponding to the token. + * @param spenderAddress Wallet or contract address to approve. */ public async unApprove( tokenAddress: string, diff --git a/src/core/blockchain/web3-public/web3-public.ts b/src/core/blockchain/web3-public/web3-public.ts index 04f0738185..ec570aff10 100644 --- a/src/core/blockchain/web3-public/web3-public.ts +++ b/src/core/blockchain/web3-public/web3-public.ts @@ -20,7 +20,6 @@ import { RpcResponse } from '@core/blockchain/web3-public/models/rpc-response'; import { Web3Pure } from '@core/blockchain/web3-pure/web3-pure'; import Web3 from 'web3'; import BigNumber from 'bignumber.js'; -import { Method } from 'web3-core-method'; import { Transaction, provider as Provider, BlockNumber, HttpProvider } from 'web3-core'; import { AbiItem } from 'web3-utils'; import { BlockTransactionString } from 'web3-eth'; @@ -41,9 +40,9 @@ export class Web3Public { private readonly clearController: { clear: boolean } = { clear: false }; /** - * @param web3 web3 instance initialized with ethereum provider, e.g. rpc link - * @param blockchainName blockchain in which you need to execute requests - * @param [httpClient=axios] http client that implements {@link HttpClient} interface + * @param web3 Web3 instance initialized with ethereum provider, e.g. rpc link. + * @param blockchainName Blockchain in which you need to execute requests. + * @param [httpClient=axios] Http client that implements {@link HttpClient} interface. */ constructor( private readonly web3: Web3, @@ -52,9 +51,9 @@ export class Web3Public { ) {} /** - * HealthCheck current rpc node - * @param timeoutMs acceptable node response timeout - * @return null if healthcheck is not defined for current blockchain, else is node works status + * Health-check current rpc node. + * @param timeoutMs Acceptable node response timeout. + * @returns Null if healthcheck is not defined for current blockchain, else node health status. */ public async healthCheck(timeoutMs: number = 4000): Promise { if (!isBlockchainHealthcheckAvailable(this.blockchainName)) { @@ -90,28 +89,27 @@ export class Web3Public { } /** - * @description set new provider to web3 instance - * @param provider new web3 provider, e.g. rpc link + * Sets new provider to web3 instance. + * @param provider New web3 provider, e.g. rpc link. */ public setProvider(provider: Provider): void { this.web3.setProvider(provider); } /** - * @description gets block by blockId - * @param [blockId] block id: hash, number ... Default is 'latest'. - * @returns {BlockTransactionString} block by blockId parameter. + * Gets block by block id. + * @param [blockId] Block id: hash, number ... Default is 'latest'. + * @returns Block by blockId parameter. */ public getBlock(blockId: BlockNumber | string = 'latest'): Promise { return this.web3.eth.getBlock(blockId); } /** - * @description gets account eth or token balance as integer (multiplied to 10 ** decimals) - * @param address wallet address whose balance you want to find out - * @param [tokenAddress] address of the smart-contract corresponding to the token, or {@link NATIVE_TOKEN_ADDRESS}. - * If not passed the balance in the native currency will be returned. - * @returns address eth or token balance as integer (multiplied to 10 ** decimals) + * Gets account native or ERC-20 token balance in wei. + * @param address Wallet address, whose balance you want to find out. + * @param tokenAddress Address of the smart-contract corresponding to the token, + * {@link NATIVE_TOKEN_ADDRESS} is used as default. */ public async getBalance(address: string, tokenAddress?: string): Promise { let balance; @@ -124,10 +122,9 @@ export class Web3Public { } /** - * @description gets ERC-20 tokens balance as integer (multiplied to 10 ** decimals) - * @param tokenAddress address of the smart-contract corresponding to the token - * @param address wallet address whose balance you want to find out - * @returns address tokens balance as integer (multiplied to 10 ** decimals) + * Gets ERC-20 tokens balance in wei. + * @param tokenAddress Address of the smart-contract corresponding to the token. + * @param address Wallet address, whose balance you want to find out. */ public async getTokenBalance(address: string, tokenAddress: string): Promise { const contract = new this.web3.eth.Contract(ERC20_TOKEN_ABI as AbiItem[], tokenAddress); @@ -137,14 +134,14 @@ export class Web3Public { } /** - * @description predicts the volume of gas required to execute the contract method - * @param contractAbi abi of smart-contract - * @param contractAddress address of smart-contract - * @param methodName method whose execution gas number is to be calculated - * @param methodArguments arguments of the executed contract method - * @param fromAddress the address for which the gas calculation will be called - * @param [value] The value transferred for the call “transaction” in wei. - * @return The gas amount estimated + * Predicts the volume of gas required to execute the contract method. + * @param contractAbi Abi of smart-contract. + * @param contractAddress Address of smart-contract. + * @param methodName Method which execution gas limit is to be calculated. + * @param methodArguments Arguments of the contract method. + * @param fromAddress The address for which the gas calculation will be called. + * @param value The value transferred for the call “transaction” in wei. + * @returns Estimated gas limit. */ public async getEstimatedGas( contractAbi: AbiItem[], @@ -170,16 +167,16 @@ export class Web3Public { } /** - * @description calculates the average price per unit of gas according to web3 - * @return average gas price in Wei + * Calculates the average price per unit of gas according to web3. + * @returns Average gas price in wei. */ public async getGasPrice(): Promise { return this.web3.eth.getGasPrice(); } /** - * @description calculates the average price per unit of gas according to web3 - * @return average gas price in ETH + * Calculates the average price per unit of gas according to web3. + * @returns Average gas price with decimals. */ public async getGasPriceInETH(): Promise { const gasPrice = await this.web3.eth.getGasPrice(); @@ -187,22 +184,11 @@ export class Web3Public { } /** - * @description calculates the gas fee using average price per unit of gas according to web3 and Eth price according to coingecko - * @param gasLimit gas limit - * @param etherPrice price of Eth unit - * @return gas fee in usd$ - */ - public async getGasFee(gasLimit: BigNumber, etherPrice: BigNumber): Promise { - const gasPrice = await this.getGasPriceInETH(); - return gasPrice.multipliedBy(gasLimit).multipliedBy(etherPrice); - } - - /** - * @description executes allowance method in ERC-20 token contract - * @param tokenAddress address of the smart-contract corresponding to the token - * @param spenderAddress wallet or contract address, allowed to spend - * @param ownerAddress wallet address to spend from - * @return tokens amount, allowed to be spent + * Calls allowance method in ERC-20 token contract. + * @param tokenAddress Address of the smart-contract corresponding to the token. + * @param spenderAddress Wallet or contract address, allowed to spend. + * @param ownerAddress Wallet address to spend from. + * @returns Token's amount, allowed to be spent. */ public async getAllowance( tokenAddress: string, @@ -218,30 +204,11 @@ export class Web3Public { } /** - * @description gets mined transaction gas fee in Ether - * @param hash transaction hash - * @return transaction gas fee in Wei or null if transaction is not mined - */ - public async getTransactionGasFee(hash: string): Promise { - const transaction = await this.getTransactionByHash(hash); - const receipt = await this.web3.eth.getTransactionReceipt(hash); - - if (!transaction || !receipt) { - return null; - } - - const gasPrice = new BigNumber(transaction.gasPrice); - const gasLimit = new BigNumber(receipt.gasUsed); - - return gasPrice.multipliedBy(gasLimit); - } - - /** - * @description get a transaction by hash in several attempts - * @param hash hash of the target transaction - * @param attempt current attempt number - * @param attemptsLimit maximum allowed number of attempts - * @param delay ms delay before next attempt + * Gets a transaction by hash in several attempts. + * @param hash Hash of the target transaction. + * @param attempt Current attempt number. + * @param attemptsLimit Maximum allowed number of attempts. + * @param delay Delay before next attempt in ms. */ public async getTransactionByHash( hash: string, @@ -267,14 +234,14 @@ export class Web3Public { } /** - * @description call smart-contract pure method of smart-contract and returns its output value - * @param contractAddress address of smart-contract which method is to be executed - * @param contractAbi abi of smart-contract which method is to be executed - * @param methodName calling method name - * @param [options] additional options - * @param [options.from] the address the call “transaction” should be made from - * @param [options.methodArguments] executing method arguments - * @return smart-contract pure method returned value + * Calls pure method of smart-contract and returns its output value. + * @param contractAddress Address of smart-contract which method is to be executed. + * @param contractAbi Abi of smart-contract which method is to be executed. + * @param methodName Called method name. + * @param [options] Additional options. + * @param [options.from] The address the call should be made from. + * @param [options.methodArguments] Method arguments. + * @param [options.value] Native token amount to be passed. */ public async callContractMethod( contractAddress: string, @@ -295,9 +262,9 @@ export class Web3Public { } /** - * @description get balance of multiple tokens via multicall - * @param address wallet address - * @param tokensAddresses tokens addresses + * Gets balances of multiple tokens via multicall. + * @param address Wallet address, which contains tokens. + * @param tokensAddresses Tokens addresses. */ public async getTokensBalances( address: string, @@ -338,8 +305,8 @@ export class Web3Public { * Uses multicall to make several calls of one method in one contract. * @param contractAddress Target contract address. * @param contractAbi Target contract abi. - * @param methodName target method name - * @param methodCallsArguments list method calls parameters arrays + * @param methodName Method name. + * @param methodCallsArguments Method parameters array, for each method call. */ public async multicallContractMethod( contractAddress: string, @@ -429,11 +396,11 @@ export class Web3Public { } /** - * @description Checks if the specified address contains the required amount of these tokens. - * Throws an InsufficientFundsError if the balance is insufficient - * @param token token balance for which you need to check - * @param amount required balance - * @param userAddress the address where the required balance should be + * Checks if the specified address contains the required amount of these tokens. + * Throws an InsufficientFundsError if balance is insufficient. + * @param token Token, which balance you need to check. + * @param amount Required balance. + * @param userAddress The address, where the required balance should be. */ public async checkBalance( token: { address: string; symbol: string; decimals: number }, @@ -528,15 +495,15 @@ export class Web3Public { } /** - * @description get estimated gas of several contract method execution via rpc batch request - * @param abi contract ABI - * @param contractAddress contract address - * @param fromAddress sender address - * @param callsData transactions parameters - * @returns list of contract execution estimated gases. - * if the execution of the method in the real blockchain would not be reverted, + * Get estimated gas of several contract method executions via rpc batch request. + * @param abi Contract ABI. + * @param contractAddress Contract address. + * @param fromAddress Sender address. + * @param callsData Transactions parameters. + * @returns List of contract execution estimated gases. + * If the execution of the method in the real blockchain would not be reverted, * then the list item would be equal to the predicted gas limit. - * Else (if you have not enough balance, allowance ...) then the list item would be equal to null + * Else (if you have not enough balance, allowance ...) then the list item would be equal to null. */ public async batchEstimatedGas( abi: AbiItem[], @@ -572,40 +539,12 @@ export class Web3Public { } /** - * @description send batch request via web3 - * @see {@link https://web3js.readthedocs.io/en/v1.3.0/web3-eth.html#batchrequest|Web3BatchRequest} - * @param calls Web3 method calls - * @param callsParams ethereum method transaction parameters - * @returns batch request call result sorted in order of input parameters - */ - public web3BatchRequest( - calls: { request: (...params: unknown[]) => Method }[], - callsParams: Object[] - ): Promise { - const batch = new this.web3.BatchRequest(); - const promises: Promise[] = calls.map( - (call, index) => - new Promise((resolve, reject) => - batch.add( - call.request({ ...callsParams[index] }, (error: Error, result: T) => - error ? reject(error) : resolve(result) - ) - ) - ) - ); - - batch.execute(); - - return Promise.all(promises); - } - - /** - * @description send batch request to rpc provider directly + * Sends batch request to rpc provider directly. * @see {@link https://playground.open-rpc.org/?schemaUrl=https://raw.githubusercontent.com/ethereum/eth1.0-apis/assembled-spec/openrpc.json&uiSchema%5BappBar%5D%5Bui:splitView%5D=false&uiSchema%5BappBar%5D%5Bui:input%5D=false&uiSchema%5BappBar%5D%5Bui:examplesDropdown%5D=false|EthereumJSON-RPC} - * @param rpcCallsData rpc methods and parameters list - * @returns rpc batch request call result sorted in order of input 1parameters + * @param rpcCallsData Rpc methods and parameters list. + * @returns Rpc batch request call result sorted in order of input parameters. */ - public async rpcBatchRequest( + private async rpcBatchRequest( rpcCallsData: { rpcMethod: string; params: Object; @@ -630,9 +569,9 @@ export class Web3Public { } /** - * @description execute multiplie calls in the single contract call - * @param calls multicall calls data list - * @return result of calls execution + * Executes multiple calls in the single contract call. + * @param calls Multicall calls data list. + * @returns Result of calls execution. */ private async multicall(calls: Call[]): Promise { const contract = new this.web3.eth.Contract( @@ -643,7 +582,7 @@ export class Web3Public { } /** - * @description returns httpClient if it exists or imports the axios client + * Returns httpClient if it exists or imports the axios client. */ private async getHttpClient(): Promise { if (!this.httpClient) { diff --git a/src/core/blockchain/web3-pure/web3-pure.ts b/src/core/blockchain/web3-pure/web3-pure.ts index d1fec0fc31..41944af6c2 100644 --- a/src/core/blockchain/web3-pure/web3-pure.ts +++ b/src/core/blockchain/web3-pure/web3-pure.ts @@ -3,16 +3,19 @@ import { NATIVE_TOKEN_ADDRESS } from '@core/blockchain/constants/native-token-ad import BigNumber from 'bignumber.js'; import Web3 from 'web3'; import { TransactionConfig } from 'web3-core'; -import { toChecksumAddress, isAddress, toWei, fromWei, AbiItem, fromAscii } from 'web3-utils'; +import { toChecksumAddress, isAddress, AbiItem, fromAscii } from 'web3-utils'; import { TransactionGasParams } from '@features/instant-trades/models/gas-params'; +/** + * Contains common methods, connected with web3, e.g. wei conversion, encoding data, etc. + */ export class Web3Pure { public static readonly ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'; private static web3Eth = new Web3().eth; /** - * @description gets address of native coin {@link NATIVE_TOKEN_ADDRESS} + * Gets address of native coin {@link NATIVE_TOKEN_ADDRESS}. */ static get nativeTokenAddress(): string { return NATIVE_TOKEN_ADDRESS; @@ -35,26 +38,26 @@ export class Web3Pure { } /** - * @description convert amount from Ether to Wei units - * @param amount amount to convert - * @param [decimals=18] token decimals + * Converts amount from Ether to Wei units. + * @param amount Amount to convert. + * @param decimals Token decimals. */ static toWei(amount: BigNumber | string | number, decimals = 18): string { return new BigNumber(amount || 0).times(new BigNumber(10).pow(decimals)).toFixed(0); } /** - * @description convert amount from Wei to Ether units - * @param amountInWei amount to convert - * @param [decimals=18] token decimals + * Converts amount from Wei to Ether units. + * @param amountInWei Amount to convert. + * @param decimals Token decimals. */ static fromWei(amountInWei: BigNumber | string | number, decimals = 18): BigNumber { return new BigNumber(amountInWei).div(new BigNumber(10).pow(decimals)); } /** - * @description convert address to bytes32 format - * @param address address to convert + * Converts address to bytes32 format. + * @param address Address to convert. */ static addressToBytes32(address: string): string { if (address.slice(0, 2) !== '0x' || address.length !== 42) { @@ -66,45 +69,32 @@ export class Web3Pure { } /** - * @description convert address to checksum format - * @param address address to convert + * Converts address to checksum format. + * @param address Address to convert. */ static toChecksumAddress(address: string): string { return toChecksumAddress(address); } /** - * @description checks if a given address is a valid Ethereum address - * @param address the address to check validity + * Checks if a given address is a valid Ethereum address. + * @param address The address to check validity of. */ static isAddressCorrect(address: string): boolean { return isAddress(address); } /** - * @description converts Eth amount into Wei - * @param value to convert in Eth - */ - static ethToWei(value: string | BigNumber): string { - return toWei(value.toString(), 'ether'); - } - - /** - * @description converts Wei amount into Eth - * @param value to convert in Wei - */ - static weiToEth(value: string | BigNumber): string { - return fromWei(value.toString(), 'ether'); - } - - /** - * @description checks if address is Ether native address - * @param address address to check + * Checks if address is Ether native address. + * @param address Address to check. */ static isNativeAddress = (address: string): boolean => { return address === NATIVE_TOKEN_ADDRESS; }; + /** + * Returns transaction config with encoded data. + */ static encodeMethodCall( contractAddress: string, contractAbi: AbiItem[], @@ -129,7 +119,7 @@ export class Web3Pure { * @param contractAbi The JSON interface object of a function. * @param methodName Method name to encode. * @param methodArguments Parameters to encode. - * @return string An ABI encoded function call. Means function signature + parameters. + * @returns An ABI encoded function call. Means function signature + parameters. */ public static encodeFunctionCall( contractAbi: AbiItem[], @@ -144,7 +134,7 @@ export class Web3Pure { } /** - * @description Converts ascii address to bytes32 format + * Converts ascii address to bytes32 format. * @param address Address to convert. */ public static asciiToBytes32(address: string): string { diff --git a/src/core/sdk/models/configuration.ts b/src/core/sdk/models/configuration.ts index 89ed0b540c..e294c19edd 100644 --- a/src/core/sdk/models/configuration.ts +++ b/src/core/sdk/models/configuration.ts @@ -4,21 +4,71 @@ import Web3 from 'web3'; import { provider } from 'web3-core'; export interface Configuration { + /** + * Rpc data to connect to blockchains you will use. + * You have to pass rpcProvider for each blockchain you will use with sdk. + */ readonly rpcProviders: Partial>; + + /** + * Required to use `swap`, `approve` and other methods which sends transactions. + * But you can calculate and encode trades without `walletProvider`. + * Pass it when user connects wallet. Please note that `address` and `chainId` must + * match account address and selected chain id in a user's wallet. + */ readonly walletProvider?: WalletProvider; + + /** + * You can pass your own http client (e.g. HttpClient in Angular) if you have it, + * to not duplicate http clients and decrease bundle size. + */ readonly httpClient?: HttpClient; + + /** + * Integrator wallet address. + */ readonly providerAddress?: string; } export interface RpcProvider { + /** + * Rpc link. Copy it from your rpc provider (like Infura, Quicknode, Getblock, Moralis, etc.) website. + */ readonly mainRpc: string; + + /** + * Same as `mainRpc`. Will be used instead `mainRpc` if mainRpc is out of timeout = `mainPrcTimeout`. + */ readonly spareRpc?: string; + + /** + * Specifies timeout in ms after which `mainRpc` will be replaced with `spareRpc` (if `spareRpc` is defined) + */ readonly mainPrcTimeout?: number; + + /** + * Before the `mainRpc` link is applied to the sdk, all the `mainRpc` links + * will be health-checked by receiving and verifying the predefined data. + * If an error occurs during the request the `mainRpc` will be replaced with a spare one. + * This `healthCheckTimeout` parameter allows you to set the maximum allowable timeout when + * checking the `mainRpc`. + */ readonly healthCheckTimeout?: number; } export interface WalletProvider { + /** + * Wallet provider. + */ readonly core: provider | Web3; + + /** + * User wallet address. + */ readonly address: string; + + /** + * Selected chain in user wallet. + */ readonly chainId: number | string; } diff --git a/src/core/sdk/sdk.ts b/src/core/sdk/sdk.ts index 36adf05dc1..d70f258d84 100644 --- a/src/core/sdk/sdk.ts +++ b/src/core/sdk/sdk.ts @@ -12,25 +12,60 @@ import { EMPTY_ADDRESS } from '@core/blockchain/constants/empty-address'; import { BlockchainName } from 'src/core'; import { CrossChainSymbiosisManager } from '@features/cross-chain/cross-chain-symbiosis-manager'; +/** + * Base class to work with sdk. + */ export class SDK { + /** + * Instant trades manager object. Use it to calculate and create instant trades. + */ public readonly instantTrades: InstantTradesManager; + /** + * Cross-chain trades manager object. Use it to calculate and create cross-chain trades. + */ public readonly crossChain: CrossChainManager; + /** + * Cross-chain symbiosis manager object. Use it to get pending trades in symbiosis and revert them. + */ public readonly crossChainSymbiosisManager: CrossChainSymbiosisManager; + /** + * Tokens manager object. Use it to fetch and store tokens data. + */ public readonly tokens = new TokensManager(); + /** + * Can be used to get `Web3Public` instance by blockchain name to get public information from blockchain. + */ public readonly web3PublicService = Injector.web3PublicService; + /** + * Can be used to send transactions and execute smart contracts methods. + */ public readonly web3Private = Injector.web3Private; + /** + * Use it to get gas price information. + */ public readonly gasPriceApi = Injector.gasPriceApi; + /** + * Use it to get crypto price information. + */ public readonly cryptoPriceApi = Injector.coingeckoApi; + /** + * @internal + * Stores currently set rpc providers for each blockchain. + */ public static rpcList: Partial>; + /** + * Creates new sdk instance. Changes dependencies of all sdk entities according + * to new configuration (even for entities created with other previous sdk instances). + */ public static async createSDK(configuration: Configuration): Promise { this.rpcList = configuration.rpcProviders; @@ -68,6 +103,9 @@ export class SDK { this.crossChainSymbiosisManager = new CrossChainSymbiosisManager(); } + /** + * Updates sdk configuration and sdk entities dependencies. + */ public async updateConfiguration(configuration: Configuration): Promise { const [web3PublicService, web3Private, httpClient] = await Promise.all([ SDK.createWeb3PublicService(configuration), diff --git a/src/features/cross-chain/models/cross-chain-options.ts b/src/features/cross-chain/models/cross-chain-options.ts index 9608710de3..abf62e0ca3 100644 --- a/src/features/cross-chain/models/cross-chain-options.ts +++ b/src/features/cross-chain/models/cross-chain-options.ts @@ -17,6 +17,7 @@ export interface CrossChainOptions { gasCalculation?: 'enabled' | 'disabled'; /** + * @internal * Integrator address. */ providerAddress?: string; diff --git a/src/features/cross-chain/providers/common/cross-chain-trade.ts b/src/features/cross-chain/providers/common/cross-chain-trade.ts index a5e7f0ef79..a5663f57b6 100644 --- a/src/features/cross-chain/providers/common/cross-chain-trade.ts +++ b/src/features/cross-chain/providers/common/cross-chain-trade.ts @@ -13,7 +13,7 @@ import { EncodeTransactionOptions, SwapTransactionOptions } from 'src/features'; -import { UnnecessaryApprove, WalletNotConnectedError, WrongNetworkError } from 'src/common'; +import { UnnecessaryApproveError, WalletNotConnectedError, WrongNetworkError } from 'src/common'; import { TransactionReceipt } from 'web3-eth'; import { ContractParams } from '@features/cross-chain/models/contract-params'; import { TransactionConfig } from 'web3-core'; @@ -95,7 +95,7 @@ export abstract class CrossChainTrade { */ public async approve(options: BasicTransactionOptions): Promise { if (!(await this.needApprove())) { - throw new UnnecessaryApprove(); + throw new UnnecessaryApproveError(); } this.checkWalletConnected(); diff --git a/src/features/cross-chain/providers/rubic-trade-provider/rubic-cross-chain-trade.ts b/src/features/cross-chain/providers/rubic-trade-provider/rubic-cross-chain-trade.ts index bf5ff355c3..a75426d3a7 100644 --- a/src/features/cross-chain/providers/rubic-trade-provider/rubic-cross-chain-trade.ts +++ b/src/features/cross-chain/providers/rubic-trade-provider/rubic-cross-chain-trade.ts @@ -17,7 +17,11 @@ import { LowSlippageDeflationaryTokenError, RubicSdkError } from 'src/common'; import { TOKEN_WITH_FEE_ERRORS } from '@features/cross-chain/constants/token-with-fee-errors'; import { CROSS_CHAIN_TRADE_TYPE } from 'src/features'; +/** + * Calculated Rubic cross chain trade. + */ export class RubicCrossChainTrade extends CelerRubicCrossChainTrade { + /** @internal */ public static async getGasData( fromTrade: CrossChainContractTrade, toTrade: CrossChainContractTrade, diff --git a/src/features/cross-chain/providers/symbiosis-trade-provider/symbiosis-cross-chain-trade.ts b/src/features/cross-chain/providers/symbiosis-trade-provider/symbiosis-cross-chain-trade.ts index 2a8e63197b..6e06277eb5 100644 --- a/src/features/cross-chain/providers/symbiosis-trade-provider/symbiosis-cross-chain-trade.ts +++ b/src/features/cross-chain/providers/symbiosis-trade-provider/symbiosis-cross-chain-trade.ts @@ -12,7 +12,11 @@ import { GasData } from '@features/cross-chain/models/gas-data'; import { EMPTY_ADDRESS } from '@core/blockchain/constants/empty-address'; import BigNumber from 'bignumber.js'; +/** + * Calculated Symbiosis cross chain trade. + */ export class SymbiosisCrossChainTrade extends CrossChainTrade { + /** @internal */ public static async getGasData( from: PriceTokenAmount, to: PriceTokenAmount, @@ -70,6 +74,9 @@ export class SymbiosisCrossChainTrade extends CrossChainTrade { public readonly to: PriceTokenAmount; + /** + * Overall price impact, fetched from symbiosis api. + */ public readonly priceImpact: number; public readonly gasData: GasData | null; diff --git a/src/features/instant-trades/dexes/common/oneinch-common/oneinch-abstract-provider.ts b/src/features/instant-trades/dexes/common/oneinch-common/oneinch-abstract-provider.ts index c1c346203f..9a5d17a923 100644 --- a/src/features/instant-trades/dexes/common/oneinch-common/oneinch-abstract-provider.ts +++ b/src/features/instant-trades/dexes/common/oneinch-common/oneinch-abstract-provider.ts @@ -204,7 +204,7 @@ export abstract class OneinchAbstractProvider extends InstantTradeProvider { /** * Extracts tokens path from oneInch api response. - * @return Promise Tokens array, used in the route. + * @returns Promise Tokens array, used in the route. */ private async extractPath( fromToken: Token, diff --git a/src/features/instant-trades/dexes/common/uniswap-v2-abstract/uniswap-v2-abstract-provider.ts b/src/features/instant-trades/dexes/common/uniswap-v2-abstract/uniswap-v2-abstract-provider.ts index bb3b50c53a..df92d9ee9e 100644 --- a/src/features/instant-trades/dexes/common/uniswap-v2-abstract/uniswap-v2-abstract-provider.ts +++ b/src/features/instant-trades/dexes/common/uniswap-v2-abstract/uniswap-v2-abstract-provider.ts @@ -18,8 +18,10 @@ import { EMPTY_ADDRESS } from '@core/blockchain/constants/empty-address'; export abstract class UniswapV2AbstractProvider< T extends UniswapV2AbstractTrade = UniswapV2AbstractTrade > extends InstantTradeProvider { + /** @internal */ public abstract readonly InstantTradeClass: UniswapV2TradeClass; + /** @internal */ public abstract readonly providerSettings: UniswapV2ProviderConfiguration; public get type(): TradeType { @@ -73,6 +75,14 @@ export abstract class UniswapV2AbstractProvider< return (await this.calculateExactOutput(from, to, options)).from.tokenAmount; } + /** + * Calculates instant trade. + * @param from Token to sell. + * @param to Token to get. + * @param weiAmount Amount to sell or to get in wei. + * @param exact Defines, whether to call 'exactInput' or 'exactOutput' method. + * @param options Additional options. + */ public async calculateDifficultTrade( from: PriceToken, to: PriceToken, diff --git a/src/features/instant-trades/dexes/common/uniswap-v2-abstract/uniswap-v2-abstract-trade.ts b/src/features/instant-trades/dexes/common/uniswap-v2-abstract/uniswap-v2-abstract-trade.ts index 992cd8aed5..2e6c577bbb 100644 --- a/src/features/instant-trades/dexes/common/uniswap-v2-abstract/uniswap-v2-abstract-trade.ts +++ b/src/features/instant-trades/dexes/common/uniswap-v2-abstract/uniswap-v2-abstract-trade.ts @@ -45,6 +45,7 @@ export type UniswapV2TradeStruct = { }; export abstract class UniswapV2AbstractTrade extends InstantTrade { + /** @internal */ @Cache public static getContractAddress(blockchain: BlockchainName): string { // see https://github.com/microsoft/TypeScript/issues/34516 @@ -63,10 +64,13 @@ export abstract class UniswapV2AbstractTrade extends InstantTrade { throw new RubicSdkError(`Static TRADE_TYPE getter is not implemented by ${this.name}`); } + /** @internal */ public static readonly contractAbi: AbiItem[] = defaultUniswapV2Abi; + /** @internal */ public static readonly swapMethods: ExactInputOutputSwapMethodsList = SWAP_METHOD; + /** @internal */ public static readonly defaultEstimatedGasInfo: DefaultEstimatedGas = defaultEstimatedGas; public static callForRoutes( @@ -84,6 +88,9 @@ export abstract class UniswapV2AbstractTrade extends InstantTrade { ); } + /** + * Deadline for transaction in minutes. + */ public deadlineMinutes: number; public slippageTolerance: number; @@ -94,16 +101,29 @@ export abstract class UniswapV2AbstractTrade extends InstantTrade { public gasFeeInfo: GasFeeInfo | null; + /** + * Path, through which tokens will be converted. + */ public readonly path: ReadonlyArray; + /** + * @internal + * Path with wrapped native address. + */ public readonly wrappedPath: ReadonlyArray; + /** + * Defines, whether to call 'exactInput' or 'exactOutput' method. + */ public readonly exact: Exact; public get type(): TradeType { return (this.constructor as typeof UniswapV2AbstractTrade).type; } + /** + * Updates parameters in swap options. + */ public set settings(value: { deadlineMinutes?: number; slippageTolerance?: number }) { this.deadlineMinutes = value.deadlineMinutes || this.deadlineMinutes; this.slippageTolerance = value.slippageTolerance || this.slippageTolerance; @@ -302,10 +322,12 @@ export abstract class UniswapV2AbstractTrade extends InstantTrade { ]) as Parameters['callContractMethod']>; } + /** @internal */ public getEstimatedGasCallData(): BatchCall { return this.estimateGasForAnyToAnyTrade(); } + /** @internal */ public getDefaultEstimatedGas(): BigNumber { const transitTokensNumber = this.wrappedPath.length - 2; let methodName: keyof DefaultEstimatedGas = 'tokensToTokens'; diff --git a/src/features/instant-trades/dexes/common/uniswap-v3-abstract/utils/quoter-controller/uniswap-v3-quoter-controller.ts b/src/features/instant-trades/dexes/common/uniswap-v3-abstract/utils/quoter-controller/uniswap-v3-quoter-controller.ts index 1f0afffa65..b4116c964f 100644 --- a/src/features/instant-trades/dexes/common/uniswap-v3-abstract/utils/quoter-controller/uniswap-v3-quoter-controller.ts +++ b/src/features/instant-trades/dexes/common/uniswap-v3-abstract/utils/quoter-controller/uniswap-v3-quoter-controller.ts @@ -45,7 +45,7 @@ export class UniswapV3QuoterController implements UniswapV3AlgebraQuoterControll * toHex(fee_i) must be of length 6, so leading zeroes are added. * @param pools Liquidity pools, included in route. * @param initialTokenAddress From token address. - * @return string Encoded string. + * @returns string Encoded string. */ @Cache public static getEncodedPoolsPath(pools: LiquidityPool[], initialTokenAddress: string): string { diff --git a/src/features/instant-trades/dexes/polygon/algebra/utils/quoter-controller/algebra-quoter-controller.ts b/src/features/instant-trades/dexes/polygon/algebra/utils/quoter-controller/algebra-quoter-controller.ts index ef817f9211..1ebddf09f1 100644 --- a/src/features/instant-trades/dexes/polygon/algebra/utils/quoter-controller/algebra-quoter-controller.ts +++ b/src/features/instant-trades/dexes/polygon/algebra/utils/quoter-controller/algebra-quoter-controller.ts @@ -32,7 +32,7 @@ export class AlgebraQuoterController implements UniswapV3AlgebraQuoterController * Converts algebra route to encoded bytes string to pass it to contract. * Structure of encoded string: '0x${tokenAddress_0}${tokenAddress_1}...${tokenAddress_n}. * @param path Symbol tokens, included in route. - * @return string Encoded string. + * @returns string Encoded string. */ public static getEncodedPath(path: Token[]): string { const encodedPath = path.reduce( diff --git a/src/features/instant-trades/instant-trade-provider.ts b/src/features/instant-trades/instant-trade-provider.ts index f636b93610..e2916a7d6b 100644 --- a/src/features/instant-trades/instant-trade-provider.ts +++ b/src/features/instant-trades/instant-trade-provider.ts @@ -31,7 +31,7 @@ export abstract class InstantTradeProvider { return Injector.web3PublicService.getWeb3Public(this.blockchain); } /** - * Calculates best instant trade, based on course. + * Calculates instant trade. * @param from Token to sell with input amount. * @param to Token to get. * @param options Additional options. diff --git a/src/features/tokens/tokens-manager.ts b/src/features/tokens/tokens-manager.ts index 1873582d00..699cf59a0a 100644 --- a/src/features/tokens/tokens-manager.ts +++ b/src/features/tokens/tokens-manager.ts @@ -9,27 +9,56 @@ import { Token, TokenStruct } from '@core/blockchain/tokens/token'; import { BlockchainName } from '@core/blockchain/models/blockchain-name'; import BigNumber from 'bignumber.js'; +/** + * Contains methods to create Tokens classes. + */ export class TokensManager { + /** + * Creates {@type Token} instance by full token data struct. + * @param tokenStruct Full token's structure. + */ public createTokenFromStruct(tokenStruct: TokenStruct): Token { return new Token(tokenStruct); } + /** + * Fetches token data and creates {@type Token} by token's address and blockchain. + * @param tokenBaseStruct Base token's structure. + */ public createToken(tokenBaseStruct: TokenBaseStruct): Promise { return Token.createToken(tokenBaseStruct); } + /** + * Same as {@link createTokenFromStruct} for multiple tokens structs. + * @param tokensStructs Full tokens' structures. + */ public createTokensFromStructs(tokensStructs: TokenStruct[]): Token[] { return tokensStructs.map(tokenStruct => this.createTokenFromStruct(tokenStruct)); } + /** + * Same as {@link createTokensFromStructs}, but uses multicall for data fetching, + * so makes only one rpc request. + * @param addresses Tokens' addresses. + * @param blockchain Tokens' blockchain. + */ public createTokens(addresses: string[], blockchain: BlockchainName): Promise { return Token.createTokens(addresses, blockchain); } + /** + * Creates {@type PriceToken} from full price token struct including price. + * @param priceTokenStruct Full price token structure. + */ public createPriceTokenFromStruct(priceTokenStruct: PriceTokenStruct): PriceToken { return new PriceToken(priceTokenStruct); } + /** + * Creates {@type PriceToken} from full token structure (without price) or from token address and blockchain. + * @param token Full or base token's structure. + */ public createPriceToken(token: TokenBaseStruct | TokenStruct): Promise { if ('name' in token && 'symbol' in token && 'decimals' in token) { return PriceToken.createFromToken(token); @@ -37,12 +66,21 @@ export class TokensManager { return PriceToken.createToken(token); } + /** + * Creates {@type PriceTokenAmount} from full price token struct including price. + * @param priceTokenAmountStruct Full price token amount structure. + */ public createPriceTokenAmountFromStruct( priceTokenAmountStruct: PriceTokenAmountStruct ): PriceTokenAmount { return new PriceTokenAmount(priceTokenAmountStruct); } + /** + * Creates {@type PriceTokenAmount} from full token structure (without price) or + * from token address and blockchain. + * @param priceTokenAmountStruct Full or base token's structure with amount. + */ public createPriceTokenAmount( priceTokenAmountStruct: | PriceTokenAmountBaseStruct From 895facdbef70d42485f91d71708062840c0bab37 Mon Sep 17 00:00:00 2001 From: ottebrut Date: Mon, 20 Jun 2022 16:47:44 +0300 Subject: [PATCH 06/13] Add classes documentation --- src/common/decorators/cache.decorator.ts | 3 +++ src/common/decorators/models/cache-config.ts | 11 +++++++++++ .../decorators/models/conditional-result.ts | 4 ++++ src/common/errors/blockchain/web3.error.ts | 3 +++ src/common/utils/blockchain.ts | 3 +++ src/common/utils/functions.ts | 15 ++++++++++++--- src/common/utils/index.ts | 2 +- src/common/utils/object.ts | 3 +++ src/core/index.ts | 3 +-- src/core/sdk/models/configuration.ts | 3 +++ src/features/instant-trades/models/trade-type.ts | 6 ++++++ .../instant-trades/models/typed-trade-provider.ts | 3 +++ 12 files changed, 53 insertions(+), 6 deletions(-) diff --git a/src/common/decorators/cache.decorator.ts b/src/common/decorators/cache.decorator.ts index 569619671e..5e5da540ba 100644 --- a/src/common/decorators/cache.decorator.ts +++ b/src/common/decorators/cache.decorator.ts @@ -126,6 +126,9 @@ function CacheBuilder(cacheConfig: CacheConfig): DecoratorSignature { }; } +/** + * Decorator, used to cache calculated result of functions. + */ export function Cache(cacheConfigOrTarget: CacheConfig): DecoratorSignature; export function Cache( cacheConfigOrTarget: Object, diff --git a/src/common/decorators/models/cache-config.ts b/src/common/decorators/models/cache-config.ts index 3dc2ca2d31..8fa28d0c35 100644 --- a/src/common/decorators/models/cache-config.ts +++ b/src/common/decorators/models/cache-config.ts @@ -1,4 +1,15 @@ +/** + * Configuration, used for cache decorator. + */ export interface CacheConfig { + /** + * Amount of time, during which cached result is relevant. + */ maxAge?: number; + + /** + * If true, then results must be of type {@link ConditionalResult}, + * defining whether to cache calculated result. + */ conditionalCache?: boolean; } diff --git a/src/common/decorators/models/conditional-result.ts b/src/common/decorators/models/conditional-result.ts index 7c839b156f..e47426db4e 100644 --- a/src/common/decorators/models/conditional-result.ts +++ b/src/common/decorators/models/conditional-result.ts @@ -1,3 +1,7 @@ +/** + * Used for {@link Cache} decorator. + * User `notSave` field to define whether to cache calculated result. + */ export type ConditionalResult = { notSave: boolean; value: T; diff --git a/src/common/errors/blockchain/web3.error.ts b/src/common/errors/blockchain/web3.error.ts index 794a842cf4..dc9fa7c6a9 100644 --- a/src/common/errors/blockchain/web3.error.ts +++ b/src/common/errors/blockchain/web3.error.ts @@ -1,3 +1,6 @@ +/** + * Type of errors, thrown by web3 methods. + */ export interface Web3Error extends Error { code: number; } diff --git a/src/common/utils/blockchain.ts b/src/common/utils/blockchain.ts index 2c0c431160..ac0391489c 100644 --- a/src/common/utils/blockchain.ts +++ b/src/common/utils/blockchain.ts @@ -1,3 +1,6 @@ +/** + * Compares provided addresses case insensitive. + */ export function compareAddresses(address0: string, address1: string): boolean { return address0.toLowerCase() === address1.toLowerCase(); } diff --git a/src/common/utils/functions.ts b/src/common/utils/functions.ts index 6230e5705a..49bd74a2f2 100644 --- a/src/common/utils/functions.ts +++ b/src/common/utils/functions.ts @@ -1,16 +1,21 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import { Tuple } from 'ts-essentials'; -type SuccessfulCall = { +export type SuccessfulCall = { success: true; value: T; }; -type ErrorCall = { +export type ErrorCall = { success: false; error: unknown; }; +/** + * Wraps result of function in {@link SuccessfulCall} or {@link ErrorCall}. + * @param func Function to calculate. + * @param parameters Parameter of function to calculate. + */ export function tryExecute( func: (...args: any[]) => unknown, parameters: Parameters[] @@ -28,7 +33,11 @@ export function tryExecute( }; } } - +/** + * Wraps result of async function in {@link SuccessfulCall} or {@link ErrorCall}. + * @param func Async function to calculate. + * @param parameters Parameter of function to calculate. + */ export async function tryExecuteAsync( func: (...args: T) => Promise, parameters: Parameters diff --git a/src/common/utils/index.ts b/src/common/utils/index.ts index 1586795dac..dd417dbb60 100644 --- a/src/common/utils/index.ts +++ b/src/common/utils/index.ts @@ -1,3 +1,3 @@ export { compareAddresses } from './blockchain'; -export { tryExecute, tryExecuteAsync } from './functions'; +export { SuccessfulCall, ErrorCall, tryExecute, tryExecuteAsync } from './functions'; export { cloneObject, notNull } from './object'; diff --git a/src/common/utils/object.ts b/src/common/utils/object.ts index 71768fc8f1..f9bdfe5c48 100644 --- a/src/common/utils/object.ts +++ b/src/common/utils/object.ts @@ -2,6 +2,9 @@ export function cloneObject(obj: T): T { return JSON.parse(JSON.stringify(obj)); } +/** + * Filters object, that can possible be `null`. + */ export function notNull(obj: T | null): obj is T { return obj !== null; } diff --git a/src/core/index.ts b/src/core/index.ts index 392016f6da..09ea49ffab 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -4,6 +4,7 @@ export { Web3Private } from './blockchain/web3-private/web3-private'; export { Web3Pure } from './blockchain/web3-pure/web3-pure'; export { BlockchainsInfo } from './blockchain/blockchains-info'; export { BlockchainName, BLOCKCHAIN_NAME } from './blockchain/models/blockchain-name'; +export { Configuration, RpcProvider, WalletProvider } from './sdk/models/configuration'; export type { Token } from './blockchain/tokens/token'; export type { PriceToken } from './blockchain/tokens/price-token'; @@ -12,5 +13,3 @@ export type { BasicTransactionOptions } from './blockchain/models/basic-transact export type { Blockchain } from './blockchain/models/blockchain'; export type { TokenBaseStruct } from './blockchain/models/token-base-struct'; export type { TransactionOptions } from './blockchain/models/transaction-options'; -export type { WalletConnectionConfiguration } from './blockchain/models/wallet-connection-configuration'; -export { Configuration, RpcProvider, WalletProvider } from './sdk/models/configuration'; diff --git a/src/core/sdk/models/configuration.ts b/src/core/sdk/models/configuration.ts index e294c19edd..8cefa24524 100644 --- a/src/core/sdk/models/configuration.ts +++ b/src/core/sdk/models/configuration.ts @@ -3,6 +3,9 @@ import { BlockchainName } from '@core/blockchain/models/blockchain-name'; import Web3 from 'web3'; import { provider } from 'web3-core'; +/** + * Main sdk configuration. + */ export interface Configuration { /** * Rpc data to connect to blockchains you will use. diff --git a/src/features/instant-trades/models/trade-type.ts b/src/features/instant-trades/models/trade-type.ts index 2034c0c268..1a54706434 100644 --- a/src/features/instant-trades/models/trade-type.ts +++ b/src/features/instant-trades/models/trade-type.ts @@ -1,3 +1,6 @@ +/** + * List of instant trade types. + */ export const TRADE_TYPE = { UNISWAP_V2: 'UNISWAP_V2', SUSHI_SWAP_ETHEREUM: 'SUSHI_SWAP_ETHEREUM', @@ -32,4 +35,7 @@ export const TRADE_TYPE = { ONE_INCH_AVALANCHE: 'ONE_INCH_AVALANCHE' } as const; +/** + * Instant trade type. + */ export type TradeType = keyof typeof TRADE_TYPE; diff --git a/src/features/instant-trades/models/typed-trade-provider.ts b/src/features/instant-trades/models/typed-trade-provider.ts index b810b15bf1..db01352f83 100644 --- a/src/features/instant-trades/models/typed-trade-provider.ts +++ b/src/features/instant-trades/models/typed-trade-provider.ts @@ -1,4 +1,7 @@ import { InstantTradeProvider } from '@features/instant-trades/instant-trade-provider'; import { TradeType } from '@features/instant-trades/models/trade-type'; +/** + * Record of instant trade types and their corresponding instant trade providers. + */ export type TypedTradeProviders = Readonly>; From 254f461a16530193001ba0ec8d3286d652619a81 Mon Sep 17 00:00:00 2001 From: ottebrut Date: Tue, 21 Jun 2022 10:47:29 +0300 Subject: [PATCH 07/13] Add ci for typedoc --- .github/workflows/ci-docs.yml | 38 +++++++++++++++++++++++++++++++++++ package.json | 3 ++- tsconfig.json | 6 +----- typedoc.json | 2 +- 4 files changed, 42 insertions(+), 7 deletions(-) create mode 100644 .github/workflows/ci-docs.yml diff --git a/.github/workflows/ci-docs.yml b/.github/workflows/ci-docs.yml new file mode 100644 index 0000000000..f513fa0a40 --- /dev/null +++ b/.github/workflows/ci-docs.yml @@ -0,0 +1,38 @@ +name: Publish documentation + +on: + pull_request: + branches: + - develop + +jobs: + docs: + name: Publish documentation + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + + - name: Read .nvmrc + run: echo ::set-output name=NVMRC::$(cat .nvmrc) + id: nvm + + - name: Set up Node.js + uses: actions/setup-node@v2 + with: + node-version: '${{ steps.nvm.outputs.NVMRC }}' + + - name: Set up yarn + run: npm install --global yarn + + - name: Set up dependencies + run: yarn + + - name: Update docs + run: npm run docs + + - name: Deploy Github Page + uses: peaceiris/actions-gh-pages@v3 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: ./docs diff --git a/package.json b/package.json index bf94a93d19..6d5140f8f3 100644 --- a/package.json +++ b/package.json @@ -55,7 +55,8 @@ "lint": "eslint src __tests__", "test": "cd ./scripts && bash test-runner.sh", "build:publish": "yarn compile && yarn build && npm publish --access public", - "analyze": "webpack --profile --json > stats.json && webpack-bundle-analyzer stats.json" + "analyze": "webpack --profile --json > stats.json && webpack-bundle-analyzer stats.json", + "docs": "typedoc" }, "dependencies": { "assert": "^2.0.0", diff --git a/tsconfig.json b/tsconfig.json index e637551e8d..2d00cdec4a 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -46,9 +46,5 @@ "skipLibCheck": true }, "include": ["src"], - "exclude": ["__tests__" ,"node_modules", "lib", "types"], - "typedocOptions": { - "entryPoints": ["src/index.ts"], - "out": "docs" - } + "exclude": ["__tests__" ,"node_modules", "lib", "types"] } diff --git a/typedoc.json b/typedoc.json index 0a1287eb40..adb75c9b29 100644 --- a/typedoc.json +++ b/typedoc.json @@ -3,5 +3,5 @@ "excludeInternal": true, "excludePrivate": true, "excludeProtected": true, - "out": "doc" + "out": "docs" } From 39ac0cdc0ebc425b50e835095e120c03c7afcf29 Mon Sep 17 00:00:00 2001 From: ottebrut Date: Tue, 21 Jun 2022 10:59:00 +0300 Subject: [PATCH 08/13] Return docker compose --- .gitignore | 1 - docker-compose.yml | 16 ++++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 docker-compose.yml diff --git a/.gitignore b/.gitignore index df1747b649..05a4611882 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,5 @@ /dist/ /cache/ /scripts/node.log -/docker-compose.yml /docs/ diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000000..d6a598bf1b --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,16 @@ +version: "3.7" + +services: + eth-node: + image: ottebrut/rubic-sdk-tools:eth-node-1.2 + container_name: eth-node + ports: + - 8545:8545 + - 1545:1545 + polygon-node: + image: ottebrut/rubic-sdk-tools:polygon-node-1.2 + container_name: polygon-node + ports: + - 8547:8545 + - 1547:1545 + From 7c0aeba942637d164fd0550281de2a27c83c77eb Mon Sep 17 00:00:00 2001 From: ottebrut Date: Tue, 21 Jun 2022 11:00:16 +0300 Subject: [PATCH 09/13] Update ci for typedoc --- .github/workflows/ci-docs.yml | 38 --------------------------------- .github/workflows/ci-master.yml | 10 ++++----- 2 files changed, 5 insertions(+), 43 deletions(-) delete mode 100644 .github/workflows/ci-docs.yml diff --git a/.github/workflows/ci-docs.yml b/.github/workflows/ci-docs.yml deleted file mode 100644 index f513fa0a40..0000000000 --- a/.github/workflows/ci-docs.yml +++ /dev/null @@ -1,38 +0,0 @@ -name: Publish documentation - -on: - pull_request: - branches: - - develop - -jobs: - docs: - name: Publish documentation - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - - - name: Read .nvmrc - run: echo ::set-output name=NVMRC::$(cat .nvmrc) - id: nvm - - - name: Set up Node.js - uses: actions/setup-node@v2 - with: - node-version: '${{ steps.nvm.outputs.NVMRC }}' - - - name: Set up yarn - run: npm install --global yarn - - - name: Set up dependencies - run: yarn - - - name: Update docs - run: npm run docs - - - name: Deploy Github Page - uses: peaceiris/actions-gh-pages@v3 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - publish_dir: ./docs diff --git a/.github/workflows/ci-master.yml b/.github/workflows/ci-master.yml index be03d5cc96..e4a9b2bb84 100644 --- a/.github/workflows/ci-master.yml +++ b/.github/workflows/ci-master.yml @@ -37,8 +37,8 @@ jobs: - name: Build bundle run: yarn build -# - name: Set up env.js -# run: node ./scripts/build-env.js --eth ${{ secrets.ETH_RPC }} --bsc ${{ secrets.BSC_RPC }} --polygon ${{ secrets.POLYGON_RPC }} -# -# - name: Run tests -# run: yarn test + - name: Deploy Github Page + uses: peaceiris/actions-gh-pages@v3 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: ./docs From 89bfec25244ef2fe4d070d1b12824209937872a2 Mon Sep 17 00:00:00 2001 From: ottebrut Date: Tue, 21 Jun 2022 11:56:58 +0300 Subject: [PATCH 10/13] Update docs --- README.md | 51 +------------------ src/common/models/http-client.ts | 3 ++ src/core/blockchain/models/blockchain.ts | 3 ++ .../blockchain/models/token-base-struct.ts | 3 ++ src/core/sdk/models/configuration.ts | 8 ++- .../models/encode-transaction-options.ts | 3 ++ .../instant-trades/models/gas-fee-info.ts | 3 ++ .../models/swap-calculation-options.ts | 3 ++ .../models/swap-transaction-options.ts | 3 ++ src/features/tokens/tokens-manager.ts | 12 ++--- 10 files changed, 36 insertions(+), 56 deletions(-) diff --git a/README.md b/README.md index a42262d1e0..c030c4ee15 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,9 @@ ![build status](https://github.com/Cryptorubic/rubic-sdk/actions/workflows/ci-master.yml/badge.svg) [![license](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://github.com/Cryptorubic/rubic-sdk/blob/main/LICENSE) +[Latest API Documentation](https://cryptorubic.github.io/rubic-sdk) + ## Table of contents -- [Description](#description) - - [Supported DEX-es](#supported-dex-es) - - [Multi-Chain swaps supported blockchains](#multi-chain-swaps-supported-blockchains) - [Installation](#installation) - [Installation with cdn](#installation-with-cdn) - [Installation with npm and webpack](#installation-with-npm-and-webpack-react-) @@ -91,52 +90,6 @@ - [weiAmountPlusSlippage](#pricetokenamountweiamountplusslippage-method) - [calculatePriceImpactPercent](#pricetokenamountcalculatepriceimpactpercent-method) -## Description -In dApps a lot of business logic is often concentrated on the frontend for interacting with the blockchain. This SDK is built on the basis of [Rubic](https://github.com/Cryptorubic/rubic-app) multichain DeFi frontend part. SDK is a library for interacting with various dexes, as well as Rubic cross-chain swaps. It also includes a number of utilities useful when working with Ethereum. - -### Supported DEX-es - -- Ethereum - - [Uniswap V2](https://uniswap.org/) - - [Uniswap V3](https://uniswap.org/) - - [Sushiswap](https://sushi.com/) - - [1inch](https://app.1inch.io/) - - [0x](https://0x.org/) -- Binance Smart Chain - - [Pancake Swap](https://pancakeswap.finance/) - - [Sushiswap](https://sushi.com/) - - [1inch](https://app.1inch.io/) -- Polygon - - [Quick Swap](https://quickswap.exchange/) - - [Sushiswap](https://sushi.com/) - - [1inch](https://app.1inch.io/) - - [Uniswap V3](https://uniswap.org/) - - [Algebra](https://app.algebra.finance/) -- Avalanche - - [Joe](https://traderjoexyz.com/#/home) - - [Pangolin](https://app.pangolin.exchange/#/swap) - - [Sushiswap](https://sushi.com/) -- Fantom - - [Spirit Swap](https://swap.spiritswap.finance/) - - [Spooky Swap](https://spookyswap.finance/) - - [Sushiswap](https://sushi.com/) -- Moonriver - - [Solarbeam](https://solarbeam.io/exchange/swap) - - [Sushiswap](https://sushi.com/) -- Harmony - - [Sushiswap](https://sushi.com/) - - [Viper Swap](https://viperswap.one/) -- Arbitrum - - [Uniswap V3](https://uniswap.org/) - - [Sushiswap](https://sushi.com/) - - [1inch](https://app.1inch.io/) -- Aurora - - [Wanna Swap](https://wannaswap.finance/exchange/swap) - - [Trisolaris](https://www.trisolaris.io/) - -### Multi-Chain swaps supported blockchains -Ethereum, Binance Smart Chain, Polygon, Avalanche, Fantom, Moonriver, Harmony, Aurora, Arbitrum - ## Installation ### Installation with cdn ```html diff --git a/src/common/models/http-client.ts b/src/common/models/http-client.ts index 5d9e897cba..e5e5389b48 100644 --- a/src/common/models/http-client.ts +++ b/src/common/models/http-client.ts @@ -1,3 +1,6 @@ +/** + * Http client, used to get and send http requests. + */ export interface HttpClient { post(url: string, body: Object): Promise; get( diff --git a/src/core/blockchain/models/blockchain.ts b/src/core/blockchain/models/blockchain.ts index 4dc87357ab..f72661712c 100644 --- a/src/core/blockchain/models/blockchain.ts +++ b/src/core/blockchain/models/blockchain.ts @@ -1,6 +1,9 @@ import { BlockchainName } from '@core/blockchain/models/blockchain-name'; import { Token } from '@core/blockchain/tokens/token'; +/** + * Stores information about blockchain. + */ export interface Blockchain { id: number; name: BlockchainName; diff --git a/src/core/blockchain/models/token-base-struct.ts b/src/core/blockchain/models/token-base-struct.ts index d0d211158a..1b3c654d10 100644 --- a/src/core/blockchain/models/token-base-struct.ts +++ b/src/core/blockchain/models/token-base-struct.ts @@ -1,5 +1,8 @@ import { BlockchainName } from '@core/blockchain/models/blockchain-name'; +/** + * Stores basic information of token. + */ export interface TokenBaseStruct { address: string; blockchain: BlockchainName; diff --git a/src/core/sdk/models/configuration.ts b/src/core/sdk/models/configuration.ts index 8cefa24524..6626ee1d80 100644 --- a/src/core/sdk/models/configuration.ts +++ b/src/core/sdk/models/configuration.ts @@ -33,6 +33,9 @@ export interface Configuration { readonly providerAddress?: string; } +/** + * Stores information about rpc in certain blockchain. + */ export interface RpcProvider { /** * Rpc link. Copy it from your rpc provider (like Infura, Quicknode, Getblock, Moralis, etc.) website. @@ -59,9 +62,12 @@ export interface RpcProvider { readonly healthCheckTimeout?: number; } +/** + * Stores wallet core and information about current user, used to make `send` transactions. + */ export interface WalletProvider { /** - * Wallet provider. + * Core provider. */ readonly core: provider | Web3; diff --git a/src/features/instant-trades/models/encode-transaction-options.ts b/src/features/instant-trades/models/encode-transaction-options.ts index 3d403dee5a..b1744882a2 100644 --- a/src/features/instant-trades/models/encode-transaction-options.ts +++ b/src/features/instant-trades/models/encode-transaction-options.ts @@ -1,3 +1,6 @@ +/** + * Stores options for transaction in `encode` function. + */ export interface EncodeTransactionOptions { /** * User wallet address to send swap transaction. diff --git a/src/features/instant-trades/models/gas-fee-info.ts b/src/features/instant-trades/models/gas-fee-info.ts index 8636c93fba..896eafcd7f 100644 --- a/src/features/instant-trades/models/gas-fee-info.ts +++ b/src/features/instant-trades/models/gas-fee-info.ts @@ -1,5 +1,8 @@ import BigNumber from 'bignumber.js'; +/** + * Stores gas fee information in calculated trade. + */ export interface GasFeeInfo { readonly gasLimit?: BigNumber; readonly gasPrice?: BigNumber; diff --git a/src/features/instant-trades/models/swap-calculation-options.ts b/src/features/instant-trades/models/swap-calculation-options.ts index 7480e00de9..fb22fd8db2 100644 --- a/src/features/instant-trades/models/swap-calculation-options.ts +++ b/src/features/instant-trades/models/swap-calculation-options.ts @@ -1,5 +1,8 @@ import { SwapOptions } from '@features/instant-trades/models/swap-options'; +/** + * Stores options for calculating trade. + */ export interface SwapCalculationOptions extends SwapOptions { /** * Disabled or enables gas fee calculation. diff --git a/src/features/instant-trades/models/swap-transaction-options.ts b/src/features/instant-trades/models/swap-transaction-options.ts index 83d3f02c61..933b0040a0 100644 --- a/src/features/instant-trades/models/swap-transaction-options.ts +++ b/src/features/instant-trades/models/swap-transaction-options.ts @@ -1,3 +1,6 @@ +/** + * Stores options for transaction in `swap` function. + */ export interface SwapTransactionOptions { /** * Callback to be called, when user confirm swap transaction. diff --git a/src/features/tokens/tokens-manager.ts b/src/features/tokens/tokens-manager.ts index 699cf59a0a..63015d688c 100644 --- a/src/features/tokens/tokens-manager.ts +++ b/src/features/tokens/tokens-manager.ts @@ -14,7 +14,7 @@ import BigNumber from 'bignumber.js'; */ export class TokensManager { /** - * Creates {@type Token} instance by full token data struct. + * Creates {@link Token} instance by full token data struct. * @param tokenStruct Full token's structure. */ public createTokenFromStruct(tokenStruct: TokenStruct): Token { @@ -22,7 +22,7 @@ export class TokensManager { } /** - * Fetches token data and creates {@type Token} by token's address and blockchain. + * Fetches token data and creates {@link Token} by token's address and blockchain. * @param tokenBaseStruct Base token's structure. */ public createToken(tokenBaseStruct: TokenBaseStruct): Promise { @@ -48,7 +48,7 @@ export class TokensManager { } /** - * Creates {@type PriceToken} from full price token struct including price. + * Creates {@link PriceToken} from full price token struct including price. * @param priceTokenStruct Full price token structure. */ public createPriceTokenFromStruct(priceTokenStruct: PriceTokenStruct): PriceToken { @@ -56,7 +56,7 @@ export class TokensManager { } /** - * Creates {@type PriceToken} from full token structure (without price) or from token address and blockchain. + * Creates {@link PriceToken} from full token structure (without price) or from token address and blockchain. * @param token Full or base token's structure. */ public createPriceToken(token: TokenBaseStruct | TokenStruct): Promise { @@ -67,7 +67,7 @@ export class TokensManager { } /** - * Creates {@type PriceTokenAmount} from full price token struct including price. + * Creates {@link PriceTokenAmount} from full price token struct including price. * @param priceTokenAmountStruct Full price token amount structure. */ public createPriceTokenAmountFromStruct( @@ -77,7 +77,7 @@ export class TokensManager { } /** - * Creates {@type PriceTokenAmount} from full token structure (without price) or + * Creates {@link PriceTokenAmount} from full token structure (without price) or * from token address and blockchain. * @param priceTokenAmountStruct Full or base token's structure with amount. */ From 69446da42f2e8dfae56115820891d0a36b9eea4f Mon Sep 17 00:00:00 2001 From: ottebrut Date: Tue, 21 Jun 2022 12:22:25 +0300 Subject: [PATCH 11/13] Added examples to tsdoc --- .../cross-chain/cross-chain-manager.ts | 18 +++++++++ .../providers/common/cross-chain-trade.ts | 7 ++++ src/features/instant-trades/instant-trade.ts | 7 ++++ .../instant-trades/instant-trades-manager.ts | 21 +++++++++++ src/features/tokens/tokens-manager.ts | 37 +++++++++++++++++++ 5 files changed, 90 insertions(+) diff --git a/src/features/cross-chain/cross-chain-manager.ts b/src/features/cross-chain/cross-chain-manager.ts index 9f474473ae..ff59a25f73 100644 --- a/src/features/cross-chain/cross-chain-manager.ts +++ b/src/features/cross-chain/cross-chain-manager.ts @@ -51,6 +51,24 @@ export class CrossChainManager { /** * Calculates best cross chain trade, based on calculated courses. + * + * @example + * ```ts + * const fromBlockchain = BLOCKCHAIN_NAME.ETHEREUM; + * // ETH + * const fromTokenAddress = '0x0000000000000000000000000000000000000000'; + * const fromAmount = 1; + * const toBlockchain = BLOCKCHAIN_NAME.BINANCE_SMART_CHAIN; + * // BUSD + * const toTokenAddress = '0xe9e7cea3dedca5984780bafc599bd69add087d56'; + * + * const trade = await sdk.crossChain.calculateTrade( + * { blockchain: fromBlockchain, address: fromTokenAddress }, + * fromAmount, + * { blockchain: toBlockchain, address: toTokenAddress } + * ); + * ``` + * * @param fromToken Token to sell. * @param fromAmount Amount to sell. * @param toToken Token to get. diff --git a/src/features/cross-chain/providers/common/cross-chain-trade.ts b/src/features/cross-chain/providers/common/cross-chain-trade.ts index a5663f57b6..e02a781662 100644 --- a/src/features/cross-chain/providers/common/cross-chain-trade.ts +++ b/src/features/cross-chain/providers/common/cross-chain-trade.ts @@ -65,6 +65,13 @@ export abstract class CrossChainTrade { /** * Sends swap transaction with connected wallet. * If user has not enough allowance, then approve transaction will be called first. + * + * @example + * ```ts + * const onConfirm = (hash: string) => console.log(hash); + * const receipt = await trade.swap({ onConfirm }); + * ``` + * * @param options Transaction options. */ public abstract swap(options?: SwapTransactionOptions): Promise; diff --git a/src/features/instant-trades/instant-trade.ts b/src/features/instant-trades/instant-trade.ts index 79394ba2ca..e1442167db 100644 --- a/src/features/instant-trades/instant-trade.ts +++ b/src/features/instant-trades/instant-trade.ts @@ -142,6 +142,13 @@ export abstract class InstantTrade { /** * Sends swap transaction with connected wallet. * If user has not enough allowance, then approve transaction will be called first. + * + * @example + * ```ts + * const onConfirm = (hash: string) => console.log(hash); + * const receipt = await trades[TRADE_TYPE.UNISWAP_V2].swap({ onConfirm }); + * ``` + * * @param options Transaction options. */ public abstract swap(options?: SwapTransactionOptions): Promise; diff --git a/src/features/instant-trades/instant-trades-manager.ts b/src/features/instant-trades/instant-trades-manager.ts index 5ebd90a2f1..6245f6a47d 100644 --- a/src/features/instant-trades/instant-trades-manager.ts +++ b/src/features/instant-trades/instant-trades-manager.ts @@ -74,6 +74,27 @@ export class InstantTradesManager { /** * Calculates instant trades. + * + * @example + * ```ts + * const blockchain = BLOCKCHAIN_NAME.ETHEREUM; + * // ETH + * const fromTokenAddress = '0x0000000000000000000000000000000000000000'; + * const fromAmount = 1; + * // USDT + * const toTokenAddress = '0xdac17f958d2ee523a2206206994597c13d831ec7'; + * + * const trades = await sdk.instantTrades.calculateTrade( + * { blockchain, address: fromTokenAddress }, + * fromAmount, + * toTokenAddress + * ); + * + * Object.entries(trades).forEach(([tradeType, trade]) => + * console.log(tradeType, `to amount: ${trade.to.tokenAmount.toFormat(3)}`) + * ) + * ``` + * * @param fromToken Token to sell. * @param fromAmount Amount to sell. * @param toToken Token to get. diff --git a/src/features/tokens/tokens-manager.ts b/src/features/tokens/tokens-manager.ts index 63015d688c..3ebff8e6ec 100644 --- a/src/features/tokens/tokens-manager.ts +++ b/src/features/tokens/tokens-manager.ts @@ -23,6 +23,19 @@ export class TokensManager { /** * Fetches token data and creates {@link Token} by token's address and blockchain. + * + * @example + * ```ts + * const token = await sdk.tokens.createToken({ + * blockchain: BLOCKCHAIN_NAME.ETHEREUM, + * address: '0xdac17f958d2ee523a2206206994597c13d831ec7' + * }); + * + * console.log(token.symbol); // USDT + * console.log(token.name); // Tether USD + * console.log(token.decimals); // 6 + * ``` + * * @param tokenBaseStruct Base token's structure. */ public createToken(tokenBaseStruct: TokenBaseStruct): Promise { @@ -57,6 +70,17 @@ export class TokensManager { /** * Creates {@link PriceToken} from full token structure (without price) or from token address and blockchain. + * + * @example + * ```ts + * const token = await sdk.tokens.createPriceToken({ + * blockchain: BLOCKCHAIN_NAME.ETHEREUM, + * address: '0xdac17f958d2ee523a2206206994597c13d831ec7' + * }); + * + * console.log(token.price.toFormat(2)); // 1.00 + * ``` + * * @param token Full or base token's structure. */ public createPriceToken(token: TokenBaseStruct | TokenStruct): Promise { @@ -79,6 +103,19 @@ export class TokensManager { /** * Creates {@link PriceTokenAmount} from full token structure (without price) or * from token address and blockchain. + * + * @example + * ```ts + * const token = await sdk.tokens.createPriceTokenAmount({ + * blockchain: BLOCKCHAIN_NAME.ETHEREUM, + * address: '0xdac17f958d2ee523a2206206994597c13d831ec7', + * tokenAmount: new BigNumber(1) + * }); + * + * console.log(token.tokenAmount.toNumber()); // 1 + * console.log(token.stringWeiAmount); // 1000000 + * ``` + * * @param priceTokenAmountStruct Full or base token's structure with amount. */ public createPriceTokenAmount( From b01bbbd81fa29cb82e20b2aa6fbb6bebce1eb36c Mon Sep 17 00:00:00 2001 From: ottebrut Date: Tue, 21 Jun 2022 14:35:52 +0300 Subject: [PATCH 12/13] Update version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 6d5140f8f3..f06e662d1e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rubic-sdk", - "version": "2.0.0", + "version": "2.0.1", "description": "Simplify dApp creation", "main": "lib/index.js", "types": "lib/index.d.ts", From 8394d829d210368fc4fef6ed95ed6ad7610d0bc3 Mon Sep 17 00:00:00 2001 From: ottebrut Date: Tue, 21 Jun 2022 14:39:57 +0300 Subject: [PATCH 13/13] Update ci for typedoc --- .github/workflows/ci-docs.yml | 38 +++++++++++++++++++++++++++++++++ .github/workflows/ci-master.yml | 6 ------ 2 files changed, 38 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/ci-docs.yml diff --git a/.github/workflows/ci-docs.yml b/.github/workflows/ci-docs.yml new file mode 100644 index 0000000000..f29393ff58 --- /dev/null +++ b/.github/workflows/ci-docs.yml @@ -0,0 +1,38 @@ +name: Documentation generation + +on: + push: + branches: + - master + +jobs: + lint: + name: Generate docs and push to github pages + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + + - name: Read .nvmrc + run: echo ::set-output name=NVMRC::$(cat .nvmrc) + id: nvm + + - name: Set up Node.js + uses: actions/setup-node@v2 + with: + node-version: '${{ steps.nvm.outputs.NVMRC }}' + + - name: Set up yarn + run: npm install --global yarn + + - name: Set up dependencies + run: yarn + + - name: Generate docs + run: yarn docs + + - name: Deploy Github Page + uses: peaceiris/actions-gh-pages@v3 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: ./docs diff --git a/.github/workflows/ci-master.yml b/.github/workflows/ci-master.yml index e4a9b2bb84..e228a39250 100644 --- a/.github/workflows/ci-master.yml +++ b/.github/workflows/ci-master.yml @@ -36,9 +36,3 @@ jobs: - name: Build bundle run: yarn build - - - name: Deploy Github Page - uses: peaceiris/actions-gh-pages@v3 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - publish_dir: ./docs