@shapeshiftoss/swapper 3.0.6 → 4.0.1

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.
package/dist/api.d.ts CHANGED
@@ -1,19 +1,19 @@
1
- import { CAIP19 } from '@shapeshiftoss/caip';
1
+ import { AssetId } from '@shapeshiftoss/caip';
2
2
  import { HDWallet } from '@shapeshiftoss/hdwallet-core';
3
- import { ApprovalNeededOutput, Asset, BuildQuoteTxInput, chainAdapters, ChainTypes, ExecQuoteInput, ExecQuoteOutput, GetQuoteInput, MinMaxOutput, Quote, SwapperType } from '@shapeshiftoss/types';
3
+ import { ApprovalNeededOutput, Asset, chainAdapters, ChainTypes, ExecQuoteOutput, GetQuoteInput, MinMaxOutput, Quote, SwapperType } from '@shapeshiftoss/types';
4
4
  export declare type SupportedAssetInput = {
5
- assetIds: CAIP19[];
5
+ assetIds: AssetId[];
6
6
  };
7
7
  export declare type ByPairInput = {
8
- sellAssetId: CAIP19;
9
- buyAssetId: CAIP19;
8
+ sellAssetId: AssetId;
9
+ buyAssetId: AssetId;
10
10
  };
11
11
  export declare type BuyAssetBySellIdInput = {
12
- sellAssetId: CAIP19;
13
- assetIds: CAIP19[];
12
+ sellAssetId: AssetId;
13
+ assetIds: AssetId[];
14
14
  };
15
15
  export declare type SupportedSellAssetsInput = {
16
- assetIds: CAIP19[];
16
+ assetIds: AssetId[];
17
17
  };
