@sky-mavis/katana-swap
Version:
Katana Swap SDK
512 lines (485 loc) • 17.6 kB
text/typescript
import { ChainId, RON } from '@sky-mavis/katana-core';
export { DEFAULT_ERC20 } from '@sky-mavis/katana-core';
import { TradeType, Token, Percent, Currency, CurrencyAmount, Price } from '@uniswap/sdk-core';
export { TradeType } from '@uniswap/sdk-core';
import { BigNumber, ContractTransaction } from 'ethers';
import { Web3Provider } from '@ethersproject/providers';
import { PermitSingle } from '@uniswap/permit2-sdk';
import * as _ethersproject_abstract_provider from '@ethersproject/abstract-provider';
import { MixedRouteSDK, Trade } from '@uniswap/router-sdk';
import { Route as Route$1 } from '@uniswap/v2-sdk';
import { Route } from '@uniswap/v3-sdk';
declare enum QuoteIntent {
Pricing = "pricing",
Quote = "quote"
}
declare enum SwapRouterNativeAssets {
RON = "RON"
}
type WalletInfo = {
account: string;
provider: Web3Provider;
};
type CommonApproveTokenArgs = {
tokenAddress: string;
owner: string;
chainId: ChainId;
spender?: string;
};
type CheckIsTokenApprovedArgs = CommonApproveTokenArgs & {
amount: string;
};
type GetTokenAllowanceArgs = CommonApproveTokenArgs;
type ApproveTokenArgs = Omit<CommonApproveTokenArgs, 'owner'> & {
wallet: WalletInfo;
amount?: string;
};
type TradeTypeParam = 'exactIn' | 'exactOut';
type GetQuoteArgs = {
chainId: ChainId;
tokenInAddress: string | SwapRouterNativeAssets;
tokenOutAddress: string | SwapRouterNativeAssets;
tradeType: TradeType;
amount: string;
intent?: QuoteIntent;
portionBips?: QuoteQueryParams['portionBips'];
portionRecipient?: QuoteQueryParams['portionRecipient'];
recipient?: QuoteQueryParams['recipient'];
};
type QuoteQueryParams = {
tokenInAddress: string;
tokenInChainId: number;
tokenOutAddress: string;
tokenOutChainId: number;
amount: string;
type: TradeTypeParam;
recipient?: string;
protocols?: string[] | string;
slippageTolerance?: string;
deadline?: string;
algorithm?: string;
gasPriceWei?: string;
minSplits?: number;
forceCrossProtocol?: boolean;
forceMixedRoutes?: boolean;
simulateFromAddress?: string;
permitSignature?: string;
permitNonce?: string;
permitExpiration?: string;
permitAmount?: string;
permitSigDeadline?: string;
enableUniversalRouter?: boolean;
quoteSpeed?: string;
debugRoutingConfig?: string;
unicornSecret?: string;
intent?: string;
enableFeeOnTransferFeeFetching?: boolean;
portionBips?: number;
portionAmount?: string;
portionRecipient?: string;
source?: string;
gasToken?: string;
};
type TokenInRoute = Pick<Token, 'address' | 'chainId' | 'symbol' | 'decimals'> & {
buyFeeBps?: string;
sellFeeBps?: string;
};
type V3PoolInRoute = {
type: 'v3-pool';
tokenIn: TokenInRoute;
tokenOut: TokenInRoute;
sqrtRatioX96: string;
liquidity: string;
tickCurrent: string;
fee: string;
amountIn?: string;
amountOut?: string;
address?: string;
};
type V2Reserve = {
token: TokenInRoute;
quotient: string;
};
type V2PoolInRoute = {
type: 'v2-pool';
tokenIn: TokenInRoute;
tokenOut: TokenInRoute;
reserve0: V2Reserve;
reserve1: V2Reserve;
amountIn?: string;
amountOut?: string;
address?: string;
};
type ClassicQuoteData = {
requestId?: string;
quoteId?: string;
blockNumber: string;
amount: string;
amountDecimals: string;
gasPriceWei?: string;
gasUseEstimate?: string;
gasUseEstimateQuote?: string;
gasUseEstimateQuoteDecimals?: string;
gasUseEstimateUSD?: string;
methodParameters?: {
calldata: string;
value: string;
};
quote: string;
quoteDecimals: string;
quoteGasAdjusted: string;
quoteGasAdjustedDecimals: string;
route: Array<(V3PoolInRoute | V2PoolInRoute)[]>;
routeString: string;
portionBips?: number;
portionRecipient?: string;
portionAmount?: string;
portionAmountDecimals?: string;
quoteGasAndPortionAdjusted?: string;
quoteGasAndPortionAdjustedDecimals?: string;
};
type SwapFeeInfo = {
recipient: string;
percent: Percent;
amount: string;
};
type RouteResult = {
routev3: Route<Currency, Currency> | null;
routev2: Route$1<Currency, Currency> | null;
mixedRoute: MixedRouteSDK<Currency, Currency> | null;
inputAmount: CurrencyAmount<Currency>;
outputAmount: CurrencyAmount<Currency>;
};
type KatanaTradeV2Route = {
routev2: Route$1<Currency, Currency>;
inputAmount: CurrencyAmount<Currency>;
outputAmount: CurrencyAmount<Currency>;
};
type KatanaTradeV3Route = {
routev3: Route<Currency, Currency>;
inputAmount: CurrencyAmount<Currency>;
outputAmount: CurrencyAmount<Currency>;
};
type KatanaTradeMixedRoute = {
mixedRoute: MixedRouteSDK<Currency, Currency>;
inputAmount: CurrencyAmount<Currency>;
outputAmount: CurrencyAmount<Currency>;
};
type KatanaTradeRoutes = {
v2Routes: KatanaTradeV2Route[];
v3Routes: KatanaTradeV3Route[];
mixedRoutes: KatanaTradeMixedRoute[];
};
declare class KatanaTrade extends Trade<Currency, Currency, TradeType> {
blockNumber: string | null | undefined;
requestId: string | undefined;
swapFee: SwapFeeInfo | undefined;
gasUseEstimate?: number;
gasUseEstimateUSD?: number;
constructor({ blockNumber, requestId, swapFee, gasUseEstimate, gasUseEstimateUSD, ...routes }: {
gasUseEstimate?: number;
gasUseEstimateUSD?: number;
totalGasUseEstimateUSD?: number;
blockNumber?: string | null;
requestId?: string;
swapFee?: SwapFeeInfo;
v2Routes: KatanaTradeV2Route[];
v3Routes: KatanaTradeV3Route[];
mixedRoutes?: KatanaTradeMixedRoute[];
tradeType: TradeType;
});
get executionPrice(): Price<Currency, Currency>;
get postSwapFeeOutputAmount(): CurrencyAmount<Currency>;
}
type CreatePermitArgs = {
chainId: ChainId;
token: string;
nonce: number;
spender?: string;
amount?: BigNumber;
expiration?: number;
sigDeadline?: number;
};
type GetPermitAllowanceArgs = {
tokenAddress: string;
owner: string;
chainId: ChainId;
spender?: string;
};
type Permit = Omit<PermitSingle, 'sigDeadline'> & {
sigDeadline: number;
};
type PermitSignature = Permit & {
signature: string;
};
type SignPermitAllowanceArgs = {
wallet: WalletInfo;
permit: Permit;
chainId: ChainId;
};
type CheckIsValidPermitAllowanceSignatureArgs = {
chainId: ChainId;
token: string;
signature: PermitSignature | undefined;
now: number;
spender?: string;
};
type CheckIsValidPermitAllowanceArgs = {
permitAllowance: BigNumber | undefined;
permitExpiration: number | undefined;
amount: BigNumber;
now: number;
};
type ITokenTag = 'main' | 'seed';
type IAllPublicTokens = {
token_address: string;
token_symbol: string;
token_decimals: string;
token_name: string;
is_active: boolean;
tag: ITokenTag;
};
/**
* Approve token
* @param chainId - Chain ID
* @param tokenAddress - Token address
* @param wallet - Wallet object
* @param amount - Amount to approve (Optional - Default to MaxUint256)
* @param spender - Spender address (Optional - Default to permit2 address)
*/
declare const approveToken: ({ chainId, tokenAddress, wallet, amount, spender, }: ApproveTokenArgs) => Promise<ContractTransaction>;
/**
* Sign the permit allowance
* @param chainId Chain ID
* @param wallet Wallet object
* @param permit Permit object
* @returns Permit object with signature
*/
declare const signPermitAllowance: ({ chainId, wallet, permit }: SignPermitAllowanceArgs) => Promise<PermitSignature>;
type SwapArgs = {
chainId: ChainId;
wallet: WalletInfo;
trade: KatanaTrade;
permitSignature?: PermitSignature;
slippageTolerance?: Percent;
txDeadlineInSeconds?: number;
};
/**
* Swap ERC20 tokens using the Universal Router
* @param chainId - The chain ID
* @param wallet - Object containing the account and provider
* @param trade - The trade to execute
* @param permitSignature - The permit signature of the input token (Optional)
* @param txDeadlineInSeconds - The transaction deadline in seconds (Optional, default: 30 minutes)
* @param slippageTolerance - The slippage tolerance for the swap (Optional, default: 0.50%)
* @returns Transaction response
*/
declare const swap: ({ chainId, wallet: { account, provider }, trade, permitSignature, slippageTolerance, txDeadlineInSeconds, }: SwapArgs) => Promise<_ethersproject_abstract_provider.TransactionResponse>;
type UnWrapRonArgs = {
wallet: WalletInfo;
chainId: ChainId;
amount: string;
};
/**
* Wrap WRON to RON
* @param chainId - Chain id
* @param wallet - Wallet info
* @param amount - Amount to unwrap
*/
declare const unwrapRon: ({ amount, chainId, wallet }: UnWrapRonArgs) => Promise<ContractTransaction>;
type WrapRonArgs = {
chainId: ChainId;
wallet: WalletInfo;
amount: string;
};
/**
* Wrap RON to WRON
* @param chainId - Chain id
* @param wallet - Wallet info
* @param amount - Amount to wrap
*/
declare const wrapRon: ({ amount, chainId, wallet }: WrapRonArgs) => Promise<ContractTransaction>;
/**
* Get permit allowance data of a token for a given owner and spender
* @param chainId Network chain ID
* @param tokenAddress Token address
* @param owner Owner address
* @param spender Spender address (Optional - Default to universal router address)
* @returns Permit allowance data of Token
*/
declare const getPermitAllowance: ({ chainId, tokenAddress, owner, spender, }: GetPermitAllowanceArgs) => Promise<{
amount: BigNumber;
expiration: number;
nonce: number;
}>;
/**
* Get allowance of a token for a given owner and spender
* @param tokenAddress Token address
* @param owner Owner address
* @param chainId Network chain ID
* @param spender Spender address (Optional - Default to permit2 address)
* @returns Allowance of Token
*/
declare const getTokenAllowance: ({ tokenAddress, owner, spender, chainId, }: GetTokenAllowanceArgs) => Promise<BigNumber>;
type GetTokenBalancesArgs = {
tokens: string[];
account: string;
chainId: ChainId;
};
/**
* Get balance of tokens for a given account
* @param chainId - Chain ID
* @param account - Account address
* @param tokens - Array of token addresses
* @returns Object with token addresses as keys and balances as values
*/
declare const getTokenBalances: ({ chainId, account, tokens, }: GetTokenBalancesArgs) => Promise<{
[tokenAddress: string]: BigNumber | null;
}>;
type GetRonBalanceArgs = {
account: string;
chainId: ChainId;
};
/**
* Get RON balance for a given account
* @param account - Account address
* @param chainId - Chain ID
* @returns RON balance
*/
declare const getRonBalance: ({ chainId, account }: GetRonBalanceArgs) => Promise<BigNumber>;
/**
* Get all tokens from Katana V2 and V3 subgraph
* @param chainId
*/
declare const getAllTokens: (chainId: ChainId) => Promise<{
mapTokens: {
[tokenAddressLowercase: string]: Token;
};
arrTokens: Token[];
arrTokenAddresses: string[];
}>;
/**
* Get RON price (USD) from Pyth
* @param chainId - Network chain ID
* @returns RON price (USD)
*/
declare const getRonPricePyth: (chainId: ChainId) => Promise<number>;
/**
* Get best trade using routing API
* @param chainId - Chain ID
* @param tokenInAddress - Token in address
* @param tokenOutAddress - Token out address
* @param amount - Amount to swap
* @param tradeType - Trade type
* @param portionBips - Portion bips (Optional)
* @param portionRecipient - Portion recipient (Optional)
* @param recipient - Recipient (Optional)
* @returns Object Trade | null if no route is found
*/
declare const getBestTrade: (args: GetQuoteArgs) => Promise<KatanaTrade | null>;
type GetUSDCPriceArgs = {
chainId: ChainId;
tokenAddress: string;
};
type GetTokenPriceArgs = GetUSDCPriceArgs;
/**
* Get the price of the input token address based on the best trade route exact out to RON or USDC
* NOTE: RON price is prioritized over USDC price
* @param chainId - Chain ID
* @param tokenAddress - Token address
* @returns Object Price | null if no route is found
*/
declare const getTokenPrice: ({ chainId, tokenAddress, }: GetTokenPriceArgs) => Promise<Price<Currency, Token | RON> | null>;
/**
* Check if token is approved for a given owner and spender
* @param chainId Chain ID
* @param tokenAddress Token address
* @param owner Owner address
* @param amount Amount to approve
* @param spender Spender address (Optional - Default to permit2 address)
* @returns Object with allowance and isApproved flag
*/
declare const checkIsTokenApproved: ({ amount, ...restProps }: CheckIsTokenApprovedArgs) => Promise<{
allowance: BigNumber;
isApproved: boolean;
}>;
/**
* Get the interval time to check if the permit signature is still valid
* @param blockTime Average block time in milliseconds
* @returns Interval time in seconds
*/
declare const getIntervalTimeCheckPermit: (blockTime?: number) => number;
/**
* Check if the signature is valid for the permit allowance
* @param chainId Chain ID
* @param token Token address
* @param signature Signature
* @param now Current time in seconds (NOTE: Signature will expire, so it should be rechecked at an interval. Calculate now such that the signature will still be valid for the submitting block)
* @param spender Spender address (Optional - Default to universal router address)
* @returns Boolean
*/
declare const checkIsValidPermitAllowanceSignature: ({ chainId, token, signature, now, spender, }: CheckIsValidPermitAllowanceSignatureArgs) => boolean;
/**
* Check if the permit allowance is valid
* @param permitAllowance Permit allowance data read from the contract
* @param permitExpiration Permit expiration time
* @param amount Amount to check
* @param now Current time in seconds (NOTE: PermitAllowance will expire, so it should be rechecked at an interval. Calculate now such that the signature will still be valid for the submitting block)
* @returns Boolean
*/
declare const checkIsValidPermitAllowance: ({ permitAllowance, permitExpiration, amount, now, }: CheckIsValidPermitAllowanceArgs) => boolean;
/**
* Create a permit object
* @param chainId Chain ID
* @param token Token address
* @param nonce Nonce number
* @param spender Spender address (Optional - Default to Universal Router Address)
* @param amount Allowance transfer amount (Optional - Default to MaxAllowanceTransferAmount from permit2-sdk)
* @param expiration Permit expiration time (Optional - Default to 30 days)
* @param sigDeadline Permit signature expiration time (Optional - Default to 30 minutes)
* @returns
*/
declare const createPermitObj: ({ chainId, token, nonce, spender, amount, expiration, sigDeadline, }: CreatePermitArgs) => Permit;
type CheckIsInsufficientBalanceArgs = {
chainId: ChainId;
tokenAddress: string;
account: string;
amount: string;
};
/**
* Utility function to check if the erc20 balance is insufficient for the requested amount
* @param chainId - Chain ID
* @param account - Account address
* @param tokenAddress - Token address
* @param amount - Requested amount in raw format
* @returns Object with token balance and isInsufficient flag
*/
declare const checkIsInsufficientBalance: ({ chainId, account, tokenAddress, amount, }: CheckIsInsufficientBalanceArgs) => Promise<{
tokenBalance?: BigNumber;
isInsufficient: boolean;
}>;
type CheckIsInsufficientRonBalanceArgs = {
chainId: ChainId;
account: string;
amount: string;
};
/**
* Utility function to check if the ron balance is insufficient for the requested amount
* @param chainId - Chain ID
* @param account - Account address
* @param amount - Requested amount in raw format
* @returns Object with token balance and isInsufficient flag
*/
declare const checkIsInsufficientRonBalance: ({ chainId, account, amount, }: CheckIsInsufficientRonBalanceArgs) => Promise<{
ronBalance?: BigNumber;
isInsufficient: boolean;
}>;
type QuoteTokenPriceArgs = {
tokenPrice: Price<Currency, Token | RON> | null;
ronPriceUSDFromPyth: number;
amount: string;
};
declare const quoteTokenPrice: ({ tokenPrice, ronPriceUSDFromPyth, amount }: QuoteTokenPriceArgs) => number | null;
declare const transformQuoteToTrade: (args: GetQuoteArgs, data: ClassicQuoteData) => KatanaTrade;
declare const getQuoteQueryParams: ({ chainId, tradeType, intent, ...restProps }: GetQuoteArgs) => QuoteQueryParams;
export { type ApproveTokenArgs, type CheckIsTokenApprovedArgs, type CheckIsValidPermitAllowanceArgs, type CheckIsValidPermitAllowanceSignatureArgs, type ClassicQuoteData, type CreatePermitArgs, type GetPermitAllowanceArgs, type GetQuoteArgs, type GetTokenAllowanceArgs, type IAllPublicTokens, KatanaTrade, type KatanaTradeRoutes, type Permit, type PermitSignature, QuoteIntent, type QuoteQueryParams, type RouteResult, type SignPermitAllowanceArgs, type SwapFeeInfo, SwapRouterNativeAssets, type TokenInRoute, type V2PoolInRoute, type V3PoolInRoute, type WalletInfo, approveToken, checkIsInsufficientBalance, checkIsInsufficientRonBalance, checkIsTokenApproved, checkIsValidPermitAllowance, checkIsValidPermitAllowanceSignature, createPermitObj, getAllTokens, getBestTrade, getIntervalTimeCheckPermit, getPermitAllowance, getQuoteQueryParams, getRonBalance, getRonPricePyth, getTokenAllowance, getTokenBalances, getTokenPrice, quoteTokenPrice, signPermitAllowance, swap, transformQuoteToTrade, unwrapRon, wrapRon };