@shapeshiftoss/swapper 14.2.3 → 14.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/dist/api.d.ts +1 -1
  2. package/dist/swappers/thorchain/ThorchainSwapper.d.ts +10 -5
  3. package/dist/swappers/thorchain/ThorchainSwapper.js +25 -24
  4. package/dist/swappers/thorchain/buildThorTrade/buildThorTrade.d.ts +4 -2
  5. package/dist/swappers/thorchain/buildThorTrade/buildThorTrade.js +3 -3
  6. package/dist/swappers/thorchain/getThorTradeQuote/getTradeQuote.js +10 -12
  7. package/dist/swappers/thorchain/types.d.ts +3 -17
  8. package/dist/swappers/thorchain/utils/{ethereum → evm}/makeTradeTx.d.ts +2 -2
  9. package/dist/swappers/thorchain/utils/{ethereum → evm}/makeTradeTx.js +0 -0
  10. package/dist/swappers/thorchain/utils/{ethereum → evm}/routerAbi.d.ts +0 -0
  11. package/dist/swappers/thorchain/utils/{ethereum → evm}/routerAbi.js +0 -0
  12. package/dist/swappers/thorchain/utils/{ethereum → evm}/routerCalldata.d.ts +0 -0
  13. package/dist/swappers/thorchain/utils/{ethereum → evm}/routerCalldata.js +0 -0
  14. package/dist/swappers/thorchain/utils/{ethereum → evm}/utils/getThorTxData.d.ts +0 -0
  15. package/dist/swappers/thorchain/utils/{ethereum → evm}/utils/getThorTxData.js +0 -0
  16. package/dist/swappers/thorchain/utils/getLimit/getLimit.js +2 -5
  17. package/dist/swappers/thorchain/utils/getUsdRate/getUsdRate.d.ts +2 -6
  18. package/dist/swappers/thorchain/utils/getUsdRate/getUsdRate.js +54 -30
  19. package/dist/swappers/thorchain/utils/test-data/responses.d.ts +2 -4
  20. package/dist/swappers/thorchain/utils/test-data/responses.js +13 -43
  21. package/dist/swappers/thorchain/utils/txFeeHelpers/evmTxFees/getEvmTxFees.d.ts +9 -0
  22. package/dist/swappers/thorchain/utils/txFeeHelpers/{ethTxFees/getEthTxFees.js → evmTxFees/getEvmTxFees.js} +3 -11
  23. package/dist/swappers/thorchain/utils/txFeeHelpers/{btcTxFees/getBtcTxFees.d.ts → utxoTxFees/getUtxoTxFees.d.ts} +2 -2
  24. package/dist/swappers/thorchain/utils/txFeeHelpers/{btcTxFees/getBtcTxFees.js → utxoTxFees/getUtxoTxFees.js} +4 -4
  25. package/dist/swappers/utils/helpers/helpers.d.ts +3 -3
  26. package/dist/swappers/zrx/types.d.ts +2 -2
  27. package/package.json +1 -1
  28. package/dist/swappers/thorchain/utils/txFeeHelpers/ethTxFees/getEthTxFees.d.ts +0 -9
package/dist/api.d.ts CHANGED
@@ -84,7 +84,7 @@ declare type CommonTradeInput = {
84
84
  };
85
85
  export declare type EvmSupportedChainIds = KnownChainIds.EthereumMainnet | KnownChainIds.AvalancheMainnet;
86
86
  export declare type CosmosSdkSupportedChainIds = KnownChainIds.CosmosMainnet | KnownChainIds.OsmosisMainnet | KnownChainIds.ThorchainMainnet;
87
- export declare type EvmSupportedChainAdapters = ethereum.ChainAdapter | avalanche.ChainAdapter;
87
+ export declare type EvmSupportedChainAdapter = ethereum.ChainAdapter | avalanche.ChainAdapter;
88
88
  export declare type CosmosSdkSupportedChainAdapters = cosmos.ChainAdapter | osmosis.ChainAdapter;
89
89
  export declare type UtxoSupportedChainIds = KnownChainIds.BitcoinMainnet | KnownChainIds.DogecoinMainnet | KnownChainIds.LitecoinMainnet | KnownChainIds.BitcoinCashMainnet;