18
18
  export declare type CommonTradeInput = {
19
19
  sellAsset: Asset;
@@ -83,16 +83,6 @@ export interface Swapper {
83
83
  * Get a trade quote
84
84
  */
85
85
  getTradeQuote(input: GetTradeQuoteInput): Promise<TradeQuote<ChainTypes>>;
86
- /**
87
- * Get a Quote along with an unsigned transaction that can be signed and broadcast to execute the swap
88
- * @deprecated The method is going away soon.
89
- **/
90
- buildQuoteTx(args: BuildQuoteTxInput): Promise<Quote<ChainTypes>>;
91
- /**
92
- * Get a basic quote (rate) for a trading pair
93
- * @deprecated The method is going away soon.
94
- */
95
- getQuote(input: GetQuoteInput, wallet?: HDWallet): Promise<Quote<ChainTypes>>;
96
86
  /**
97
87
  * Get the usd rate from either the assets symbol or tokenId
98
88
  */
@@ -101,10 +91,6 @@ export interface Swapper {
101
91
  * Get the minimum and maximum trade value of the sellAsset and buyAsset
102
92
  */
103
93
  getMinMax(input: GetQuoteInput): Promise<MinMaxOutput>;
104
- /**
105
- * Execute a quote built with buildQuoteTx by signing and broadcasting
106
- */
107
- executeQuote(args: ExecQuoteInput<ChainTypes>): Promise<ExecQuoteOutput>;
108
94
  /**
109
95
  * Execute a trade built with buildTrade by signing and broadcasting
110
96
  */
@@ -120,10 +106,10 @@ export interface Swapper {
120
106
  /**
121
107
  * Get supported buyAssetId's by sellAssetId
122
108
  */
123
- filterBuyAssetsBySellAssetId(args: BuyAssetBySellIdInput): CAIP19[];
109
+ filterBuyAssetsBySellAssetId(args: BuyAssetBySellIdInput): AssetId[];
124
110
  /**
125
111
  * Get supported sell assetIds
126
112
  */
127
- filterAssetIdsBySellable(assetIds: CAIP19[]): CAIP19[];
113
+ filterAssetIdsBySellable(assetIds: AssetId[]): AssetId[];
128
114
  }
129
115
  export {};
@@ -86,15 +86,12 @@ const main = async () => {
86
86
  manager.addSwapper(types_1.SwapperType.Zrx, zrxSwapper);
87
87
  const swapper = manager.getSwapper(types_1.SwapperType.Zrx);
88
88
  const sellAmountBase = toBaseUnit(sellAmount, sellAsset.precision);
89
- const quote = await swapper.buildQuoteTx({
90
- input: {
91
- sellAsset,
92
- buyAsset,
93
- sellAmount: sellAmountBase,
94
- sellAssetAccountId: '0',
95
- buyAssetAccountId: '0'
96
- },
97
- wallet
89
+ const quote = await swapper.getTradeQuote({
90
+ sellAsset,
91
+ buyAsset,
92
+ sellAmount: sellAmountBase,
93
+ sellAssetAccountId: '0',
94
+ sendMax: false
98
95
  });
99
96
  console.info('quote = ', JSON.stringify(quote));
100
97
  if (!quote.success) {
@@ -104,7 +101,16 @@ const main = async () => {
104
101
  const buyAmount = fromBaseUnit(quote.buyAmount || '0', buyAsset.precision);
105
102
  const answer = readline_sync_1.default.question(`Swap ${sellAmount} ${sellAsset.symbol} for ${buyAmount} ${buyAsset.symbol} on ${swapper.getType()}? (y/n): `);
106
103
  if (answer === 'y') {
107
- const txid = await swapper.executeQuote({ quote, wallet });
104
+ const trade = await swapper.buildTrade({
105
+ wallet,
106
+ buyAsset,
107
+ sendMax: false,
108
+ sellAmount: sellAmountBase,
109
+ sellAsset,
110
+ sellAssetAccountId: '0',
111
+ buyAssetAccountId: '0'
112
+ });
113
+ const txid = await swapper.executeTrade({ trade, wallet });
108
114
  console.info('broadcast tx with id: ', txid);
109
115
  }
110
116
  };
@@ -1,5 +1,5 @@
1
- import { CAIP19 } from '@shapeshiftoss/caip';
2
- import { ApprovalNeededOutput, Asset, ChainTypes, ExecQuoteOutput, GetQuoteInput, MinMaxOutput, Quote, SwapperType } from '@shapeshiftoss/types';
1
+ import { AssetId } from '@shapeshiftoss/caip';
2
+ import { ApprovalNeededOutput, Asset, ChainTypes, ExecQuoteOutput, GetQuoteInput, MinMaxOutput, SwapperType } from '@shapeshiftoss/types';
3
3
  import { BuyAssetBySellIdInput, Swapper, Trade, TradeQuote } from '../../api';
4
4
  /**
5
5
  * Playground for testing different scenarios of multiple swappers in the manager.
@@ -9,15 +9,12 @@ export declare class TestSwapper implements Swapper {
9
9
  supportAssets: string[];
10
10
  getType(): SwapperType;
11
11
  constructor();
12
- getQuote(): Promise<Quote<ChainTypes>>;
13
- buildQuoteTx(): Promise<Quote<ChainTypes>>;
14
12
  getUsdRate(input: Pick<Asset, 'symbol' | 'tokenId'>): Promise<string>;
15
13
  getMinMax(input: GetQuoteInput): Promise<MinMaxOutput>;
16
- executeQuote(): Promise<ExecQuoteOutput>;
17
14
  approvalNeeded(): Promise<ApprovalNeededOutput>;
18
15
  approveInfinite(): Promise<string>;
19
- filterBuyAssetsBySellAssetId(args: BuyAssetBySellIdInput): CAIP19[];
20
- filterAssetIdsBySellable(): CAIP19[];
16
+ filterBuyAssetsBySellAssetId(args: BuyAssetBySellIdInput): AssetId[];
17
+ filterAssetIdsBySellable(): AssetId[];
21
18
  buildTrade(): Promise<Trade<ChainTypes>>;
22
19
  getTradeQuote(): Promise<TradeQuote<ChainTypes>>;
23
20
  executeTrade(): Promise<ExecQuoteOutput>;
@@ -17,12 +17,6 @@ class TestSwapper {
17
17
  getType() {
18
18
  return types_1.SwapperType.Test;
19
19
  }
20
- async getQuote() {
21
- throw new Error('TestSwapper: getQuote unimplemented');
22
- }
23
- async buildQuoteTx() {
24
- throw new Error('TestSwapper: getQuote unimplemented');
25
- }
26
20
  getUsdRate(input) {
27
21
  console.info(input);
28
22
  throw new Error('TestSwapper: getUsdRate unimplemented');
@@ -31,9 +25,6 @@ class TestSwapper {
31
25
  console.info(input);
32
26
  throw new Error('TestSwapper: getMinMax unimplemented');
33
27
  }
34
- async executeQuote() {
35
- throw new Error('TestSwapper: executeQuote unimplemented');
36
- }
37
28
  async approvalNeeded() {
38
29
  throw new Error('TestSwapper: approvalNeeded unimplemented');
39
30
  }
@@ -1,17 +1,14 @@
1
- import { CAIP19 } from '@shapeshiftoss/caip';
2
- import { ApprovalNeededOutput, Asset, ChainTypes, ExecQuoteOutput, GetQuoteInput, MinMaxOutput, Quote, SwapperType } from '@shapeshiftoss/types';
1
+ import { AssetId } from '@shapeshiftoss/caip';
2
+ import { ApprovalNeededOutput, Asset, ChainTypes, ExecQuoteOutput, GetQuoteInput, MinMaxOutput, SwapperType } from '@shapeshiftoss/types';
3
3
  import { Swapper, Trade, TradeQuote } from '../../api';
4
4
  export declare class ThorchainSwapper implements Swapper {
5
5
  getType(): SwapperType;
6
- getQuote(): Promise<Quote<ChainTypes>>;
7
- buildQuoteTx(): Promise<Quote<ChainTypes>>;
8
6
  getUsdRate(input: Pick<Asset, 'symbol' | 'tokenId'>): Promise<string>;
9
7
  getMinMax(input: GetQuoteInput): Promise<MinMaxOutput>;
10
- executeQuote(): Promise<ExecQuoteOutput>;
11
8
  approvalNeeded(): Promise<ApprovalNeededOutput>;
12
9
  approveInfinite(): Promise<string>;
13
- filterBuyAssetsBySellAssetId(): CAIP19[];
14
- filterAssetIdsBySellable(): CAIP19[];
10
+ filterBuyAssetsBySellAssetId(): AssetId[];
11
+ filterAssetIdsBySellable(): AssetId[];
15
12
  buildTrade(): Promise<Trade<ChainTypes>>;
16
13
  getTradeQuote(): Promise<TradeQuote<ChainTypes>>;
17
14
  executeTrade(): Promise<ExecQuoteOutput>;
@@ -6,12 +6,6 @@ class ThorchainSwapper {
6
6
  getType() {
7
7
  return types_1.SwapperType.Thorchain;
8
8
  }
9
- async getQuote() {
10
- throw new Error('ThorchainSwapper: getQuote unimplemented');
11
- }
12
- async buildQuoteTx() {
13
- throw new Error('ThorchainSwapper: getQuote unimplemented');
14
- }
15
9
  getUsdRate(input) {
16
10
  console.info(input);
17
11
  throw new Error('ThorchainSwapper: getUsdRate unimplemented');
@@ -20,9 +14,6 @@ class ThorchainSwapper {
20
14
  console.info(input);
21
15
  throw new Error('ThorchainSwapper: getMinMax unimplemented');
22
16
  }
23
- async executeQuote() {
24
- throw new Error('ThorchainSwapper: executeQuote unimplemented');
25
- }
26
17
  async approvalNeeded() {
27
18
  throw new Error('ThorchainSwapper: approvalNeeded unimplemented');
28
19
  }
@@ -1,6 +1,6 @@
1
- import { CAIP19 } from '@shapeshiftoss/caip';
1
+ import { AssetId } from '@shapeshiftoss/caip';
2
2
  import { ChainAdapterManager } from '@shapeshiftoss/chain-adapters';
3
- import { ApprovalNeededOutput, Asset, BuildQuoteTxInput, ChainTypes, ExecQuoteInput, ExecQuoteOutput, GetQuoteInput, MinMaxOutput, Quote, SwapperType } from '@shapeshiftoss/types';
3
+ import { ApprovalNeededOutput, Asset, ChainTypes, ExecQuoteOutput, GetQuoteInput, MinMaxOutput, SwapperType } from '@shapeshiftoss/types';
4
4
  import Web3 from 'web3';
5
5
  import { ApprovalNeededInput, ApproveInfiniteInput, BuildTradeInput, BuyAssetBySellIdInput, ExecuteTradeInput, GetTradeQuoteInput, Swapper, Trade, TradeQuote } from '../../api';
6
6
  export declare type ZrxSwapperDeps = {
@@ -15,16 +15,13 @@ export declare class ZrxSwapper implements Swapper {
15
15
  deps: ZrxSwapperDeps;
16
16
  constructor(deps: ZrxSwapperDeps);
17
17
  getType(): SwapperType;
18
- buildQuoteTx(args: BuildQuoteTxInput): Promise<Quote<ChainTypes>>;
19
- getQuote(input: GetQuoteInput): Promise<Quote<ChainTypes>>;
20
18
  buildTrade(args: BuildTradeInput): Promise<Trade<ChainTypes>>;
21
19
  getTradeQuote(input: GetTradeQuoteInput): Promise<TradeQuote<ChainTypes>>;
22
20
  getUsdRate(input: Pick<Asset, 'symbol' | 'tokenId'>): Promise<string>;
23
21
  getMinMax(input: GetQuoteInput): Promise<MinMaxOutput>;
24
- executeQuote(args: ExecQuoteInput<ChainTypes>): Promise<ExecQuoteOutput>;
25
22
  executeTrade(args: ExecuteTradeInput<ChainTypes>): Promise<ExecQuoteOutput>;
26
23
  approvalNeeded(args: ApprovalNeededInput<ChainTypes>): Promise<ApprovalNeededOutput>;
27
24
  approveInfinite(args: ApproveInfiniteInput<ChainTypes>): Promise<string>;
28
- filterBuyAssetsBySellAssetId(args: BuyAssetBySellIdInput): CAIP19[];
29
- filterAssetIdsBySellable(assetIds: CAIP19[]): CAIP19[];
25
+ filterBuyAssetsBySellAssetId(args: BuyAssetBySellIdInput): AssetId[];
26
+ filterAssetIdsBySellable(assetIds: AssetId[]): AssetId[];
30
27
  }
@@ -3,14 +3,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ZrxSwapper = exports.ZrxError = void 0;
4
4
  const types_1 = require("@shapeshiftoss/types");
5
5
  const getZrxMinMax_1 = require("./getZrxMinMax/getZrxMinMax");
6
- const getZrxQuote_1 = require("./getZrxQuote/getZrxQuote");
7
6
  const getZrxTradeQuote_1 = require("./getZrxTradeQuote/getZrxTradeQuote");
8
7
  const helpers_1 = require("./utils/helpers/helpers");
9
8
  const ZrxApprovalNeeded_1 = require("./ZrxApprovalNeeded/ZrxApprovalNeeded");
10
9
  const ZrxApproveInfinite_1 = require("./ZrxApproveInfinite/ZrxApproveInfinite");
11
- const ZrxBuildQuoteTx_1 = require("./ZrxBuildQuoteTx/ZrxBuildQuoteTx");
12
10
  const zrxBuildTrade_1 = require("./zrxBuildTrade/zrxBuildTrade");
13
- const ZrxExecuteQuote_1 = require("./ZrxExecuteQuote/ZrxExecuteQuote");
14
11
  const zrxExecuteTrade_1 = require("./zrxExecuteTrade/zrxExecuteTrade");
15
12
  class ZrxError extends Error {
16
13
  constructor(message) {
@@ -26,12 +23,6 @@ class ZrxSwapper {
26
23
  getType() {
27
24
  return types_1.SwapperType.Zrx;
28
25
  }
29
- async buildQuoteTx(args) {
30
- return (0, ZrxBuildQuoteTx_1.ZrxBuildQuoteTx)(this.deps, args);
31
- }
32
- async getQuote(input) {
33
- return (0, getZrxQuote_1.getZrxQuote)(input);
34
- }
35
26
  async buildTrade(args) {
36
27
  return (0, zrxBuildTrade_1.zrxBuildTrade)(this.deps, args);
37
28
  }
@@ -44,9 +35,6 @@ class ZrxSwapper {
44
35
  async getMinMax(input) {
45
36
  return (0, getZrxMinMax_1.getZrxMinMax)(input);
46
37
  }
47
- async executeQuote(args) {
48
- return (0, ZrxExecuteQuote_1.ZrxExecuteQuote)(this.deps, args);
49
- }
50
38
  async executeTrade(args) {
51
39
  return (0, zrxExecuteTrade_1.zrxExecuteTrade)(this.deps, args);
52
40
  }
@@ -58,7 +46,6 @@ class ZrxSwapper {
58
46
  }
59
47
  filterBuyAssetsBySellAssetId(args) {
60
48
  const { assetIds, sellAssetId } = args;
61
- // TODO: pending changes to caip lib, we may want to import caip2 value instead.
62
49
  return assetIds.filter((id) => id.startsWith('eip155:1') && sellAssetId.startsWith('eip155:1'));
63
50
  }
64
51
  filterAssetIdsBySellable(assetIds) {
@@ -6,8 +6,6 @@ const types_1 = require("@shapeshiftoss/types");
6
6
  exports.BTC = {
7
7
  assetId: 'bip122:000000000019d6689c085ae165831e93/slip44:0',
8
8
  chainId: 'bip122:000000000019d6689c085ae165831e93',
9
- caip19: 'bip122:000000000019d6689c085ae165831e93/slip44:0',
10
- caip2: 'bip122:000000000019d6689c085ae165831e93',
11
9
  name: 'bitcoin',
12
10
  chain: types_1.ChainTypes.Bitcoin,
13
11
  dataSource: types_1.AssetDataSource.CoinGecko,
@@ -28,8 +26,6 @@ exports.BTC = {
28
26
  exports.WETH = {
29
27
  assetId: 'eip155:1/erc20:0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',
30
28
  chainId: 'eip155:1',
31
- caip19: 'eip155:1/erc20:0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',
32
- caip2: 'eip155:1',
33
29
  name: 'WETH',
34
30
  chain: types_1.ChainTypes.Ethereum,
35
31
  dataSource: types_1.AssetDataSource.CoinGecko,
@@ -51,8 +47,6 @@ exports.WETH = {
51
47
  exports.FOX = {
52
48
  assetId: 'eip155:1/erc20:0xc770eefad204b5180df6a14ee197d99d808ee52d',
53
49
  chainId: 'eip155:1',
54
- caip19: 'eip155:1/erc20:0xc770eefad204b5180df6a14ee197d99d808ee52d',
55
- caip2: 'eip155:1',
56
50
  name: 'FOX',
57
51
  chain: types_1.ChainTypes.Ethereum,
58
52
  dataSource: types_1.AssetDataSource.CoinGecko,
@@ -6,18 +6,63 @@ export declare const setupQuote: () => {
6
6
  buyAsset: Asset;
7
7
  success: boolean;
8
8
  sellAmount: string;
9
- slippage: string;
10
9
  allowanceContract: string;
11
10
  allowanceTarget: string;
12
11
  receiveAddress: string;
13
12
  sellAssetAccountId: string;
14
13
  buyAssetAccountId: string;
14
+ sendMax: boolean;
15
15
  };
16
16
  buyAsset: Asset;
17
17
  sellAsset: Asset;
18
18
  };
19
- export declare const setupZrxQuoteResponse: () => {
19
+ export declare const setupZrxTradeQuoteResponse: () => {
20
20
  quoteResponse: ZrxQuoteResponse;
21
21
  buyAsset: Asset;
22
22
  sellAsset: Asset;
23
23
  };
24
+ export declare const setupBuildTrade: () => {
25
+ buildTradeInput: {
26
+ sellAmount: string;
27
+ allowanceTarget: string;
28
+ price: string;
29
+ to: string;
30
+ buyAmount: string;
31
+ buyAsset: Asset;
32
+ sendMax: boolean;
33
+ sellAssetAccountId: string;
34
+ buyAssetAccountId: string;
35
+ sellAsset: Asset;
36
+ };
37
+ buyAsset: Asset;
38
+ sellAsset: Asset;
39
+ };
40
+ export declare const setupExecuteTrade: () => {
41
+ executeTradeInput: {
42
+ sellAmount: string;
43
+ allowanceTarget: string;
44
+ price: string;
45
+ to: string;
46
+ gas: string;
47
+ gasPrice: string;
48
+ buyAmount: string;
49
+ buyAsset: Asset;
50
+ sellAsset: Asset;
51
+ sendMax: boolean;
52
+ sellAssetAccountId: string;
53
+ txData: string;
54
+ depositAddress: string;
55
+ receiveAddress: string;
56
+ success: boolean;
57
+ statusReason: string;
58
+ feeData: {
59
+ fee: string;
60
+ chainSpecific: {};
61
+ };
62
+ rate: string;
63
+ allowanceContract: string;
64
+ sources: never[];
65
+ };
66
+ buyAsset: Asset;
67
+ sellAsset: Asset;
68
+ };
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.setupZrxQuoteResponse = exports.setupQuote = void 0;
4
- const constants_1 = require("../constants");
3
+ exports.setupExecuteTrade = exports.setupBuildTrade = exports.setupZrxTradeQuoteResponse = exports.setupQuote = void 0;
5
4
  const assets_1 = require("./assets");
6
5
  const setupQuote = () => {
7
6
  const sellAsset = { ...assets_1.FOX };
@@ -11,17 +10,17 @@ const setupQuote = () => {
11
10
  buyAsset,
12
11
  success: true,
13
12
  sellAmount: '1000000000000000000',
14
- slippage: constants_1.DEFAULT_SLIPPAGE,
15
13
  allowanceContract: 'allowanceContractAddress',
16
14
  allowanceTarget: 'allowanceTargetAddress',
17
15
  receiveAddress: 'receiveAddress',
18
16
  sellAssetAccountId: '0',
19
- buyAssetAccountId: '0'
17
+ buyAssetAccountId: '0',
18
+ sendMax: false
20
19
  };
21
20
  return { quoteInput, buyAsset, sellAsset };
22
21
  };
23
22
  exports.setupQuote = setupQuote;
24
- const setupZrxQuoteResponse = () => {
23
+ const setupZrxTradeQuoteResponse = () => {
25
24
  const sellAsset = { ...assets_1.FOX };
26
25
  const buyAsset = { ...assets_1.WETH };
27
26
  const quoteResponse = {
@@ -37,4 +36,50 @@ const setupZrxQuoteResponse = () => {
37
36
  };
38
37
  return { quoteResponse, buyAsset, sellAsset };
39
38
  };
40
- exports.setupZrxQuoteResponse = setupZrxQuoteResponse;
39
+ exports.setupZrxTradeQuoteResponse = setupZrxTradeQuoteResponse;
40
+ const setupBuildTrade = () => {
41
+ const sellAsset = { ...assets_1.FOX };
42
+ const buyAsset = { ...assets_1.WETH };
43
+ const buildTradeInput = {
44
+ sellAmount: '1000000000000000000',
45
+ allowanceTarget: 'allowanceTargetAddress',
46
+ price: '1',
47
+ to: '0x123',
48
+ buyAmount: '',
49
+ buyAsset,
50
+ sendMax: false,
51
+ sellAssetAccountId: '0',
52
+ buyAssetAccountId: '0',
53
+ sellAsset
54
+ };
55
+ return { buildTradeInput, buyAsset, sellAsset };
56
+ };
57
+ exports.setupBuildTrade = setupBuildTrade;
58
+ const setupExecuteTrade = () => {
59
+ const sellAsset = { ...assets_1.FOX };
60
+ const buyAsset = { ...assets_1.WETH };
61
+ const executeTradeInput = {
62
+ sellAmount: '1000000000000000000',
63
+ allowanceTarget: 'allowanceTargetAddress',
64
+ price: '1',
65
+ to: '0x123',
66
+ gas: '1235',
67
+ gasPrice: '1236',
68
+ buyAmount: '',
69
+ buyAsset,
70
+ sellAsset,
71
+ sendMax: false,
72
+ sellAssetAccountId: '0',
73
+ txData: '0x0',
74
+ depositAddress: '0x0',
75
+ receiveAddress: '0x0',
76
+ success: true,
77
+ statusReason: '',
78
+ feeData: { fee: '0', chainSpecific: {} },
79
+ rate: '0',
80
+ allowanceContract: '0x0',
81
+ sources: []
82
+ };
83
+ return { executeTradeInput, buyAsset, sellAsset };
84
+ };
85
+ exports.setupExecuteTrade = setupExecuteTrade;
@@ -20,7 +20,7 @@ export declare const chainAdapterMockFuncs: {
20
20
  getAccount: jest.Mock<Promise<{
21
21
  chainSpecific: {
22
22
  tokens: {
23
- caip19: string;
23
+ assetId: string;
24
24
  balance: string;
25
25
  }[];
26
26
  };
@@ -16,7 +16,7 @@ exports.chainAdapterMockFuncs = {
16
16
  getInfo: jest.fn(() => Promise.resolve({ data: { network: 'mainnet' } })),
17
17
  getAddress: jest.fn(() => Promise.resolve('address')),
18
18
  getAccount: jest.fn(() => Promise.resolve({
19
- chainSpecific: { tokens: [{ caip19: 'eip155:1/erc20:contractAddress', balance: '1000000' }] }
19
+ chainSpecific: { tokens: [{ assetId: 'eip155:1/erc20:contractAddress', balance: '1000000' }] }
20
20
  })),
21
21
  getFeeData: jest.fn(() => Promise.resolve({
22
22
  [types_1.chainAdapters.FeeDataKey.Average]: { txFee: '10000' }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shapeshiftoss/swapper",
3
- "version": "3.0.6",
3
+ "version": "4.0.1",
4
4
  "description": "TODO: description",
5
5
  "repository": "https://github.com/shapeshift/lib",
6
6
  "license": "MIT",
@@ -31,17 +31,17 @@
31
31
  },
32
32
  "peerDependencies": {
33
33
  "@shapeshiftoss/asset-service": "^2.0.0",
34
- "@shapeshiftoss/caip": "^2.0.0",
35
- "@shapeshiftoss/chain-adapters": "^2.0.0",
34
+ "@shapeshiftoss/caip": "^3.0.0",
35
+ "@shapeshiftoss/chain-adapters": "^3.0.0",
36
36
  "@shapeshiftoss/hdwallet-core": "1.20.0",
37
- "@shapeshiftoss/types": "^3.0.0"
37
+ "@shapeshiftoss/types": "^4.0.0"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@shapeshiftoss/asset-service": "^2.0.0",
41
- "@shapeshiftoss/caip": "^2.0.0",
42
- "@shapeshiftoss/chain-adapters": "^2.0.0",
41
+ "@shapeshiftoss/caip": "^3.0.0",
42
+ "@shapeshiftoss/chain-adapters": "^3.0.0",
43
43
  "@shapeshiftoss/hdwallet-core": "^1.20.0",
44
- "@shapeshiftoss/types": "^3.0.0",
44
+ "@shapeshiftoss/types": "^4.0.0",
45
45
  "@types/readline-sync": "^1.4.4",
46
46
  "readline-sync": "^1.4.10",
47
47
  "web3-utils": "^1.5.2"
@@ -1,3 +0,0 @@
1
- import { BuildQuoteTxInput, ChainTypes, Quote } from '@shapeshiftoss/types';
2
- import { ZrxSwapperDeps } from '../ZrxSwapper';
3
- export declare function ZrxBuildQuoteTx({ adapterManager, web3 }: ZrxSwapperDeps, { input, wallet }: BuildQuoteTxInput): Promise<Quote<ChainTypes>>;
@@ -1,161 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.ZrxBuildQuoteTx = void 0;
27
- const types_1 = require("@shapeshiftoss/types");
28
- const rax = __importStar(require("retry-axios"));
29
- const __1 = require("../../..");
30
- const erc20Allowance_abi_1 = require("../utils/abi/erc20Allowance-abi");
31
- const applyAxiosRetry_1 = require("../utils/applyAxiosRetry");
32
- const bignumber_1 = require("../utils/bignumber");
33
- const constants_1 = require("../utils/constants");
34
- const helpers_1 = require("../utils/helpers/helpers");
35
- const zrxService_1 = require("../utils/zrxService");
36
- async function ZrxBuildQuoteTx({ adapterManager, web3 }, { input, wallet }) {
37
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
38
- const { sellAsset, buyAsset, sellAmount, buyAmount, slippage, sellAssetAccountId, buyAssetAccountId } = input;
39
- if ((buyAmount && sellAmount) || (!buyAmount && !sellAmount)) {
40
- throw new __1.SwapError('ZrxSwapper:ZrxBuildQuoteTx Exactly one of buyAmount or sellAmount is required');
41
- }
42
- if (!sellAssetAccountId || !buyAssetAccountId) {
43
- throw new __1.SwapError('ZrxSwapper:ZrxBuildQuoteTx Both sellAssetAccountId and buyAssetAccountId are required');
44
- }
45
- const buyToken = buyAsset.tokenId || buyAsset.symbol || buyAsset.network;
46
- const sellToken = sellAsset.tokenId || sellAsset.symbol || sellAsset.network;
47
- if (!buyToken) {
48
- throw new __1.SwapError('ZrxSwapper:ZrxBuildQuoteTx One of buyAssetContract or buyAssetSymbol or buyAssetNetwork are required');
49
- }
50
- if (!sellToken) {
51
- throw new __1.SwapError('ZrxSwapper:ZrxBuildQuoteTx One of sellAssetContract or sellAssetSymbol or sellAssetNetwork are required');
52
- }
53
- if (buyAsset.chain !== types_1.ChainTypes.Ethereum) {
54
- throw new __1.SwapError(`ZrxSwapper:ZrxBuildQuoteTx buyAsset must be on chain [${types_1.ChainTypes.Ethereum}]`);
55
- }
56
- const adapter = adapterManager.byChain(buyAsset.chain);
57
- const bip44Params = adapter.buildBIP44Params({ accountNumber: Number(buyAssetAccountId) });
58
- const receiveAddress = await adapter.getAddress({ wallet, bip44Params });
59
- if ((0, bignumber_1.bnOrZero)(slippage).gt(constants_1.MAX_SLIPPAGE)) {
60
- throw new __1.SwapError(`ZrxSwapper:ZrxBuildQuoteTx slippage value of ${slippage} is greater than max slippage value of ${constants_1.MAX_SLIPPAGE}`);
61
- }
62
- const slippagePercentage = slippage ? (0, bignumber_1.bnOrZero)(slippage).div(100).toString() : constants_1.DEFAULT_SLIPPAGE;
63
- try {
64
- /**
65
- * /swap/v1/quote
66
- * params: {
67
- * sellToken: contract address (or symbol) of token to sell
68
- * buyToken: contractAddress (or symbol) of token to buy
69
- * sellAmount?: integer string value of the smallest increment of the sell token
70
- * buyAmount?: integer string value of the smallest incremtent of the buy token
71
- * }
72
- */
73
- const zrxRetry = (0, applyAxiosRetry_1.applyAxiosRetry)(zrxService_1.zrxService, {
74
- statusCodesToRetry: [[400, 400]],
75
- shouldRetry: (err) => {
76
- var _a, _b, _c, _d;
77
- const cfg = rax.getConfig(err);
78
- const retryAttempt = (_a = cfg === null || cfg === void 0 ? void 0 : cfg.currentRetryAttempt) !== null && _a !== void 0 ? _a : 0;
79
- const retry = (_b = cfg === null || cfg === void 0 ? void 0 : cfg.retry) !== null && _b !== void 0 ? _b : 3;
80
- // ensure max retries is always respected
81
- if (retryAttempt >= retry)
82
- return false;
83
- // retry if 0x returns error code 111 Gas estimation failed
84
- if (((_d = (_c = err === null || err === void 0 ? void 0 : err.response) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.code) === 111)
85
- return true;
86
- // Handle the request based on your other config options, e.g. `statusCodesToRetry`
87
- return rax.shouldRetryRequest(err);
88
- }
89
- });
90
- const quoteResponse = await zrxRetry.get('/swap/v1/quote', {
91
- params: {
92
- buyToken,
93
- sellToken,
94
- sellAmount: (0, helpers_1.normalizeAmount)(sellAmount === null || sellAmount === void 0 ? void 0 : sellAmount.toString()),
95
- buyAmount: (0, helpers_1.normalizeAmount)(buyAmount === null || buyAmount === void 0 ? void 0 : buyAmount.toString()),
96
- takerAddress: receiveAddress,
97
- slippagePercentage,
98
- skipValidation: false,
99
- affiliateAddress: constants_1.AFFILIATE_ADDRESS
100
- }
101
- });
102
- const { data } = quoteResponse;
103
- const estimatedGas = (0, bignumber_1.bnOrZero)(data.gas);
104
- const quote = {
105
- sellAsset,
106
- buyAsset,
107
- sellAssetAccountId,
108
- buyAssetAccountId,
109
- receiveAddress,
110
- success: true,
111
- rate: data.price,
112
- depositAddress: data.to,
113
- feeData: {
114
- fee: (0, bignumber_1.bnOrZero)(estimatedGas).multipliedBy((0, bignumber_1.bnOrZero)(data.gasPrice)).toString(),
115
- chainSpecific: {
116
- estimatedGas: estimatedGas.toString(),
117
- gasPrice: data.gasPrice
118
- }
119
- },
120
- txData: data.data,
121
- sellAmount: data.sellAmount,
122
- buyAmount: data.buyAmount,
123
- allowanceContract: data.allowanceTarget,
124
- sources: ((_a = data.sources) === null || _a === void 0 ? void 0 : _a.filter((s) => parseFloat(s.proportion) > 0)) || constants_1.DEFAULT_SOURCE
125
- };
126
- if (!data.allowanceTarget)
127
- throw new __1.SwapError('ZrxSwapper:ZrxBuildQuoteTx no allowance target');
128
- if (!data.sellAmount)
129
- throw new __1.SwapError('ZrxSwapper:ZrxBuildQuoteTx no sell amount');
130
- const allowanceRequired = await (0, helpers_1.getAllowanceRequired)({
131
- sellAsset,
132
- allowanceContract: data.allowanceTarget,
133
- receiveAddress,
134
- sellAmount: data.sellAmount,
135
- web3,
136
- erc20AllowanceAbi: erc20Allowance_abi_1.erc20AllowanceAbi
137
- });
138
- if (allowanceRequired) {
139
- quote.feeData = {
140
- fee: ((_b = quote.feeData) === null || _b === void 0 ? void 0 : _b.fee) || '0',
141
- chainSpecific: {
142
- ...(_c = quote.feeData) === null || _c === void 0 ? void 0 : _c.chainSpecific,
143
- approvalFee: (0, bignumber_1.bnOrZero)(constants_1.APPROVAL_GAS_LIMIT).multipliedBy((0, bignumber_1.bnOrZero)(data.gasPrice)).toString()
144
- }
145
- };
146
- }
147
- return quote;
148
- }
149
- catch (e) {
150
- const statusReason = ((_g = (_f = (_e = (_d = e === null || e === void 0 ? void 0 : e.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.validationErrors) === null || _f === void 0 ? void 0 : _f[0]) === null || _g === void 0 ? void 0 : _g.reason) ||
151
- ((_j = (_h = e === null || e === void 0 ? void 0 : e.response) === null || _h === void 0 ? void 0 : _h.data) === null || _j === void 0 ? void 0 : _j.reason) ||
152
- 'Unknown Error';
153
- return {
154
- sellAsset,
155
- buyAsset,
156
- success: false,
157
- statusReason
158
- };
159
- }
160
- }
161
- exports.ZrxBuildQuoteTx = ZrxBuildQuoteTx;
@@ -1,3 +0,0 @@
1
- import { ChainTypes, ExecQuoteInput, ExecQuoteOutput } from '@shapeshiftoss/types';
2
- import { ZrxSwapperDeps } from '../ZrxSwapper';
3
- export declare function ZrxExecuteQuote({ adapterManager }: ZrxSwapperDeps, { quote, wallet }: ExecQuoteInput<ChainTypes.Ethereum>): Promise<ExecQuoteOutput>;
@@ -1,79 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ZrxExecuteQuote = void 0;
4
- const web3_utils_1 = require("web3-utils");
5
- const api_1 = require("../../../api");
6
- async function ZrxExecuteQuote({ adapterManager }, { quote, wallet }) {
7
- var _a, _b, _c, _d, _e, _f;
8
- const { sellAsset } = quote;
9
- if (!quote.success) {
10
- throw new api_1.SwapError('ZrxSwapper:ZrxExecuteQuote Cannot execute a failed quote');
11
- }
12
- if (!sellAsset.network || !sellAsset.symbol) {
13
- throw new api_1.SwapError('ZrxSwapper:ZrxExecuteQuote sellAssetNetwork and sellAssetSymbol are required');
14
- }
15
- if (!quote.sellAssetAccountId) {
16
- throw new api_1.SwapError('ZrxSwapper:ZrxExecuteQuote sellAssetAccountId is required');
17
- }
18
- if (!quote.sellAmount) {
19
- throw new api_1.SwapError('ZrxSwapper:ZrxExecuteQuote sellAmount is required');
20
- }
21
- if (!quote.depositAddress) {
22
- throw new api_1.SwapError('ZrxSwapper:ZrxExecuteQuote depositAddress is required');
23
- }
24
- // value is 0 for erc20s
25
- const value = sellAsset.symbol === 'ETH' ? quote.sellAmount : '0';
26
- const adapter = adapterManager.byChain(sellAsset.chain);
27
- const bip44Params = adapter.buildBIP44Params({
28
- accountNumber: Number(quote.sellAssetAccountId)
29
- });
30
- let buildTxResponse, signedTx, txid;
31
- try {
32
- buildTxResponse = await adapter.buildSendTransaction({
33
- value,
34
- wallet,
35
- to: quote.depositAddress,
36
- chainSpecific: {
37
- gasPrice: (0, web3_utils_1.numberToHex)(((_b = (_a = quote.feeData) === null || _a === void 0 ? void 0 : _a.chainSpecific) === null || _b === void 0 ? void 0 : _b.gasPrice) || 0),
38
- gasLimit: (0, web3_utils_1.numberToHex)(((_d = (_c = quote.feeData) === null || _c === void 0 ? void 0 : _c.chainSpecific) === null || _d === void 0 ? void 0 : _d.estimatedGas) || 0)
39
- },
40
- bip44Params
41
- });
42
- }
43
- catch (error) {
44
- throw new api_1.SwapError(`ZrxExecuteQuote - buildSendTransaction error: ${error}`);
45
- }
46
- const { txToSign } = buildTxResponse;
47
- const txWithQuoteData = { ...txToSign, data: (_e = quote.txData) !== null && _e !== void 0 ? _e : '' };
48
- if (wallet.supportsOfflineSigning()) {
49
- try {
50
- signedTx = await adapter.signTransaction({ txToSign: txWithQuoteData, wallet });
51
- }
52
- catch (error) {
53
- throw new api_1.SwapError(`ZrxExecuteQuote - signTransaction error: ${error}`);
54
- }
55
- if (!signedTx) {
56
- throw new api_1.SwapError(`ZrxExecuteQuote - Signed transaction is required: ${signedTx}`);
57
- }
58
- try {
59
- txid = await adapter.broadcastTransaction(signedTx);
60
- }
61
- catch (error) {
62
- throw new api_1.SwapError(`ZrxExecuteQuote - broadcastTransaction error: ${error}`);
63
- }
64
- return { txid };
65
- }
66
- else if (wallet.supportsBroadcast() && adapter.signAndBroadcastTransaction) {
67
- try {
68
- txid = await ((_f = adapter.signAndBroadcastTransaction) === null || _f === void 0 ? void 0 : _f.call(adapter, { txToSign: txWithQuoteData, wallet }));
69
- }
70
- catch (error) {
71
- throw new api_1.SwapError(`ZrxExecuteQuote - signAndBroadcastTransaction error: ${error}`);
72
- }
73
- return { txid };
74
- }
75
- else {
76
- throw new api_1.SwapError('ZrxExecuteQuote - invalid HDWallet config');
77
- }
78
- }
79
- exports.ZrxExecuteQuote = ZrxExecuteQuote;
@@ -1,2 +0,0 @@
1
- import { ChainTypes, GetQuoteInput, Quote } from '@shapeshiftoss/types';
2
- export declare function getZrxQuote(input: GetQuoteInput): Promise<Quote<ChainTypes.Ethereum>>;
@@ -1,95 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getZrxQuote = void 0;
4
- const types_1 = require("@shapeshiftoss/types");
5
- const getZrxMinMax_1 = require("../getZrxMinMax/getZrxMinMax");
6
- const bignumber_1 = require("../utils/bignumber");
7
- const constants_1 = require("../utils/constants");
8
- const helpers_1 = require("../utils/helpers/helpers");
9
- const zrxService_1 = require("../utils/zrxService");
10
- const ZrxSwapper_1 = require("../ZrxSwapper");
11
- async function getZrxQuote(input) {
12
- var _a, _b, _c, _d, _e, _f, _g;
13
- const { sellAsset, buyAsset, sellAmount, buyAmount } = input;
14
- if (!buyAsset) {
15
- throw new ZrxSwapper_1.ZrxError('getQuote - Missing buyAsset');
16
- }
17
- if (!sellAsset) {
18
- throw new ZrxSwapper_1.ZrxError('getQuote - Missing sellAsset');
19
- }
20
- if (buyAsset.chain !== types_1.ChainTypes.Ethereum || sellAsset.chain !== types_1.ChainTypes.Ethereum) {
21
- throw new ZrxSwapper_1.ZrxError('getQuote - Both assets need to be on the Ethereum chain to use Zrx');
22
- }
23
- if (!sellAmount && !buyAmount) {
24
- throw new ZrxSwapper_1.ZrxError('getQuote - sellAmount or buyAmount amount is required');
25
- }
26
- const useSellAmount = !!sellAmount;
27
- const buyToken = buyAsset.tokenId || buyAsset.symbol;
28
- const sellToken = sellAsset.tokenId || sellAsset.symbol;
29
- const { minimum: minQuoteSellAmount, maximum: maxSellAmount } = await (0, getZrxMinMax_1.getZrxMinMax)(input);
30
- const minQuoteSellAmountWei = (0, bignumber_1.bnOrZero)(minQuoteSellAmount).times((0, bignumber_1.bnOrZero)(10).exponentiatedBy(sellAsset.precision));
31
- const amount = useSellAmount ? { sellAmount } : { buyAmount };
32
- const amountKey = Object.keys(amount)[0];
33
- const amountValue = Object.values(amount)[0];
34
- let normalizedAmount = (0, helpers_1.normalizeAmount)(amountValue);
35
- if (!normalizedAmount || normalizedAmount === '0') {
36
- normalizedAmount = (0, helpers_1.normalizeAmount)(minQuoteSellAmountWei === null || minQuoteSellAmountWei === void 0 ? void 0 : minQuoteSellAmountWei.toString());
37
- }
38
- if (!normalizedAmount || normalizedAmount === '0') {
39
- throw new ZrxSwapper_1.ZrxError('getQuote - Must have valid sellAmount, buyAmount or minimum amount');
40
- }
41
- try {
42
- /**
43
- * /swap/v1/price
44
- * params: {
45
- * sellToken: contract address (or symbol) of token to sell
46
- * buyToken: contractAddress (or symbol) of token to buy
47
- * sellAmount?: integer string value of the smallest increment of the sell token
48
- * buyAmount?: integer string value of the smallest incremtent of the buy token
49
- * }
50
- */
51
- const quoteResponse = await zrxService_1.zrxService.get('/swap/v1/price', {
52
- params: {
53
- sellToken,
54
- buyToken,
55
- [amountKey]: normalizedAmount
56
- }
57
- });
58
- const { data } = quoteResponse;
59
- const estimatedGas = (0, bignumber_1.bnOrZero)(data.estimatedGas).times(1.5);
60
- const rate = useSellAmount ? data.price : (0, bignumber_1.bnOrZero)(1).div(data.price).toString();
61
- return {
62
- sellAsset,
63
- buyAsset,
64
- success: true,
65
- rate,
66
- minimum: minQuoteSellAmount,
67
- maximum: maxSellAmount,
68
- feeData: {
69
- fee: (0, bignumber_1.bnOrZero)(estimatedGas).multipliedBy((0, bignumber_1.bnOrZero)(data.gasPrice)).toString(),
70
- chainSpecific: {
71
- estimatedGas: estimatedGas.toString(),
72
- gasPrice: data.gasPrice,
73
- approvalFee: sellAsset.tokenId &&
74
- (0, bignumber_1.bnOrZero)(constants_1.APPROVAL_GAS_LIMIT).multipliedBy((0, bignumber_1.bnOrZero)(data.gasPrice)).toString()
75
- }
76
- },
77
- sellAmount: data.sellAmount,
78
- buyAmount: data.buyAmount,
79
- sources: ((_a = data.sources) === null || _a === void 0 ? void 0 : _a.filter((s) => parseFloat(s.proportion) > 0)) || constants_1.DEFAULT_SOURCE,
80
- allowanceContract: data.allowanceTarget
81
- };
82
- }
83
- catch (e) {
84
- const statusReason = ((_e = (_d = (_c = (_b = e === null || e === void 0 ? void 0 : e.response) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.validationErrors) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.reason) ||
85
- ((_g = (_f = e === null || e === void 0 ? void 0 : e.response) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.reason) ||
86
- 'Unknown Error';
87
- return {
88
- sellAsset,
89
- buyAsset,
90
- success: false,
91
- statusReason
92
- };
93
- }
94
- }
95
- exports.getZrxQuote = getZrxQuote;