@shapeshiftoss/swapper 7.7.1 → 7.8.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.
@@ -3,10 +3,15 @@ import { ethereum } from '@shapeshiftoss/chain-adapters';
3
3
  import { Asset } from '@shapeshiftoss/types';
4
4
  import Web3 from 'web3';
5
5
  import { ApprovalNeededInput, ApprovalNeededOutput, ApproveInfiniteInput, BuildTradeInput, BuyAssetBySellIdInput, ExecuteTradeInput, GetTradeQuoteInput, Swapper, SwapperType, Trade, TradeQuote, TradeResult, TradeTxs } from '../../api';
6
+ /**
7
+ * CowSwap only supports ERC-20 swaps, hence ETH is not supported
8
+ * In order to get rates correctly, we need WETH asset to be passed as feeAsset
9
+ */
6
10
  export declare type CowSwapperDeps = {
7
11
  apiUrl: string;
8
12
  adapter: ethereum.ChainAdapter;
9
13
  web3: Web3;
14
+ feeAsset: Asset;
10
15
  };
11
16
  export declare class CowSwapper implements Swapper<'eip155:1'> {
12
17
  static swapperName: string;
@@ -4,6 +4,7 @@ exports.CowSwapper = void 0;
4
4
  const api_1 = require("../../api");
5
5
  const CowApprovalNeeded_1 = require("./CowApprovalNeeded/CowApprovalNeeded");
6
6
  const CowApproveInfinite_1 = require("./CowApproveInfinite/CowApproveInfinite");
7
+ const getCowSwapTradeQuote_1 = require("./getCowSwapTradeQuote/getCowSwapTradeQuote");
7
8
  const blacklist_1 = require("./utils/blacklist");
8
9
  const helpers_1 = require("./utils/helpers/helpers");
9
10
  class CowSwapper {
@@ -20,8 +21,7 @@ class CowSwapper {
20
21
  throw new Error('CowSwapper: buildTrade unimplemented');
21
22
  }
22
23
  async getTradeQuote(input) {
23
- console.info(input);
24
- throw new Error('CowSwapper: getTradeQuote unimplemented');
24
+ return (0, getCowSwapTradeQuote_1.getCowSwapTradeQuote)(this.deps, input);
25
25
  }
26
26
  async getUsdRate(input) {
27
27
  return (0, helpers_1.getUsdRate)(this.deps, input);
@@ -12,7 +12,7 @@ const getCowSwapMinMax = async (deps, sellAsset, buyAsset) => {
12
12
  throw new api_1.SwapError('[getCowSwapMinMax]', { code: api_1.SwapErrorTypes.UNSUPPORTED_PAIR });
13
13
  }
14
14
  const usdRate = await (0, helpers_1.getUsdRate)(deps, sellAsset);
15
- const minimum = (0, bignumber_1.bn)(1).dividedBy((0, bignumber_1.bnOrZero)(usdRate)).toString(); // $1 worth of the sell token.
15
+ const minimum = (0, bignumber_1.bn)(constants_1.MIN_COWSWAP_VALUE_USD).dividedBy((0, bignumber_1.bnOrZero)(usdRate)).toString(); // $10 worth of the sell token.
16
16
  const maximum = constants_1.MAX_COWSWAP_TRADE; // Arbitrarily large value. 10e+28 here.
17
17
  return {
18
18
  minimum,
@@ -0,0 +1,14 @@
1
+ import { GetTradeQuoteInput, TradeQuote } from '../../../api';
2
+ import { CowSwapperDeps } from '../CowSwapper';
3
+ export declare type CowSwapQuoteApiInput = {
4
+ appData: string;
5
+ buyToken: string;
6
+ from: string;
7
+ kind: string;
8
+ partiallyFillable: boolean;
9
+ receiver: string;
10
+ sellAmountBeforeFee: string;
11
+ sellToken: string;
12
+ validTo: number;
13
+ };
14
+ export declare function getCowSwapTradeQuote(deps: CowSwapperDeps, input: GetTradeQuoteInput): Promise<TradeQuote<'eip155:1'>>;
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getCowSwapTradeQuote = void 0;
4
+ const caip_1 = require("@shapeshiftoss/caip");
5
+ const api_1 = require("../../../api");
6
+ const bignumber_1 = require("../../utils/bignumber");
7
+ const constants_1 = require("../../utils/constants");
8
+ const helpers_1 = require("../../utils/helpers/helpers");
9
+ const getCowSwapMinMax_1 = require("../getCowSwapMinMax/getCowSwapMinMax");
10
+ const constants_2 = require("../utils/constants");
11
+ const cowService_1 = require("../utils/cowService");
12
+ const helpers_2 = require("../utils/helpers/helpers");
13
+ async function getCowSwapTradeQuote(deps, input) {
14
+ try {
15
+ const { sellAsset, buyAsset, sellAmount, sellAssetAccountNumber, wallet } = input;
16
+ const { adapter, feeAsset } = deps;
17
+ const { assetReference: sellAssetErc20Address, assetNamespace: sellAssetNamespace } = (0, caip_1.fromAssetId)(sellAsset.assetId);
18
+ const { assetReference: buyAssetErc20Address, assetNamespace: buyAssetNamespace } = (0, caip_1.fromAssetId)(buyAsset.assetId);
19
+ if (buyAssetNamespace !== 'erc20' || sellAssetNamespace !== 'erc20') {
20
+ throw new api_1.SwapError('[getCowSwapTradeQuote] - Both assets need to be ERC-20 to use CowSwap', {
21
+ code: api_1.SwapErrorTypes.UNSUPPORTED_PAIR,
22
+ details: { buyAssetNamespace, sellAssetNamespace }
23
+ });
24
+ }
25
+ const { minimum, maximum } = await (0, getCowSwapMinMax_1.getCowSwapMinMax)(deps, sellAsset, buyAsset);
26
+ const minQuoteSellAmount = (0, bignumber_1.bnOrZero)(minimum).times((0, bignumber_1.bn)(10).exponentiatedBy(sellAsset.precision));
27
+ // making sure we do not have decimals for cowswap api (can happen at least from minQuoteSellAmount)
28
+ const normalizedSellAmount = (0, helpers_1.normalizeIntegerAmount)((0, bignumber_1.bnOrZero)(sellAmount).lt(minQuoteSellAmount) ? minQuoteSellAmount : sellAmount);
29
+ const apiInput = {
30
+ sellToken: sellAssetErc20Address,
31
+ buyToken: buyAssetErc20Address,
32
+ receiver: constants_2.DEFAULT_ADDRESS,
33
+ validTo: constants_2.DEFAULT_VALIDTO_TIMESTAMP,
34
+ appData: constants_2.DEFAULT_APP_DATA,
35
+ partiallyFillable: false,
36
+ from: constants_2.DEFAULT_ADDRESS,
37
+ kind: constants_2.ORDER_KIND_SELL,
38
+ sellAmountBeforeFee: normalizedSellAmount
39
+ };
40
+ /**
41
+ * /v1/quote
42
+ * params: {
43
+ * sellToken: contract address of token to sell
44
+ * buyToken: contractAddress of token to buy
45
+ * receiver: receiver address can be defaulted to "0x0000000000000000000000000000000000000000"
46
+ * validTo: time duration during which quote is valid (eg : 1654851610 as timestamp)
47
+ * appData: appData for the CowSwap quote that can be used later, can be defaulted to "0x0000000000000000000000000000000000000000000000000000000000000000"
48
+ * partiallyFillable: false
49
+ * from: sender address can be defaulted to "0x0000000000000000000000000000000000000000"
50
+ * kind: "sell" or "buy"
51
+ * sellAmountBeforeFee / buyAmountAfterFee: amount in base unit
52
+ * }
53
+ */
54
+ const quoteResponse = await cowService_1.cowService.post(`${deps.apiUrl}/v1/quote/`, apiInput);
55
+ const { data: { quote } } = quoteResponse;
56
+ const rate = (0, bignumber_1.bn)(quote.buyAmount)
57
+ .div(quote.sellAmount)
58
+ .times((0, bignumber_1.bn)(10).exponentiatedBy(sellAsset.precision - buyAsset.precision))
59
+ .toString();
60
+ const receiveAddress = wallet ? await adapter.getAddress({ wallet }) : constants_2.DEFAULT_ADDRESS;
61
+ const [feeDataOptions, wethUsdRate, usdRateSellAsset] = await Promise.all([
62
+ adapter.getFeeData({
63
+ to: constants_2.COW_SWAP_VAULT_RELAYER_ADDRESS,
64
+ value: '0',
65
+ chainSpecific: { from: receiveAddress, contractAddress: sellAssetErc20Address }
66
+ }),
67
+ (0, helpers_2.getUsdRate)(deps, feeAsset),
68
+ (0, helpers_2.getUsdRate)(deps, sellAsset)
69
+ ]);
70
+ const feeData = feeDataOptions['fast'];
71
+ const fee = (0, bignumber_1.bnOrZero)(quote.feeAmount)
72
+ .multipliedBy((0, bignumber_1.bnOrZero)(usdRateSellAsset))
73
+ .div((0, bignumber_1.bnOrZero)(wethUsdRate))
74
+ .div((0, bignumber_1.bn)(10).exponentiatedBy(sellAsset.precision - feeAsset.precision))
75
+ .toString();
76
+ return {
77
+ rate,
78
+ minimum,
79
+ maximum,
80
+ feeData: {
81
+ fee,
82
+ chainSpecific: {
83
+ estimatedGas: feeData.chainSpecific.gasLimit,
84
+ gasPrice: feeData.chainSpecific.gasPrice,
85
+ approvalFee: (0, bignumber_1.bnOrZero)(constants_1.APPROVAL_GAS_LIMIT)
86
+ .multipliedBy((0, bignumber_1.bnOrZero)(feeData.chainSpecific.gasPrice))
87
+ .toString()
88
+ },
89
+ tradeFee: '0'
90
+ },
91
+ sellAmount: quote.sellAmount,
92
+ buyAmount: quote.buyAmount,
93
+ sources: constants_2.DEFAULT_SOURCE,
94
+ allowanceContract: '',
95
+ buyAsset,
96
+ sellAsset,
97
+ sellAssetAccountNumber
98
+ };
99
+ }
100
+ catch (e) {
101
+ if (e instanceof api_1.SwapError)
102
+ throw e;
103
+ throw new api_1.SwapError('[getCowSwapTradeQuote]', {
104
+ cause: e,
105
+ code: api_1.SwapErrorTypes.TRADE_QUOTE_FAILED
106
+ });
107
+ }
108
+ }
109
+ exports.getCowSwapTradeQuote = getCowSwapTradeQuote;
@@ -2,3 +2,19 @@ export declare type CowSwapPriceResponse = {
2
2
  amount: string;
3
3
  token: string;
4
4
  };
5
+ export declare type CowSwapQuoteResponse = {
6
+ quote: {
7
+ sellToken: string;
8
+ buyToken: string;
9
+ receiver: string;
10
+ sellAmount: string;
11
+ buyAmount: string;
12
+ validTo: number;
13
+ appData: string;
14
+ feeAmount: string;
15
+ kind: string;
16
+ partiallyFillable: boolean;
17
+ };
18
+ from: string;
19
+ expiration: string;
20
+ };
@@ -1,2 +1,12 @@
1
1
  export declare const MAX_ALLOWANCE = "100000000000000000000000000";
2
2
  export declare const MAX_COWSWAP_TRADE = "100000000000000000000000000";
3
+ export declare const MIN_COWSWAP_VALUE_USD = 10;
4
+ export declare const DEFAULT_SOURCE: {
5
+ name: string;
6
+ proportion: string;
7
+ }[];
8
+ export declare const DEFAULT_ADDRESS = "0x0000000000000000000000000000000000000000";
9
+ export declare const DEFAULT_APP_DATA = "0x0000000000000000000000000000000000000000000000000000000000000000";
10
+ export declare const COW_SWAP_VAULT_RELAYER_ADDRESS = "0xc92e8bdf79f0507f65a392b0ab4667716bfe0110";
11
+ export declare const DEFAULT_VALIDTO_TIMESTAMP = 4294967295;
12
+ export declare const ORDER_KIND_SELL = "sell";
@@ -1,4 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MAX_COWSWAP_TRADE = void 0;
3
+ exports.ORDER_KIND_SELL = exports.DEFAULT_VALIDTO_TIMESTAMP = exports.COW_SWAP_VAULT_RELAYER_ADDRESS = exports.DEFAULT_APP_DATA = exports.DEFAULT_ADDRESS = exports.DEFAULT_SOURCE = exports.MIN_COWSWAP_VALUE_USD = exports.MAX_COWSWAP_TRADE = void 0;
4
4
  exports.MAX_COWSWAP_TRADE = '100000000000000000000000000';
5
+ exports.MIN_COWSWAP_VALUE_USD = 10;
6
+ exports.DEFAULT_SOURCE = [{ name: 'CowSwap', proportion: '1' }];
7
+ exports.DEFAULT_ADDRESS = '0x0000000000000000000000000000000000000000';
8
+ exports.DEFAULT_APP_DATA = '0x0000000000000000000000000000000000000000000000000000000000000000';
9
+ exports.COW_SWAP_VAULT_RELAYER_ADDRESS = '0xc92e8bdf79f0507f65a392b0ab4667716bfe0110';
10
+ // CowSwap API requires validTo field which specifies a limit date for the order to be valid
11
+ // This is the default value being used by CowSwap exchange, corresponding to a date in year 2106
12
+ exports.DEFAULT_VALIDTO_TIMESTAMP = 4294967295;
13
+ exports.ORDER_KIND_SELL = 'sell';
@@ -1,3 +1,3 @@
1
1
  import { Asset } from '@shapeshiftoss/types';
2
2
  import { CowSwapperDeps } from '../../CowSwapper';
3
- export declare const getUsdRate: ({ apiUrl }: CowSwapperDeps, input: Asset) => Promise<string>;
3
+ export declare const getUsdRate: ({ apiUrl, feeAsset }: CowSwapperDeps, input: Asset) => Promise<string>;
@@ -7,8 +7,9 @@ const bignumber_1 = require("../../../utils/bignumber");
7
7
  const cowService_1 = require("../cowService");
8
8
  const USDC_CONTRACT_ADDRESS = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48';
9
9
  const USDC_ASSET_PRECISION = 6;
10
- const getUsdRate = async ({ apiUrl }, input) => {
11
- const asset = input;
10
+ const getUsdRate = async ({ apiUrl, feeAsset }, input) => {
11
+ // Replacing ETH by WETH specifically for CowSwap in order to get an usd rate when called with ETH as feeAsset
12
+ const asset = input.assetId !== caip_1.ethAssetId ? input : feeAsset;
12
13
  const { assetReference: erc20Address, assetNamespace } = (0, caip_1.fromAssetId)(asset.assetId);
13
14
  if (assetNamespace !== 'erc20') {
14
15
  throw new api_1.SwapError('[getUsdRate] - unsupported asset namespace', {
@@ -37,4 +37,5 @@ export declare const grantAllowance: ({ quote, wallet, adapter, erc20Abi, web3 }
37
37
  * @param amount
38
38
  */
39
39
  export declare const normalizeAmount: (amount: string | number | BN) => string;
40
+ export declare const normalizeIntegerAmount: (amount: string | number | BN) => string;
40
41
  export {};
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.normalizeAmount = exports.grantAllowance = exports.getAllowanceRequired = exports.getERC20Allowance = void 0;
3
+ exports.normalizeIntegerAmount = exports.normalizeAmount = exports.grantAllowance = exports.getAllowanceRequired = exports.getERC20Allowance = void 0;
4
4
  const caip_1 = require("@shapeshiftoss/caip");
5
5
  const web3_utils_1 = require("web3-utils");
6
6
  const api_1 = require("../../../api");
@@ -108,3 +108,10 @@ const normalizeAmount = (amount) => {
108
108
  return (0, bignumber_1.bnOrZero)(amount).toNumber().toLocaleString('fullwide', { useGrouping: false });
109
109
  };
110
110
  exports.normalizeAmount = normalizeAmount;
111
+ const normalizeIntegerAmount = (amount) => {
112
+ return (0, bignumber_1.bnOrZero)(amount)
113
+ .integerValue()
114
+ .toNumber()
115
+ .toLocaleString('fullwide', { useGrouping: false });
116
+ };
117
+ exports.normalizeIntegerAmount = normalizeIntegerAmount;
@@ -3,4 +3,5 @@ import Web3 from 'web3';
3
3
  export declare const setupDeps: () => {
4
4
  web3: Web3;
5
5
  adapter: ethereum.ChainAdapter;
6
+ feeAsset: import("@shapeshiftoss/types").Asset;
6
7
  };
@@ -30,6 +30,7 @@ exports.setupDeps = void 0;
30
30
  const chain_adapters_1 = require("@shapeshiftoss/chain-adapters");
31
31
  const unchained = __importStar(require("@shapeshiftoss/unchained-client"));
32
32
  const web3_1 = __importDefault(require("web3"));
33
+ const assets_1 = require("./assets");
33
34
  jest.mock('@shapeshiftoss/chain-adapters');
34
35
  jest.mock('web3');
35
36
  const setupDeps = () => {
@@ -44,6 +45,6 @@ const setupDeps = () => {
44
45
  });
45
46
  const ethNodeUrl = 'http://localhost:1000';
46
47
  const web3Provider = new web3_1.default.providers.HttpProvider(ethNodeUrl);
47
- return { web3: new web3_1.default(web3Provider), adapter: ethChainAdapter };
48
+ return { web3: new web3_1.default(web3Provider), adapter: ethChainAdapter, feeAsset: assets_1.WETH };
48
49
  };
49
50
  exports.setupDeps = setupDeps;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shapeshiftoss/swapper",
3
- "version": "7.7.1",
3
+ "version": "7.8.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",