UNPKG

@bancor/carbon-sdk

Version:

The SDK is a READ-ONLY tool, intended to facilitate working with Carbon contracts. It's a convenient wrapper around our matching algorithm, allowing programs and users get a ready to use transaction data that will allow them to manage strategies and fulfi

394 lines 22.1 kB
import { PopulatedTransaction } from '@ethersproject/contracts'; import { PayableOverrides } from 'ethers'; import { ChainCache } from '../chain-cache'; import { ContractsApi } from '../contracts-api'; import { Filter, Action, Strategy, StrategyUpdate, OrdersMapBNStr, MatchActionBNStr, TradeActionBNStr, EncodedStrategyBNStr, MatchType, TokenPair } from '../common/types'; import { DecimalFetcher } from '../utils/decimals'; /** * Enum representing options for the marginal price parameter of the function. */ export declare enum MarginalPriceOptions { /** Indicates that the marginal price should be reset to its default value. */ reset = "RESET", /** Indicates that the marginal price should be maintained at its current value. */ maintain = "MAINTAIN" } export declare function isMarginalPriceValue(marginalPrice?: MarginalPriceOptions | string): boolean; export declare class Toolkit { private _api; private _decimals; private _cache; /** * Constructs a new Toolkit instance. * * @param {ContractsApi} api - The ContractsApi instance. * @param {DecimalFetcher} [decimalFetcher] - Optional DecimalFetcher. */ constructor(api: ContractsApi, cache: ChainCache, decimalFetcher?: DecimalFetcher); getMinMaxPricesByAddresses(baseToken: string, quoteToken: string): Promise<{ minBuyPrice: string; maxSellPrice: string; }>; static getMatchActions(amountWei: string, tradeByTargetAmount: boolean, ordersMap: OrdersMapBNStr, matchType?: MatchType, filter?: Filter): MatchActionBNStr[]; /** * Returns whether a pair has liquidity * * @param {string} sourceToken - address of the token the trade sells. * @param {string} targetToken - address of the token the trade buys. * * @returns {Boolean} true or false. * @throws {Error} If `startDataSync` has not been called. * @throws {Error} If no orders have been found. */ hasLiquidityByPair(sourceToken: string, targetToken: string): Promise<boolean>; /** * Returns liquidity for a given pair. * * @param {string} sourceToken - address of the token the trade sells. * @param {string} targetToken - address of the token the trade buys. * * @returns {Promise<String>} liquidity value as string * @throws {Error} If `startDataSync` has not been called. */ getLiquidityByPair(sourceToken: string, targetToken: string): Promise<string>; /** * Returns the maximum source amount for a given pair. * This is the sum of all source amounts in the orderbook. * This number represents the maximum amount that can be traded by source. * * @param {string} sourceToken - Address of the token the trade sells. * @param {string} targetToken - Address of the token the trade buys. * * @returns {Promise<string>} Maximum source amount as a string. * @throws {Error} If `startDataSync` has not been called. */ getMaxSourceAmountByPair(sourceToken: string, targetToken: string): Promise<string>; /** * Gets the strategy by its id * * If the cache is synced, it will return the strategy from the cache. * Otherwise, it will fetch the strategy from the chain. * * @param {string} id - ID of the strategy to fetch. */ getStrategyById(id: string): Promise<Strategy>; /** * Gets all the strategies that belong to the given pair * * If the cache is synced, it will return the strategies from the cache. * Otherwise, it will fetch the strategies from the chain. * * @param {string} token0 - Address of one of the tokens in the pair - the order is not important. * @param {string} token1 - Address of one of the tokens in the pair - the order is not important. */ getStrategiesByPair(token0: string, token1: string): Promise<Strategy[]>; /** * Gets all the strategies that belong to pairs in the given list. * If the cache is synced, it will return the strategies from the cache. * Otherwise, it will fetch the strategies from the chain. * * @param {TokenPair[]} pairs - List of pairs to get strategies for. If undefined, all pairs will be fetched. * * @returns {Promise<{ * pair: TokenPair; * strategies: Strategy[]; * }[]>} An array of pairs and their strategies. */ getStrategiesByPairs(pairs?: TokenPair[]): Promise<{ pair: TokenPair; strategies: Strategy[]; }[]>; /** * Gets the strategies that are owned by the user. * It does so by reading the voucher token and * figuring out strategy IDs from them. * It is possible to pass a synced cache and in that case * the strategies will be read from the cache first. * @param {string} user - The user who owns the strategies. * * @returns {Promise<Strategy[]>} An array of owned strategies. * */ getUserStrategies(user: string): Promise<Strategy[]>; /** * Returns the data needed to process a trade. * `getMatchParams` returns the data for a given source and target token pair. * You can use the result to call `matchBySourceAmount` or `matchByTargetAmount`, * then get the actions and pass them to `getTradeDataFromActions`. * * @param {string} sourceToken - Address of the source token. * @param {string} targetToken - Address of the target token. * @param {string} amount - The amount of tokens to trade. * @param {boolean} tradeByTargetAmount - Whether to trade by target amount (`true`) or source amount (`false`). * * @returns {Promise<Object>} An object containing the necessary data to process a trade. * @property {OrdersMap} orders - The orders mapped by their IDs. * @property {string} amountWei - The amount in wei to trade. * @property {number} sourceDecimals - The number of decimals for the source token. * @property {number} targetDecimals - The number of decimals for the target token. */ getMatchParams(sourceToken: string, targetToken: string, amount: string, tradeByTargetAmount: boolean): Promise<{ orders: OrdersMapBNStr; amountWei: string; sourceDecimals: number; targetDecimals: number; }>; /** * Returns the off-chain match algorithm results of orders to fulfill to complete the trade. * Each trade action is identified by the ID of the strategy that the trade order belongs to * and the input amount to place for this order. * * The `getTradeData` method will match the specified `amount` of source tokens or target tokens * with available orders from the blockchain, depending on the value of `tradeByTargetAmount`. * It uses the provided `filter` function to filter the available orders. The resulting trade * actions will be returned in an object, along with the unsigned transaction that can be used * to execute the trade. * * It is up to the user to sign and send the transaction. * * @param {string} sourceToken - The source token for the trade. * @param {string} targetToken - The target token for the trade. * @param {string} amount - The amount of source tokens or target tokens to trade, depending on the value of `tradeByTargetAmount`. * @param {boolean} tradeByTargetAmount - Whether to trade by target amount (`true`) or source amount (`false`). * @param {MatchType} [matchType] - The type of match to perform. Defaults to `MatchType.Fast`. * @param {(rate: Rate) => boolean} [filter] - Optional function to filter the available orders. * * @returns {Promise<Object>} An object containing the trade actions and other relevant data. * @property {TradeAction[]} tradeActions - An array of trade actions in wei. * @property {Action[]} actionsTokenRes - An array of trade actions in the proper token resolution. * @property {string} totalSourceAmount - The total input amount in token resolution. * @property {string} totalTargetAmount - The total output amount in token resolution. * @property {string} effectiveRate - The effective rate between totalInput and totalOutput * @property {MatchAction[]} actionsWei - An array of trade actions in wei. * @throws {Error} If `startDataSync` has not been called. */ getTradeData(sourceToken: string, targetToken: string, amount: string, tradeByTargetAmount: boolean, matchType?: MatchType, filter?: Filter): Promise<{ tradeActions: TradeActionBNStr[]; actionsTokenRes: Action[]; totalSourceAmount: string; totalTargetAmount: string; effectiveRate: string; actionsWei: MatchActionBNStr[]; }>; getTradeDataFromActions(sourceToken: string, targetToken: string, tradeByTargetAmount: boolean, actionsWei: MatchActionBNStr[]): Promise<{ tradeActions: TradeActionBNStr[]; actionsTokenRes: Action[]; totalSourceAmount: string; totalTargetAmount: string; effectiveRate: string; actionsWei: MatchActionBNStr[]; }>; /** * Creates an unsigned transaction to fulfill a trade using an array of trade actions. * Each trade action is identified by the ID of the strategy that the trade order belongs to * and the input amount to place for this order. * * It is up to the user to sign and send the transaction. * * @param {string} sourceToken - The source token for the trade. * @param {string} targetToken - The target token for the trade. * @param {TradeAction[]} tradeActions - An array of trade actions in wei - as received from `trade`. * @param {string} deadline - Deadline for the trade * @param {string} maxInput - Maximum input for the trade * @param {Overrides} [overrides] - Optional overrides for the transaction. * @returns {Promise<PopulatedTransaction>} A promise that resolves to the unsigned trade transaction. * * @example * // calling trade * const tradeTx = sdk.composeTradeTransaction( * '0xE0B7927c4aF23765Cb51314A0E0521A9645F0E2A', * '0x6B175474E89094C44Da98b954EedeAC495271d0F', * false, * [] * ); * * // Performing the trade by signing and sending the transaction: * * // Import the ethers.js library and the relevant wallet provider * const ethers = require('ethers'); * const provider = new ethers.providers.Web3Provider(web3.currentProvider); * * // Load the private key for the wallet that will sign and send the transaction * const privateKey = '0x...'; * const wallet = new ethers.Wallet(privateKey, provider); * * // Sign and send the transaction * const signedTradeTx = await wallet.sign(tradeTx); * const txReceipt = await provider.sendTransaction(signedTradeTx); * console.log(txReceipt); * // { * // blockHash: '0x...', * // blockNumber: 12345, * // ... * // } */ composeTradeByTargetTransaction(sourceToken: string, targetToken: string, tradeActions: TradeActionBNStr[], deadline: string, maxInput: string, overrides?: PayableOverrides): Promise<PopulatedTransaction>; /** * Creates an unsigned transaction to fulfill a trade using an array of trade actions. * Each trade action is identified by the ID of the strategy that the trade order belongs to * and the input amount to place for this order. * * It is up to the user to sign and send the transaction. * * @param {string} sourceToken - The source token for the trade. * @param {string} targetToken - The target token for the trade. * @param {TradeAction[]} tradeActions - An array of trade actions in wei - as received from `trade`. * @param {string} deadline - Deadline for the trade * @param {string} minReturn - Minimum return for the trade * @param {Overrides} [overrides] - Optional overrides for the transaction. * @returns {Promise<PopulatedTransaction>} A promise that resolves to the unsigned trade transaction. * * @example * // calling trade * const tradeTx = sdk.composeTradeTransaction( * '0xE0B7927c4aF23765Cb51314A0E0521A9645F0E2A', * '0x6B175474E89094C44Da98b954EedeAC495271d0F', * false, * [] * ); * * // Performing the trade by signing and sending the transaction: * * // Import the ethers.js library and the relevant wallet provider * const ethers = require('ethers'); * const provider = new ethers.providers.Web3Provider(web3.currentProvider); * * // Load the private key for the wallet that will sign and send the transaction * const privateKey = '0x...'; * const wallet = new ethers.Wallet(privateKey, provider); * * // Sign and send the transaction * const signedTradeTx = await wallet.sign(tradeTx); * const txReceipt = await provider.sendTransaction(signedTradeTx); * console.log(txReceipt); * // { * // blockHash: '0x...', * // blockNumber: 12345, * // ... * // } */ composeTradeBySourceTransaction(sourceToken: string, targetToken: string, tradeActions: TradeActionBNStr[], deadline: string, minReturn: string, overrides?: PayableOverrides): Promise<PopulatedTransaction>; /** * Calculates the sell budget given a buy budget of an overlapping strategy. * * @param {string} baseToken - The address of the base token for the strategy. * @param {string} buyPriceLow - The minimum buy price for the strategy, in in `quoteToken` per 1 `baseToken`, as a string. * @param {string} sellPriceHigh - The maximum sell price for the strategy, in `quoteToken` per 1 `baseToken`, as a string. * @param {string} marketPrice - The market price, in `quoteToken` per 1 `baseToken`, as a string. * @param {string} spreadPercentage - The spread percentage, e.g. for 10%, enter `10`. * @param {string} buyBudget - The budget for buying tokens in the strategy, in `quoteToken`, as a string. * @return {Promise<string>} The result of the calculation - the sell budget in token res in base token. */ calculateOverlappingStrategySellBudget(baseToken: string, quoteToken: string, buyPriceLow: string, sellPriceHigh: string, marketPrice: string, spreadPercentage: string, buyBudget: string): Promise<string>; /** * Calculates the buy budget given a sell budget of an overlapping strategy. * * @param {string} quoteToken - The address of the base token for the strategy. * @param {string} buyPriceLow - The minimum buy price for the strategy, in in `quoteToken` per 1 `baseToken`, as a string. * @param {string} sellPriceHigh - The maximum sell price for the strategy, in `quoteToken` per 1 `baseToken`, as a string. * @param {string} marketPrice - The market price, in `quoteToken` per 1 `baseToken`, as a string. * @param {string} spreadPercentage - The spread percentage, e.g. for 10%, enter `10`. * @param {string} sellBudget - The budget for selling tokens in the strategy, in `baseToken`, as a string. * @return {Promise<string>} The result of the calculation - the buy budget in token res in quote token. */ calculateOverlappingStrategyBuyBudget(baseToken: string, quoteToken: string, buyPriceLow: string, sellPriceHigh: string, marketPrice: string, spreadPercentage: string, sellBudget: string): Promise<string>; /** * Creates an unsigned transaction to create a strategy for buying and selling tokens of `baseToken` for price in `quoteToken` per 1 `baseToken`. * * The `createBuySellStrategy` method creates a strategy object based on the specified parameters, encodes it according to the * format used by the smart contracts, and returns an unsigned transaction that can be used to create the strategy on the * blockchain. * * It is up to the user to sign and send the transaction. * * @param {string} baseToken - The address of the base token for the strategy. * @param {string} quoteToken - The address of the quote token for the strategy. * @param {string} buyPriceLow - The minimum buy price for the strategy, in in `quoteToken` per 1 `baseToken`, as a string. * @param {string} buyPriceMarginal - The marginal buy price for the strategy, in in `quoteToken` per 1 `baseToken`, as a string. * @param {string} buyPriceHigh - The maximum buy price for the strategy, in `quoteToken` per 1 `baseToken`, as a string. * @param {string} buyBudget - The maximum budget for buying tokens in the strategy, in `quoteToken`, as a string. * @param {string} sellPriceLow - The minimum sell price for the strategy, in `quoteToken` per 1 `baseToken`, as a string. * @param {string} sellPriceMarginal - The marginal sell price for the strategy, in `quoteToken` per 1 `baseToken`, as a string. * @param {string} sellPriceHigh - The maximum sell price for the strategy, in `quoteToken` per 1 `baseToken`, as a string. * @param {string} sellBudget - The maximum budget for selling tokens in the strategy, in `baseToken`, as a string. * @param {Overrides} [overrides] - Optional overrides for the transaction, such as gas price or nonce. * @returns {Promise<PopulatedTransaction>} A promise that resolves to the unsigned transaction that can be used to create the strategy. * * * @example * // Import the ethers.js library and the relevant wallet provider * const ethers = require('ethers'); * const provider = new ethers.providers.Web3Provider(web3.currentProvider); * * // Load the private key for the wallet that will sign and send the transaction * const privateKey = '0x...'; * const wallet = new ethers.Wallet(privateKey, provider); * * // Call the createBuySellStrategy method to create an unsigned transaction * const createStrategyTx = sdk.createBuySellStrategy( * '0xE0B7927c4aF23765Cb51314A0E0521A9645F0E2A', * '0x6B175474E89094C44Da98b954EedeAC495271d0F', * '0.1', * '0.2', * '0.2', * '1', * '0.5', * '0.5', * '0.6', * '2' * ); * * // Sign and send the transaction * const signedCreateStrategyTx = await wallet.sign(createStrategyTx); * const txReceipt = await provider.sendTransaction(signedCreateStrategyTx); */ createBuySellStrategy(baseToken: string, quoteToken: string, buyPriceLow: string, buyPriceMarginal: string, buyPriceHigh: string, buyBudget: string, sellPriceLow: string, sellPriceMarginal: string, sellPriceHigh: string, sellBudget: string, overrides?: PayableOverrides): Promise<PopulatedTransaction>; /** * Creates an unsigned transaction to create multiple strategies - similarly to `createBuySellStrategy`. * * @param {Strategy[]} strategies - An array of strategies to create. * @param {Overrides} [overrides] - Optional overrides for the transaction, such as gas price or nonce. * @returns {Promise<PopulatedTransaction>} A promise that resolves to the unsigned transaction that can be used to create the strategies. */ batchCreateBuySellStrategies(strategies: { baseToken: string; quoteToken: string; buyPriceLow: string; buyPriceMarginal: string; buyPriceHigh: string; buyBudget: string; sellPriceLow: string; sellPriceMarginal: string; sellPriceHigh: string; sellBudget: string; }[], overrides?: PayableOverrides): Promise<PopulatedTransaction>; /** * Creates an unsigned transaction to update an on chain strategy. * This function takes various optional parameters to update different aspects of the strategy and returns a promise that resolves to a PopulatedTransaction object. * * @param {string} strategyId - The unique identifier of the strategy to be updated. * @param {EncodedStrategyBNStr} encoded - The encoded strategy string, representing the current state of the strategy in the contracts. * @param {StrategyUpdate} strategyUpdate - An object containing optional fields to update in the strategy, including buy and sell price limits and budgets. * @param {MarginalPriceOptions | string} [buyPriceMarginal] - Optional parameter that can be used to instruct the SDK what to do with the marginal price - or pass a value to use. * If unsure leave this undefined. * @param {MarginalPriceOptions | string} [sellPriceMarginal] - Optional parameter that can be used to instruct the SDK what to do with the marginal price - or pass a value to use. * If unsure leave this undefined. * @param {PayableOverrides} [overrides] - Optional Ethereum transaction overrides. * @returns {Promise<PopulatedTransaction>} A promise that resolves to a PopulatedTransaction object. */ updateStrategy(strategyId: string, encoded: EncodedStrategyBNStr, { buyPriceLow, buyPriceHigh, buyBudget, sellPriceLow, sellPriceHigh, sellBudget, }: StrategyUpdate, buyPriceMarginal?: MarginalPriceOptions | string, sellPriceMarginal?: MarginalPriceOptions | string, overrides?: PayableOverrides): Promise<PopulatedTransaction>; deleteStrategy(strategyId: string): Promise<PopulatedTransaction>; /** * Returns liquidity for a given rate. * * @param {string} sourceToken - address of the token the trade sells. * @param {string} targetToken - address of the token the trade buys. * @param {string[]} rates - the rates for which to find liquidity depth. * * @returns {Promise<String[]>} liquidity value as string * @throws {Error} If `startDataSync` has not been called. */ getRateLiquidityDepthsByPair(sourceToken: string, targetToken: string, rates: string[]): Promise<string[]>; getMinRateByPair(sourceToken: string, targetToken: string): Promise<string>; getMaxRateByPair(sourceToken: string, targetToken: string): Promise<string>; } //# sourceMappingURL=Toolkit.d.ts.map