90
90
  export declare type GetEvmTradeQuoteInput = CommonTradeInput & {
@@ -1,7 +1,8 @@
1
1
  import { Asset } from '@shapeshiftoss/asset-service';
2
2
  import { AssetId, ChainId } from '@shapeshiftoss/caip';
3
- import { KnownChainIds } from '@shapeshiftoss/types';
4
- import type { ApprovalNeededInput, ApprovalNeededOutput, ApproveInfiniteInput, BuildTradeInput, BuyAssetBySellIdInput, ExecuteTradeInput, GetTradeQuoteInput, Swapper, Trade, TradeQuote, TradeResult, TradeTxs } from '../../api';
3
+ import { ChainAdapterManager } from '@shapeshiftoss/chain-adapters';
4
+ import Web3 from 'web3';
5
+ import type { ApprovalNeededInput, ApprovalNeededOutput, ApproveInfiniteInput, BuildTradeInput, BuyAssetBySellIdInput, EvmSupportedChainIds, ExecuteTradeInput, GetTradeQuoteInput, Swapper, Trade, TradeQuote, TradeResult, TradeTxs } from '../../api';
5
6
  import { SwapperName, SwapperType } from '../../api';
6
7
  import { ThorchainSwapperDeps } from './types';
7
8
  export * from './types';
@@ -12,12 +13,16 @@ export declare class ThorchainSwapper implements Swapper<ChainId> {
12
13
  private supportedSellAssetIds;
13
14
  private supportedBuyAssetIds;
14
15
  deps: ThorchainSwapperDeps;
16
+ daemonUrl: string;
17
+ midgardUrl: string;
18
+ adapterManager: ChainAdapterManager;
19
+ web3: Web3;
15
20
  constructor(deps: ThorchainSwapperDeps);
16
21
  initialize(): Promise<void>;
17
22
  getType(): SwapperType;
18
- getUsdRate(input: Pick<Asset, 'symbol' | 'assetId'>): Promise<string>;
19
- approvalNeeded(input: ApprovalNeededInput<KnownChainIds.EthereumMainnet>): Promise<ApprovalNeededOutput>;
20
- approveInfinite(input: ApproveInfiniteInput<KnownChainIds.EthereumMainnet>): Promise<string>;
23
+ getUsdRate({ assetId }: Pick<Asset, 'assetId'>): Promise<string>;
24
+ approvalNeeded(input: ApprovalNeededInput<EvmSupportedChainIds>): Promise<ApprovalNeededOutput>;
25
+ approveInfinite(input: ApproveInfiniteInput<EvmSupportedChainIds>): Promise<string>;
21
26
  approveAmount(): Promise<string>;
22
27
  filterBuyAssetsBySellAssetId(args: BuyAssetBySellIdInput): AssetId[];
23
28
  filterAssetIdsBySellable(): AssetId[];
@@ -36,6 +36,7 @@ class ThorchainSwapper {
36
36
  [types_1.KnownChainIds.BitcoinCashMainnet]: true,
37
37
  [types_1.KnownChainIds.CosmosMainnet]: true,
38
38
  [types_1.KnownChainIds.ThorchainMainnet]: true,
39
+ [types_1.KnownChainIds.AvalancheMainnet]: true,
39
40
  };
40
41
  this.buySupportedChainIds = {
41
42
  [types_1.KnownChainIds.EthereumMainnet]: true,
@@ -45,31 +46,28 @@ class ThorchainSwapper {
45
46
  [types_1.KnownChainIds.BitcoinCashMainnet]: true,
46
47
  [types_1.KnownChainIds.CosmosMainnet]: true,
47
48
  [types_1.KnownChainIds.ThorchainMainnet]: true,
49
+ [types_1.KnownChainIds.AvalancheMainnet]: true,
48
50
  };
49
- this.supportedSellAssetIds = [];
50
- this.supportedBuyAssetIds = [];
51
+ this.supportedSellAssetIds = [caip_1.thorchainAssetId];
52
+ this.supportedBuyAssetIds = [caip_1.thorchainAssetId];
51
53
  this.deps = deps;
54
+ this.daemonUrl = deps.daemonUrl;
55
+ this.midgardUrl = deps.midgardUrl;
56
+ this.adapterManager = deps.adapterManager;
57
+ this.web3 = deps.web3;
52
58
  }
53
59
  async initialize() {
54
60
  try {
55
61
  const { data: allPools } = await thorService_1.thorService.get(`${this.deps.daemonUrl}/lcd/thorchain/pools`);
56
62
  const availablePools = allPools.filter((pool) => pool.status === 'Available');
57
- this.supportedSellAssetIds = availablePools.reduce((acc, pool) => {
63
+ availablePools.forEach((pool) => {
58
64
  const assetId = caip_1.adapters.poolAssetIdToAssetId(pool.asset);
59
- if (!assetId || !this.sellSupportedChainIds[(0, caip_1.fromAssetId)(assetId).chainId])
60
- return acc;
61
- acc.push(assetId);
62
- return acc;
63
- }, []);
64
- this.supportedSellAssetIds.push(caip_1.thorchainAssetId);
65
- this.supportedBuyAssetIds = availablePools.reduce((acc, pool) => {
66
- const assetId = caip_1.adapters.poolAssetIdToAssetId(pool.asset);
67
- if (!assetId || !this.buySupportedChainIds[(0, caip_1.fromAssetId)(assetId).chainId])
68
- return acc;
69
- acc.push(assetId);
70
- return acc;
71
- }, []);
72
- this.supportedBuyAssetIds.push(caip_1.thorchainAssetId);
65
+ if (!assetId)
66
+ return;
67
+ const { chainId } = (0, caip_1.fromAssetId)(assetId);
68
+ this.sellSupportedChainIds[chainId] && this.supportedSellAssetIds.push(assetId);
69
+ this.buySupportedChainIds[chainId] && this.supportedBuyAssetIds.push(assetId);
70
+ });
73
71
  }
74
72
  catch (e) {
75
73
  throw new api_1.SwapError('[thorchainInitialize]: initialize failed to set supportedAssetIds', {
@@ -81,8 +79,8 @@ class ThorchainSwapper {
81
79
  getType() {
82
80
  return api_1.SwapperType.Thorchain;
83
81
  }
84
- getUsdRate(input) {
85
- return (0, getUsdRate_1.getUsdRate)({ deps: this.deps, input });
82
+ async getUsdRate({ assetId }) {
83
+ return (0, getUsdRate_1.getUsdRate)(this.daemonUrl, assetId);
86
84
  }
87
85
  async approvalNeeded(input) {
88
86
  return (0, thorTradeApprovalNeeded_1.thorTradeApprovalNeeded)({ deps: this.deps, input });
@@ -165,7 +163,7 @@ class ThorchainSwapper {
165
163
  }
166
164
  }
167
165
  async getTradeTxs(tradeResult) {
168
- var _a, _b, _c, _d, _e, _f, _g;
166
+ var _a, _b, _c, _d;
169
167
  try {
170
168
  const midgardTxid = tradeResult.tradeId.startsWith('0x')
171
169
  ? tradeResult.tradeId.slice(2)
@@ -183,12 +181,15 @@ class ThorchainSwapper {
183
181
  code: api_1.SwapErrorTypes.TRADE_FAILED,
184
182
  cause: data,
185
183
  });
186
- const standardBuyTxid = ((_g = (_f = (_e = data === null || data === void 0 ? void 0 : data.actions[0]) === null || _e === void 0 ? void 0 : _e.out[0]) === null || _f === void 0 ? void 0 : _f.coins[0]) === null || _g === void 0 ? void 0 : _g.asset.startsWith('ETH.'))
187
- ? `0x${buyTxid}`
188
- : buyTxid;
184
+ const standardBuyTxid = (() => {
185
+ var _a, _b, _c;
186
+ const outCoinAsset = (_c = (_b = (_a = data === null || data === void 0 ? void 0 : data.actions[0]) === null || _a === void 0 ? void 0 : _a.out[0]) === null || _b === void 0 ? void 0 : _b.coins[0]) === null || _c === void 0 ? void 0 : _c.asset;
187
+ const isEvmCoinAsset = (outCoinAsset === null || outCoinAsset === void 0 ? void 0 : outCoinAsset.startsWith('ETH.')) || (outCoinAsset === null || outCoinAsset === void 0 ? void 0 : outCoinAsset.startsWith('AVAX.'));
188
+ return isEvmCoinAsset ? `0x${buyTxid}` : buyTxid;
189
+ })().toLowerCase();
189
190
  return {
190
191
  sellTxid: tradeResult.tradeId,
191
- buyTxid: standardBuyTxid.toLowerCase(),
192
+ buyTxid: standardBuyTxid,
192
193
  };
193
194
  }
194
195
  catch (e) {
@@ -1,7 +1,9 @@
1
1
  import { ChainId } from '@shapeshiftoss/caip';
2
2
  import { BuildTradeInput } from '../../../api';
3
3
  import { ThorchainSwapperDeps, ThorTrade } from '../types';
4
- export declare const buildTrade: ({ deps, input, }: {
4
+ declare type BuildTradeArgs = {
5
5
  deps: ThorchainSwapperDeps;
6
6
  input: BuildTradeInput;
7
- }) => Promise<ThorTrade<ChainId>>;
7
+ };
8
+ export declare const buildTrade: ({ deps, input }: BuildTradeArgs) => Promise<ThorTrade<ChainId>>;
9
+ export {};
@@ -8,8 +8,8 @@ const constants_1 = require("../../utils/constants");
8
8
  const getTradeQuote_1 = require("../getThorTradeQuote/getTradeQuote");
9
9
  const getThorTxData_1 = require("../utils/bitcoin/utils/getThorTxData");
10
10
  const getCosmosTxData_1 = require("../utils/cosmos/getCosmosTxData");
11
- const makeTradeTx_1 = require("../utils/ethereum/makeTradeTx");
12
- const buildTrade = async ({ deps, input, }) => {
11
+ const makeTradeTx_1 = require("../utils/evm/makeTradeTx");
12
+ const buildTrade = async ({ deps, input }) => {
13
13
  var _a, _b, _c, _d;
14
14
  try {
15
15
  const { buyAsset, receiveAddress: destinationAddress, sellAmountCryptoPrecision, sellAsset, bip44Params, slippage: slippageTolerance = constants_1.DEFAULT_SLIPPAGE, wallet, sendMax, } = input;
@@ -38,7 +38,7 @@ const buildTrade = async ({ deps, input, }) => {
38
38
  buyAssetTradeFeeUsd: quote.feeData.buyAssetTradeFeeUsd,
39
39
  });
40
40
  return {
41
- chainId: types_1.KnownChainIds.EthereumMainnet,
41
+ chainId: sellAsset.chainId,
42
42
  ...quote,
43
43
  receiveAddress: destinationAddress,
44
44
  txData: ethTradeTx.txToSign,
@@ -12,8 +12,8 @@ const getInboundAddressDataForChain_1 = require("../utils/getInboundAddressDataF
12
12
  const getTradeRate_1 = require("../utils/getTradeRate/getTradeRate");
13
13
  const getUsdRate_1 = require("../utils/getUsdRate/getUsdRate");
14
14
  const isRune_1 = require("../utils/isRune/isRune");
15
- const getBtcTxFees_1 = require("../utils/txFeeHelpers/btcTxFees/getBtcTxFees");
16
- const getEthTxFees_1 = require("../utils/txFeeHelpers/ethTxFees/getEthTxFees");
15
+ const getEvmTxFees_1 = require("../utils/txFeeHelpers/evmTxFees/getEvmTxFees");
16
+ const getUtxoTxFees_1 = require("../utils/txFeeHelpers/utxoTxFees/getUtxoTxFees");
17
17
  const getThorTradeQuote = async ({ deps, input }) => {
18
18
  const { sellAsset, buyAsset, sellAmountCryptoPrecision, bip44Params, chainId, receiveAddress, sendMax, } = input;
19
19
  if (!bip44Params) {
@@ -36,11 +36,8 @@ const getThorTradeQuote = async ({ deps, input }) => {
36
36
  ? constants_2.RUNE_OUTBOUND_TRANSACTION_FEE_CRYPTO_HUMAN.toString()
37
37
  : (0, bignumber_1.fromBaseUnit)((0, bignumber_1.bnOrZero)(buyAssetAddressData === null || buyAssetAddressData === void 0 ? void 0 : buyAssetAddressData.outbound_fee), constants_3.THORCHAIN_FIXED_PRECISION);
38
38
  const buyAssetChainFeeAssetId = buyAdapter.getFeeAssetId();
39
- const sellAssetUsdRate = await (0, getUsdRate_1.getUsdRate)({ deps, input: { assetId: sellAsset.assetId } });
40
- const buyFeeAssetUsdRate = await (0, getUsdRate_1.getUsdRate)({
41
- deps,
42
- input: { assetId: buyAssetChainFeeAssetId },
43
- });
39
+ const sellAssetUsdRate = await (0, getUsdRate_1.getUsdRate)(deps.daemonUrl, sellAsset.assetId);
40
+ const buyFeeAssetUsdRate = await (0, getUsdRate_1.getUsdRate)(deps.daemonUrl, buyAssetChainFeeAssetId);
44
41
  const buyAssetTradeFeeUsd = (0, bignumber_1.bn)(buyFeeAssetUsdRate)
45
42
  .times(estimatedBuyAssetTradeFeeFeeAssetCryptoHuman)
46
43
  .toString();
@@ -67,12 +64,13 @@ const getThorTradeQuote = async ({ deps, input }) => {
67
64
  switch (chainNamespace) {
68
65
  case caip_1.CHAIN_NAMESPACE.Evm:
69
66
  return (async () => {
70
- const ethAddressData = await (0, getInboundAddressDataForChain_1.getInboundAddressDataForChain)(deps.daemonUrl, caip_1.ethAssetId);
67
+ const sellChainFeeAssetId = sellAdapter.getFeeAssetId();
68
+ const ethAddressData = await (0, getInboundAddressDataForChain_1.getInboundAddressDataForChain)(deps.daemonUrl, sellChainFeeAssetId);
71
69
  const router = ethAddressData === null || ethAddressData === void 0 ? void 0 : ethAddressData.router;
72
70
  if (!router)
73
- throw new api_1.SwapError('[getThorTradeQuote] No router address found for ETH');
74
- const feeData = await (0, getEthTxFees_1.getEthTxFees)({
75
- adapterManager: deps.adapterManager,
71
+ throw new api_1.SwapError(`[getThorTradeQuote] No router address found for ${sellChainFeeAssetId}`);
72
+ const feeData = await (0, getEvmTxFees_1.getEvmTxFees)({
73
+ adapter: sellAdapter,
76
74
  sellAssetReference,
77
75
  buyAssetTradeFeeUsd,
78
76
  });
@@ -94,7 +92,7 @@ const getThorTradeQuote = async ({ deps, input }) => {
94
92
  xpub: input.xpub,
95
93
  buyAssetTradeFeeUsd,
96
94
  });
97
- const feeData = await (0, getBtcTxFees_1.getBtcTxFees)({
95
+ const feeData = await (0, getUtxoTxFees_1.getUtxoTxFees)({
98
96
  sellAmountCryptoPrecision,
99
97
  vault,
100
98
  opReturnData,
@@ -4,20 +4,6 @@ import type { BTCSignTx, CosmosSignTx, ETHSignTx } from '@shapeshiftoss/hdwallet
4
4
  import { KnownChainIds } from '@shapeshiftoss/types';
5
5
  import type Web3 from 'web3';
6
6
  import type { Trade, UtxoSupportedChainIds } from '../../api';
7
- export declare type MidgardPoolResponse = {
8
- asset: string;
9
- assetDepth: string;
10
- assetPrice: string;
11
- assetPriceUSD: string;
12
- liquidityUnits: string;
13
- poolAPY: string;
14
- runeDepth: string;
15
- status: string;
16
- synthSupply: string;
17
- synthUnits: string;
18
- units: string;
19
- volume24h: string;
20
- };
21
7
  export declare type ThornodePoolResponse = {
22
8
  LP_units: string;
23
9
  asset: string;
@@ -71,13 +57,13 @@ export interface BtcThorTrade<C extends ChainId> extends Trade<C> {
71
57
  chainId: UtxoSupportedChainIds;
72
58
  txData: BTCSignTx;
73
59
  }
74
- export interface EthThorTrade<C extends ChainId> extends Trade<C> {
75
- chainId: KnownChainIds.EthereumMainnet;
60
+ export interface EvmThorTrade<C extends ChainId> extends Trade<C> {
61
+ chainId: KnownChainIds.EthereumMainnet | KnownChainIds.AvalancheMainnet;
76
62
  txData: ETHSignTx;
77
63
  }
78
64
  export interface CosmosThorTrade<C extends ChainId> extends Trade<C> {
79
65
  chainId: KnownChainIds.CosmosMainnet;
80
66
  txData: CosmosSignTx;
81
67
  }
82
- export declare type ThorTrade<C extends ChainId> = BtcThorTrade<C> | EthThorTrade<C> | CosmosThorTrade<C>;
68
+ export declare type ThorTrade<C extends ChainId> = BtcThorTrade<C> | EvmThorTrade<C> | CosmosThorTrade<C>;
83
69
  export {};
@@ -1,7 +1,7 @@
1
1
  import { Asset } from '@shapeshiftoss/asset-service';
2
- import { ethereum } from '@shapeshiftoss/chain-adapters';
3
2
  import { ETHSignTx, HDWallet } from '@shapeshiftoss/hdwallet-core';
4
3
  import { BIP44Params } from '@shapeshiftoss/types';
4
+ import { EvmSupportedChainAdapter } from '../../../../api';
5
5
  import type { ThorchainSwapperDeps } from '../../types';
6
6
  declare type MakeTradeTxArgs = {
7
7
  wallet: HDWallet;
@@ -10,7 +10,7 @@ declare type MakeTradeTxArgs = {
10
10
  buyAsset: Asset;
11
11
  sellAsset: Asset;
12
12
  destinationAddress: string;
13
- adapter: ethereum.ChainAdapter;
13
+ adapter: EvmSupportedChainAdapter;
14
14
  slippageTolerance: string;
15
15
  deps: ThorchainSwapperDeps;
16
16
  gasLimit: string;
@@ -26,11 +26,8 @@ const getLimit = async ({ sellAsset, buyAssetId, sellAmountCryptoPrecision, deps
26
26
  details: { sellAssetChainFeeAssetId, buyAssetChainFeeAssetId },
27
27
  });
28
28
  }
29
- const sellFeeAssetUsdRate = await (0, getUsdRate_1.getUsdRate)({
30
- deps,
31
- input: { assetId: sellAssetChainFeeAssetId },
32
- });
33
- const buyAssetUsdRate = await (0, getUsdRate_1.getUsdRate)({ deps, input: { assetId: buyAssetId } });
29
+ const sellFeeAssetUsdRate = await (0, getUsdRate_1.getUsdRate)(deps.daemonUrl, sellAssetChainFeeAssetId);
30
+ const buyAssetUsdRate = await (0, getUsdRate_1.getUsdRate)(deps.daemonUrl, buyAssetId);
34
31
  const expectedBuyAmountCryptoPrecision8 = (0, bignumber_1.toBaseUnit)((0, bignumber_1.fromBaseUnit)((0, bignumber_1.bnOrZero)(sellAmountCryptoPrecision).times(tradeRate), sellAsset.precision), constants_2.THORCHAIN_FIXED_PRECISION);
35
32
  const isValidSlippageRange = (0, bignumber_1.bnOrZero)(slippageTolerance).gte(0) && (0, bignumber_1.bnOrZero)(slippageTolerance).lte(1);
36
33
  if ((0, bignumber_1.bnOrZero)(expectedBuyAmountCryptoPrecision8).lt(0) || !isValidSlippageRange)
@@ -1,6 +1,2 @@
1
- import { Asset } from '@shapeshiftoss/asset-service';
2
- import { ThorchainSwapperDeps } from '../../types';
3
- export declare const getUsdRate: ({ deps, input, }: {
4
- deps: ThorchainSwapperDeps;
5
- input: Pick<Asset, 'assetId'>;
6
- }) => Promise<string>;
1
+ import { AssetId } from '@shapeshiftoss/caip';
2
+ export declare const getUsdRate: (daemonUrl: string, assetId: AssetId) => Promise<string>;
@@ -6,42 +6,66 @@ const api_1 = require("../../../../api");
6
6
  const bignumber_1 = require("../../../utils/bignumber");
7
7
  const isRune_1 = require("../isRune/isRune");
8
8
  const thorService_1 = require("../thorService");
9
- const THOR_PRECISION = 8;
10
- // not sure what to do for rune usd rate - inverting USDC pool rate for now
11
- const usdcPool = 'ETH.USDC-0XA0B86991C6218B36C1D19D4A2E9EB0CE3606EB48';
12
- const getUsdRate = async ({ deps, input, }) => {
13
- const { assetId } = input;
9
+ const PRECISION = 18;
10
+ const USD_POOLS = Object.freeze([
11
+ 'AVAX.USDC-0XB97EF9EF8734C71904D8002F8B6BC66DD9C48A6E',
12
+ 'BNB.BUSD-BD1',
13
+ 'ETH.USDC-0XA0B86991C6218B36C1D19D4A2E9EB0CE3606EB48',
14
+ 'ETH.USDT-0XDAC17F958D2EE523A2206206994597C13D831EC7',
15
+ ]);
16
+ // calculate rune usd price from a usd pool (ex. USDC_POOL)
17
+ const getRuneUsdPrice = async (daemonUrl) => {
18
+ const { data } = await thorService_1.thorService.get(`${daemonUrl}/lcd/thorchain/pools`);
19
+ const availableUsdPools = data.filter((pool) => pool.status === 'Available' && USD_POOLS.includes(pool.asset));
20
+ const { aggregatedRuneUsdPrice, numPools } = availableUsdPools.reduce((prev, pool) => {
21
+ const usdBalance = (0, bignumber_1.bnOrZero)(pool.balance_asset);
22
+ const runeBalance = (0, bignumber_1.bnOrZero)(pool.balance_rune);
23
+ if (usdBalance.isZero() || runeBalance.isZero())
24
+ return prev;
25
+ // usdBalance / runeBalance = runeUsdPrice
26
+ const runeUsdPrice = usdBalance.div(runeBalance);
27
+ prev.aggregatedRuneUsdPrice = prev.aggregatedRuneUsdPrice.plus(runeUsdPrice);
28
+ prev.numPools++;
29
+ return prev;
30
+ }, { aggregatedRuneUsdPrice: (0, bignumber_1.bn)(0), numPools: 0 });
31
+ if (!numPools) {
32
+ throw new api_1.SwapError('[getUsdRate]: no available usd pools', {
33
+ code: api_1.SwapErrorTypes.USD_RATE_FAILED,
34
+ });
35
+ }
36
+ // aggregatedRuneUsdPrice / numPools = averageRuneUsdPrice
37
+ return aggregatedRuneUsdPrice.div(numPools);
38
+ };
39
+ const getUsdRate = async (daemonUrl, assetId) => {
14
40
  try {
15
- const thorchainPoolId = (() => {
16
- if ((0, isRune_1.isRune)(assetId)) {
17
- return usdcPool;
18
- }
19
- return caip_1.adapters.assetIdToPoolAssetId({ assetId });
20
- })();
21
- if (!thorchainPoolId) {
22
- throw new api_1.SwapError(`[getUsdRate]: No thorchainPoolId found for assetId: ${assetId}`, {
41
+ if ((0, isRune_1.isRune)(assetId)) {
42
+ const runeUsdPrice = await getRuneUsdPrice(daemonUrl);
43
+ return runeUsdPrice.toFixed(PRECISION);
44
+ }
45
+ const poolId = caip_1.adapters.assetIdToPoolAssetId({ assetId });
46
+ if (!poolId) {
47
+ throw new api_1.SwapError(`[getUsdRate]: no pool found for assetId: ${assetId}`, {
23
48
  code: api_1.SwapErrorTypes.USD_RATE_FAILED,
24
49
  });
25
50
  }
26
- const { data: responseData } = await thorService_1.thorService.get(`${deps.midgardUrl}/pool/${thorchainPoolId}`);
27
- const rate = (() => {
28
- if ((0, isRune_1.isRune)(assetId)) {
29
- const bnRate = (0, bignumber_1.bnOrZero)(responseData === null || responseData === void 0 ? void 0 : responseData.assetPrice);
30
- if (bnRate.isZero()) {
31
- throw new api_1.SwapError('[getUsdRate]: cannot invert rate zero', {
32
- code: api_1.SwapErrorTypes.USD_RATE_FAILED,
33
- });
34
- }
35
- const inverseRate = (0, bignumber_1.bn)(1).div(bnRate);
36
- return inverseRate.toFixed(THOR_PRECISION);
37
- }
38
- return responseData === null || responseData === void 0 ? void 0 : responseData.assetPriceUSD;
39
- })();
40
- if (!rate)
41
- throw new api_1.SwapError(`[getUsdRate]: No rate for ${assetId}`, {
51
+ const { data } = await thorService_1.thorService.get(`${daemonUrl}/lcd/thorchain/pool/${poolId}`);
52
+ if (data.status !== 'Available') {
53
+ throw new api_1.SwapError('[getUsdRate]: pool is no longer available', {
42
54
  code: api_1.SwapErrorTypes.USD_RATE_FAILED,
43
55
  });
44
- return rate;
56
+ }
57
+ const assetBalance = (0, bignumber_1.bnOrZero)(data.balance_asset);
58
+ const runeBalance = (0, bignumber_1.bnOrZero)(data.balance_rune);
59
+ if (assetBalance.isZero() || runeBalance.isZero()) {
60
+ throw new api_1.SwapError('[getUsdRate]: pool has a zero balance', {
61
+ code: api_1.SwapErrorTypes.USD_RATE_FAILED,
62
+ });
63
+ }
64
+ const runeUsdPrice = await getRuneUsdPrice(daemonUrl);
65
+ // runeBalance / assetBalance = assetPriceInRune
66
+ const assetPriceInRune = runeBalance.div(assetBalance);
67
+ // runeUsdPrice * assetPriceInRune = assetUsdPrice
68
+ return runeUsdPrice.times(assetPriceInRune).toFixed(PRECISION);
45
69
  }
46
70
  catch (e) {
47
71
  if (e instanceof api_1.SwapError)
@@ -1,8 +1,6 @@
1
- import { InboundAddressResponse, MidgardPoolResponse, ThornodePoolResponse } from '../../types';
2
- export declare const btcMidgardPool: MidgardPoolResponse;
1
+ import { InboundAddressResponse, ThornodePoolResponse } from '../../types';
3
2
  export declare const btcThornodePool: ThornodePoolResponse;
4
- export declare const ethMidgardPool: MidgardPoolResponse;
5
3
  export declare const ethThornodePool: ThornodePoolResponse;
6
- export declare const foxMidgardPool: MidgardPoolResponse;
7
4
  export declare const foxThornodePool: ThornodePoolResponse;
5
+ export declare const usdcThornodePool: ThornodePoolResponse;
8
6
  export declare const mockInboundAddresses: InboundAddressResponse[];
@@ -1,20 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.mockInboundAddresses = exports.foxThornodePool = exports.foxMidgardPool = exports.ethThornodePool = exports.ethMidgardPool = exports.btcThornodePool = exports.btcMidgardPool = void 0;
4
- exports.btcMidgardPool = {
5
- asset: 'BTC.BTC',
6
- assetDepth: '91027798705',
7
- assetPrice: '10280.68095465986',
8
- assetPriceUSD: '29850.505131750208',
9
- liquidityUnits: '536055974608843',
10
- poolAPY: '0.09305294391574037',
11
- runeDepth: '935827756491105',
12
- status: 'available',
13
- synthSupply: '3281284823',
14
- synthUnits: '9838954536080',
15
- units: '545894929144923',
16
- volume24h: '15031085906495',
17
- };
3
+ exports.mockInboundAddresses = exports.usdcThornodePool = exports.foxThornodePool = exports.ethThornodePool = exports.btcThornodePool = void 0;
18
4
  exports.btcThornodePool = {
19
5
  LP_units: '536055974608843',
20
6
  asset: 'BTC.BTC',
@@ -27,20 +13,6 @@ exports.btcThornodePool = {
27
13
  synth_supply: '3281284823',
28
14
  synth_units: '9838954536080',
29
15
  };
30
- exports.ethMidgardPool = {
31
- asset: 'ETH.ETH',
32
- assetDepth: '915018987646',
33
- assetPrice: '676.2118757936507',
34
- assetPriceUSD: '1595',
35
- liquidityUnits: '273709963437801',
36
- poolAPY: '0.10532151323548256',
37
- runeDepth: '618746706022909',
38
- status: 'available',
39
- synthSupply: '3572065751',
40
- synthUnits: '535301524652',
41
- units: '274245264962453',
42
- volume24h: '9890096673763',
43
- };
44
16
  exports.ethThornodePool = {
45
17
  LP_units: '273709963437801',
46
18
  asset: 'ETH.ETH',
@@ -53,20 +25,6 @@ exports.ethThornodePool = {
53
25
  synth_supply: '3572065751',
54
26
  synth_units: '535301524652',
55
27
  };
56
- exports.foxMidgardPool = {
57
- asset: 'ETH.FOX-0XC770EEFAD204B5180DF6A14EE197D99D808EE52D',
58
- assetDepth: '166650912393467',
59
- assetPrice: '0.05303710198887871',
60
- assetPriceUSD: '0.15399605260336216',
61
- liquidityUnits: '10015457121887',
62
- poolAPY: '0.2597568967423438',
63
- runeDepth: '8838681437152',
64
- status: 'available',
65
- synthSupply: '17428372569375',
66
- synthUnits: '552604585625',
67
- units: '10568061707512',
68
- volume24h: '251596933033',
69
- };
70
28
  exports.foxThornodePool = {
71
29
  LP_units: '10015457121887',
72
30
  asset: 'ETH.FOX-0XC770EEFAD204B5180DF6A14EE197D99D808EE52D',
@@ -79,6 +37,18 @@ exports.foxThornodePool = {
79
37
  synth_supply: '17428372569375',
80
38
  synth_units: '552604585625',
81
39
  };
40
+ exports.usdcThornodePool = {
41
+ LP_units: '30018075345020',
42
+ asset: 'ETH.USDC-0XA0B86991C6218B36C1D19D4A2E9EB0CE3606EB48',
43
+ balance_asset: '290355330190652994811',
44
+ balance_rune: '100000000000000000000',
45
+ pending_inbound_asset: '22020062300',
46
+ pending_inbound_rune: '0',
47
+ pool_units: '31954495292990',
48
+ status: 'Available',
49
+ synth_supply: '25598723155460',
50
+ synth_units: '1936419947970',
51
+ };
82
52
  exports.mockInboundAddresses = [
83
53
  {
84
54
  chain: 'BCH',
@@ -0,0 +1,9 @@
1
+ import { AssetReference } from '@shapeshiftoss/caip';
2
+ import { EvmSupportedChainAdapter, EvmSupportedChainIds, QuoteFeeData } from '../../../../../api';
3
+ declare type GetEvmTxFeesArgs = {
4
+ adapter: EvmSupportedChainAdapter;
5
+ sellAssetReference: AssetReference | string;
6
+ buyAssetTradeFeeUsd: string;
7
+ };
8
+ export declare const getEvmTxFees: ({ adapter, sellAssetReference, buyAssetTradeFeeUsd, }: GetEvmTxFeesArgs) => Promise<QuoteFeeData<EvmSupportedChainIds>>;
9
+ export {};
@@ -1,21 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getEthTxFees = void 0;
3
+ exports.getEvmTxFees = void 0;
4
4
  const chain_adapters_1 = require("@shapeshiftoss/chain-adapters");
5
- const types_1 = require("@shapeshiftoss/types");
6
5
  const api_1 = require("../../../../../api");
7
6
  const bignumber_1 = require("../../../../utils/bignumber");
8
7
  const constants_1 = require("../../../../utils/constants");
9
8
  const constants_2 = require("../../constants");
10
- const getEthTxFees = async ({ adapterManager, sellAssetReference, buyAssetTradeFeeUsd, }) => {
9
+ const getEvmTxFees = async ({ adapter, sellAssetReference, buyAssetTradeFeeUsd, }) => {
11
10
  try {
12
- const adapter = adapterManager.get(types_1.KnownChainIds.EthereumMainnet);
13
- if (!adapter) {
14
- throw new api_1.SwapError(`[getThorTxInfo] - No chain adapter found for ${types_1.KnownChainIds.EthereumMainnet}.`, {
15
- code: api_1.SwapErrorTypes.UNSUPPORTED_CHAIN,
16
- details: { chainId: types_1.KnownChainIds.EthereumMainnet },
17
- });
18
- }
19
11
  const gasFeeData = await adapter.getGasFeeData();
20
12
  // this is a good value to cover all thortrades out of eth/erc20
21
13
  // in the future we may want to look at doing this more precisely and in a future-proof way
@@ -50,4 +42,4 @@ const getEthTxFees = async ({ adapterManager, sellAssetReference, buyAssetTradeF
50
42
  throw new api_1.SwapError('[getThorTxInfo]', { cause: e, code: api_1.SwapErrorTypes.TRADE_QUOTE_FAILED });
51
43
  }
52
44
  };
53
- exports.getEthTxFees = getEthTxFees;
45
+ exports.getEvmTxFees = getEvmTxFees;
@@ -1,6 +1,6 @@
1
1
  import { UtxoBaseAdapter } from '@shapeshiftoss/chain-adapters';
2
2
  import { QuoteFeeData, UtxoSupportedChainIds } from '../../../../../api';
3
- declare type GetBtcTxFeesInput = {
3
+ declare type GetUtxoTxFeesInput = {
4
4
  opReturnData: string;
5
5
  vault: string;
6
6
  sellAmountCryptoPrecision: string;
@@ -9,5 +9,5 @@ declare type GetBtcTxFeesInput = {
9
9
  buyAssetTradeFeeUsd: string;
10
10
  sendMax: boolean;
11
11
  };
12
- export declare const getBtcTxFees: ({ opReturnData, vault, sellAmountCryptoPrecision, sellAdapter, pubkey, buyAssetTradeFeeUsd, sendMax, }: GetBtcTxFeesInput) => Promise<QuoteFeeData<UtxoSupportedChainIds>>;
12
+ export declare const getUtxoTxFees: ({ opReturnData, vault, sellAmountCryptoPrecision, sellAdapter, pubkey, buyAssetTradeFeeUsd, sendMax, }: GetUtxoTxFeesInput) => Promise<QuoteFeeData<UtxoSupportedChainIds>>;
13
13
  export {};
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getBtcTxFees = void 0;
3
+ exports.getUtxoTxFees = void 0;
4
4
  const types_1 = require("@shapeshiftoss/types");
5
5
  const api_1 = require("../../../../../api");
6
6
  const bignumber_1 = require("../../../../utils/bignumber");
7
- const getBtcTxFees = async ({ opReturnData, vault, sellAmountCryptoPrecision, sellAdapter, pubkey, buyAssetTradeFeeUsd, sendMax, }) => {
7
+ const getUtxoTxFees = async ({ opReturnData, vault, sellAmountCryptoPrecision, sellAdapter, pubkey, buyAssetTradeFeeUsd, sendMax, }) => {
8
8
  try {
9
9
  const feeDataOptions = await sellAdapter.getFeeData({
10
10
  to: vault,
@@ -38,7 +38,7 @@ const getBtcTxFees = async ({ opReturnData, vault, sellAmountCryptoPrecision, se
38
38
  catch (e) {
39
39
  if (e instanceof api_1.SwapError)
40
40
  throw e;
41
- throw new api_1.SwapError('[getBtcTxFeess]', { cause: e, code: api_1.SwapErrorTypes.TRADE_QUOTE_FAILED });
41
+ throw new api_1.SwapError('[getUtxoTxFees]', { cause: e, code: api_1.SwapErrorTypes.TRADE_QUOTE_FAILED });
42
42
  }
43
43
  };
44
- exports.getBtcTxFees = getBtcTxFees;
44
+ exports.getUtxoTxFees = getUtxoTxFees;
@@ -2,10 +2,10 @@ import { Asset } from '@shapeshiftoss/asset-service';
2
2
  import { HDWallet } from '@shapeshiftoss/hdwallet-core';
3
3
  import Web3 from 'web3';
4
4
  import { AbiItem } from 'web3-utils';
5
- import { EvmSupportedChainAdapters, EvmSupportedChainIds, TradeQuote } from '../../../api';
5
+ import { EvmSupportedChainAdapter, EvmSupportedChainIds, TradeQuote } from '../../../api';
6
6
  import { BN } from '../bignumber';
7
7
  export declare type IsApprovalRequiredArgs = {
8
- adapter: EvmSupportedChainAdapters;
8
+ adapter: EvmSupportedChainAdapter;
9
9
  receiveAddress: string;
10
10
  allowanceContract: string;
11
11
  sellAsset: Asset;
@@ -28,7 +28,7 @@ export declare type GetApproveContractDataArgs = {
28
28
  declare type GrantAllowanceArgs<T extends EvmSupportedChainIds> = {
29
29
  quote: TradeQuote<T>;
30
30
  wallet: HDWallet;
31
- adapter: EvmSupportedChainAdapters;
31
+ adapter: EvmSupportedChainAdapter;
32
32
  erc20Abi: AbiItem[];
33
33
  web3: Web3;
34
34
  };
@@ -1,6 +1,6 @@
1
1
  import { HDWallet } from '@shapeshiftoss/hdwallet-core';
2
2
  import type Web3 from 'web3';
3
- import { EvmSupportedChainAdapters, EvmSupportedChainIds, SwapSource, Trade } from '../../api';
3
+ import { EvmSupportedChainAdapter, EvmSupportedChainIds, SwapSource, Trade } from '../../api';
4
4
  export declare type ZrxCommonResponse = {
5
5
  price: string;
6
6
  gasPrice: string;
@@ -26,6 +26,6 @@ export declare type ZrxExecuteTradeInput<T extends EvmSupportedChainIds> = {
26
26
  wallet: HDWallet;
27
27
  };
28
28
  export declare type ZrxSwapperDeps = {
29
- adapter: EvmSupportedChainAdapters;
29
+ adapter: EvmSupportedChainAdapter;
30
30
  web3: Web3;
31
31
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shapeshiftoss/swapper",
3
- "version": "14.2.3",
3
+ "version": "14.4.0",
4
4
  "description": "An interface and implementations to trade coins via various protocols",
5
5
  "repository": "https://github.com/shapeshift/lib",
6
6
  "license": "MIT",
@@ -1,9 +0,0 @@
1
- import { AssetReference } from '@shapeshiftoss/caip';
2
- import { ChainAdapterManager } from '@shapeshiftoss/chain-adapters';
3
- import { KnownChainIds } from '@shapeshiftoss/types';
4
- import { QuoteFeeData } from '../../../../../api';
5
- export declare const getEthTxFees: ({ adapterManager, sellAssetReference, buyAssetTradeFeeUsd, }: {
6
- adapterManager: ChainAdapterManager;
7
- sellAssetReference: AssetReference | string;
8
- buyAssetTradeFeeUsd: string;
9
- }) => Promise<QuoteFeeData<KnownChainIds.EthereumMainnet>>;