@shapeshiftoss/swapper 17.7.3 → 17.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.
Files changed (124) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/constants.js +35 -26
  3. package/dist/cjs/index.d.ts +1 -0
  4. package/dist/cjs/index.js +1 -0
  5. package/dist/cjs/swappers/ArbitrumBridgeSwapper/getTradeQuote/getTradeQuote.test.js +12 -4
  6. package/dist/cjs/swappers/BebopSwapper/getBebopSolanaTradeRate/getBebopSolanaTradeRate.js +9 -5
  7. package/dist/cjs/swappers/BebopSwapper/getBebopTradeQuote/getBebopTradeQuote.js +1 -9
  8. package/dist/cjs/swappers/BebopSwapper/getBebopTradeRate/getBebopTradeRate.js +9 -13
  9. package/dist/cjs/swappers/BebopSwapper/types.d.ts +64 -78
  10. package/dist/cjs/swappers/BebopSwapper/utils/fetchFromBebop.d.ts +0 -16
  11. package/dist/cjs/swappers/BebopSwapper/utils/fetchFromBebop.js +49 -82
  12. package/dist/cjs/swappers/BobGatewaySwapper/BobGatewaySwapper.d.ts +2 -0
  13. package/dist/cjs/swappers/BobGatewaySwapper/BobGatewaySwapper.js +8 -0
  14. package/dist/cjs/swappers/BobGatewaySwapper/endpoints.d.ts +2 -0
  15. package/dist/cjs/swappers/BobGatewaySwapper/endpoints.js +143 -0
  16. package/dist/cjs/swappers/BobGatewaySwapper/index.d.ts +3 -0
  17. package/dist/cjs/swappers/BobGatewaySwapper/index.js +22 -0
  18. package/dist/cjs/swappers/BobGatewaySwapper/swapperApi/getTradeQuote.d.ts +3 -0
  19. package/dist/cjs/swappers/BobGatewaySwapper/swapperApi/getTradeQuote.js +90 -0
  20. package/dist/cjs/swappers/BobGatewaySwapper/swapperApi/getTradeRate.d.ts +3 -0
  21. package/dist/cjs/swappers/BobGatewaySwapper/swapperApi/getTradeRate.js +73 -0
  22. package/dist/cjs/swappers/BobGatewaySwapper/types.d.ts +20 -0
  23. package/dist/cjs/swappers/BobGatewaySwapper/types.js +2 -0
  24. package/dist/cjs/swappers/BobGatewaySwapper/utils/constants.d.ts +13 -0
  25. package/dist/cjs/swappers/BobGatewaySwapper/utils/constants.js +31 -0
  26. package/dist/cjs/swappers/BobGatewaySwapper/utils/helpers.d.ts +49 -0
  27. package/dist/cjs/swappers/BobGatewaySwapper/utils/helpers.js +314 -0
  28. package/dist/cjs/swappers/ChainflipSwapper/ChainflipSwapper.js +1 -0
  29. package/dist/cjs/swappers/ChainflipSwapper/constants.d.ts +1 -1
  30. package/dist/cjs/swappers/ChainflipSwapper/constants.js +3 -0
  31. package/dist/cjs/swappers/ChainflipSwapper/endpoints.js +20 -0
  32. package/dist/cjs/swappers/ChainflipSwapper/types.d.ts +2 -1
  33. package/dist/cjs/swappers/ChainflipSwapper/types.js +1 -0
  34. package/dist/cjs/swappers/ChainflipSwapper/utils/getQuoteOrRate.js +23 -3
  35. package/dist/cjs/swappers/ChainflipSwapper/utils/helpers.d.ts +2 -2
  36. package/dist/cjs/swappers/ChainflipSwapper/utils/helpers.js +2 -1
  37. package/dist/cjs/swappers/CowSwapper/utils/helpers/helpers.test.js +3 -3
  38. package/dist/cjs/swappers/RelaySwapper/constant.js +1 -1
  39. package/dist/cjs/swappers/SunioSwapper/endpoints.js +19 -36
  40. package/dist/cjs/swappers/SunioSwapper/utils/buildSwapContractCall.d.ts +6 -0
  41. package/dist/cjs/swappers/SunioSwapper/utils/buildSwapContractCall.js +33 -0
  42. package/dist/cjs/swappers/SunioSwapper/utils/buildSwapRouteParameters.js +6 -6
  43. package/dist/cjs/swappers/SunioSwapper/utils/constants.d.ts +2 -0
  44. package/dist/cjs/swappers/SunioSwapper/utils/constants.js +7 -1
  45. package/dist/cjs/swappers/SunioSwapper/utils/estimateSunioNetworkFee.d.ts +12 -0
  46. package/dist/cjs/swappers/SunioSwapper/utils/estimateSunioNetworkFee.js +78 -0
  47. package/dist/cjs/swappers/SunioSwapper/utils/getQuoteOrRate.js +16 -74
  48. package/dist/cjs/swappers/SunioSwapper/utils/getSunioTransactionFees.d.ts +2 -0
  49. package/dist/cjs/swappers/SunioSwapper/utils/getSunioTransactionFees.js +36 -0
  50. package/dist/cjs/swappers/utils/helpers/helpers.js +1 -0
  51. package/dist/cjs/thorchain-utils/getL1RateOrQuote.js +5 -2
  52. package/dist/cjs/thorchain-utils/getQuote.js +27 -29
  53. package/dist/cjs/thorchain-utils/tron/getTronTransactionFees.js +8 -5
  54. package/dist/cjs/thorchain-utils/types.d.ts +1 -1
  55. package/dist/cjs/types.d.ts +10 -3
  56. package/dist/cjs/types.js +5 -0
  57. package/dist/esm/.tsbuildinfo +1 -1
  58. package/dist/esm/constants.js +9 -0
  59. package/dist/esm/index.d.ts +1 -0
  60. package/dist/esm/index.js +1 -0
  61. package/dist/esm/swappers/ArbitrumBridgeSwapper/getTradeQuote/getTradeQuote.test.js +12 -4
  62. package/dist/esm/swappers/BebopSwapper/getBebopSolanaTradeRate/getBebopSolanaTradeRate.js +10 -6
  63. package/dist/esm/swappers/BebopSwapper/getBebopTradeQuote/getBebopTradeQuote.js +1 -9
  64. package/dist/esm/swappers/BebopSwapper/getBebopTradeRate/getBebopTradeRate.js +10 -14
  65. package/dist/esm/swappers/BebopSwapper/types.d.ts +64 -78
  66. package/dist/esm/swappers/BebopSwapper/utils/fetchFromBebop.d.ts +0 -16
  67. package/dist/esm/swappers/BebopSwapper/utils/fetchFromBebop.js +45 -76
  68. package/dist/esm/swappers/BobGatewaySwapper/BobGatewaySwapper.d.ts +2 -0
  69. package/dist/esm/swappers/BobGatewaySwapper/BobGatewaySwapper.js +5 -0
  70. package/dist/esm/swappers/BobGatewaySwapper/endpoints.d.ts +2 -0
  71. package/dist/esm/swappers/BobGatewaySwapper/endpoints.js +140 -0
  72. package/dist/esm/swappers/BobGatewaySwapper/index.d.ts +3 -0
  73. package/dist/esm/swappers/BobGatewaySwapper/index.js +3 -0
  74. package/dist/esm/swappers/BobGatewaySwapper/swapperApi/getTradeQuote.d.ts +3 -0
  75. package/dist/esm/swappers/BobGatewaySwapper/swapperApi/getTradeQuote.js +86 -0
  76. package/dist/esm/swappers/BobGatewaySwapper/swapperApi/getTradeRate.d.ts +3 -0
  77. package/dist/esm/swappers/BobGatewaySwapper/swapperApi/getTradeRate.js +69 -0
  78. package/dist/esm/swappers/BobGatewaySwapper/types.d.ts +20 -0
  79. package/dist/esm/swappers/BobGatewaySwapper/utils/constants.d.ts +13 -0
  80. package/dist/esm/swappers/BobGatewaySwapper/utils/constants.js +27 -0
  81. package/dist/esm/swappers/BobGatewaySwapper/utils/helpers.d.ts +49 -0
  82. package/dist/esm/swappers/BobGatewaySwapper/utils/helpers.js +299 -0
  83. package/dist/esm/swappers/ChainflipSwapper/ChainflipSwapper.js +2 -1
  84. package/dist/esm/swappers/ChainflipSwapper/constants.d.ts +1 -1
  85. package/dist/esm/swappers/ChainflipSwapper/constants.js +4 -1
  86. package/dist/esm/swappers/ChainflipSwapper/endpoints.js +20 -0
  87. package/dist/esm/swappers/ChainflipSwapper/types.d.ts +2 -1
  88. package/dist/esm/swappers/ChainflipSwapper/types.js +1 -0
  89. package/dist/esm/swappers/ChainflipSwapper/utils/getQuoteOrRate.js +24 -4
  90. package/dist/esm/swappers/ChainflipSwapper/utils/helpers.d.ts +2 -2
  91. package/dist/esm/swappers/ChainflipSwapper/utils/helpers.js +2 -1
  92. package/dist/esm/swappers/CowSwapper/utils/helpers/helpers.test.js +3 -3
  93. package/dist/esm/swappers/RelaySwapper/constant.js +1 -1
  94. package/dist/esm/swappers/SunioSwapper/endpoints.js +19 -36
  95. package/dist/esm/swappers/SunioSwapper/utils/buildSwapContractCall.d.ts +6 -0
  96. package/dist/esm/swappers/SunioSwapper/utils/buildSwapContractCall.js +29 -0
  97. package/dist/esm/swappers/SunioSwapper/utils/buildSwapRouteParameters.js +6 -6
  98. package/dist/esm/swappers/SunioSwapper/utils/constants.d.ts +2 -0
  99. package/dist/esm/swappers/SunioSwapper/utils/constants.js +6 -0
  100. package/dist/esm/swappers/SunioSwapper/utils/estimateSunioNetworkFee.d.ts +12 -0
  101. package/dist/esm/swappers/SunioSwapper/utils/estimateSunioNetworkFee.js +74 -0
  102. package/dist/esm/swappers/SunioSwapper/utils/getQuoteOrRate.js +16 -74
  103. package/dist/esm/swappers/SunioSwapper/utils/getSunioTransactionFees.d.ts +2 -0
  104. package/dist/esm/swappers/SunioSwapper/utils/getSunioTransactionFees.js +32 -0
  105. package/dist/esm/swappers/utils/helpers/helpers.js +2 -1
  106. package/dist/esm/thorchain-utils/getL1RateOrQuote.js +5 -2
  107. package/dist/esm/thorchain-utils/getQuote.js +27 -29
  108. package/dist/esm/thorchain-utils/tron/getTronTransactionFees.js +8 -5
  109. package/dist/esm/thorchain-utils/types.d.ts +1 -1
  110. package/dist/esm/types.d.ts +10 -3
  111. package/dist/esm/types.js +5 -0
  112. package/package.json +8 -7
  113. package/dist/cjs/swappers/SunioSwapper/utils/buildSwapTransaction.d.ts +0 -11
  114. package/dist/cjs/swappers/SunioSwapper/utils/buildSwapTransaction.js +0 -57
  115. package/dist/cjs/thorchain-utils/getThresholdedAffiliateBps/getThresholdedAffiliateBps.d.ts +0 -12
  116. package/dist/cjs/thorchain-utils/getThresholdedAffiliateBps/getThresholdedAffiliateBps.js +0 -47
  117. package/dist/cjs/thorchain-utils/getThresholdedAffiliateBps/getThresholdedAffiliateBps.test.js +0 -100
  118. package/dist/esm/swappers/SunioSwapper/utils/buildSwapTransaction.d.ts +0 -11
  119. package/dist/esm/swappers/SunioSwapper/utils/buildSwapTransaction.js +0 -53
  120. package/dist/esm/thorchain-utils/getThresholdedAffiliateBps/getThresholdedAffiliateBps.d.ts +0 -12
  121. package/dist/esm/thorchain-utils/getThresholdedAffiliateBps/getThresholdedAffiliateBps.js +0 -41
  122. package/dist/esm/thorchain-utils/getThresholdedAffiliateBps/getThresholdedAffiliateBps.test.d.ts +0 -1
  123. package/dist/esm/thorchain-utils/getThresholdedAffiliateBps/getThresholdedAffiliateBps.test.js +0 -98
  124. /package/dist/{cjs/thorchain-utils/getThresholdedAffiliateBps/getThresholdedAffiliateBps.test.d.ts → esm/swappers/BobGatewaySwapper/types.js} +0 -0
@@ -5,23 +5,14 @@ const caip_1 = require("@shapeshiftoss/caip");
5
5
  const chain_adapters_1 = require("@shapeshiftoss/chain-adapters");
6
6
  const unchained_client_1 = require("@shapeshiftoss/unchained-client");
7
7
  const tronweb_1 = require("tronweb");
8
- const getTronTransactionFees_1 = require("../../tron-utils/getTronTransactionFees");
9
8
  const utils_1 = require("../../utils");
10
9
  const getSunioTradeQuote_1 = require("./getSunioTradeQuote/getSunioTradeQuote");
11
10
  const getSunioTradeRate_1 = require("./getSunioTradeRate/getSunioTradeRate");
11
+ const buildSwapContractCall_1 = require("./utils/buildSwapContractCall");
12
12
  const buildSwapRouteParameters_1 = require("./utils/buildSwapRouteParameters");
13
13
  const constants_1 = require("./utils/constants");
14
+ const getSunioTransactionFees_1 = require("./utils/getSunioTransactionFees");
14
15
  const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
15
- const convertAddressesToEvmFormat = (value) => {
16
- if (Array.isArray(value)) {
17
- return value.map(v => convertAddressesToEvmFormat(v));
18
- }
19
- if (typeof value === 'string' && value.startsWith('T') && tronweb_1.TronWeb.isAddress(value)) {
20
- const hex = tronweb_1.TronWeb.address.toHex(value);
21
- return hex.replace(/^41/, '0x');
22
- }
23
- return value;
24
- };
25
16
  exports.sunioApi = {
26
17
  getTradeQuote: async (input, deps) => {
27
18
  const maybeTradeQuote = await (0, getSunioTradeQuote_1.getSunioTradeQuote)(input, deps);
@@ -32,7 +23,7 @@ exports.sunioApi = {
32
23
  return maybeTradeRate.map(rate => [rate]);
33
24
  },
34
25
  getUnsignedTronTransaction: async (args) => {
35
- const { tradeQuote, stepIndex, from, slippageTolerancePercentageDecimal, assertGetTronChainAdapter, } = args;
26
+ const { tradeQuote, stepIndex, from, slippageTolerancePercentageDecimal, assertGetTronChainAdapter, config, } = args;
36
27
  if (!(0, utils_1.isExecutableTradeQuote)(tradeQuote)) {
37
28
  throw new Error('Unable to execute a trade rate quote');
38
29
  }
@@ -45,24 +36,12 @@ exports.sunioApi = {
45
36
  const rpcUrl = adapter.httpProvider.getRpcUrl();
46
37
  const tronWeb = new tronweb_1.TronWeb({
47
38
  fullHost: rpcUrl,
39
+ headers: config.VITE_TRON_GRID_API_KEY
40
+ ? { 'TRON-PRO-API-KEY': config.VITE_TRON_GRID_API_KEY }
41
+ : {},
48
42
  });
49
43
  const routeParams = (0, buildSwapRouteParameters_1.buildSwapRouteParameters)(sunioMetadata.route, step.sellAmountIncludingProtocolFeesCryptoBaseUnit, step.buyAmountAfterFeesCryptoBaseUnit, tradeQuote.receiveAddress, slippageTolerancePercentageDecimal);
50
- const parameters = [
51
- { type: 'address[]', value: routeParams.path },
52
- { type: 'string[]', value: routeParams.poolVersion },
53
- { type: 'uint256[]', value: routeParams.versionLen },
54
- { type: 'uint24[]', value: routeParams.fees },
55
- {
56
- type: 'tuple(uint256,uint256,address,uint256)',
57
- value: convertAddressesToEvmFormat([
58
- routeParams.swapData.amountIn,
59
- routeParams.swapData.amountOutMin,
60
- routeParams.swapData.recipient,
61
- routeParams.swapData.deadline,
62
- ]),
63
- },
64
- ];
65
- const functionSelector = 'swapExactInput(address[],string[],uint256[],uint24[],(uint256,uint256,address,uint256))';
44
+ const parameters = (0, buildSwapContractCall_1.buildSwapExactInputParameters)(routeParams);
66
45
  const isSellingNativeTrx = step.sellAsset.assetId === caip_1.tronAssetId;
67
46
  const callValue = isSellingNativeTrx
68
47
  ? Number(step.sellAmountIncludingProtocolFeesCryptoBaseUnit)
@@ -71,7 +50,7 @@ exports.sunioApi = {
71
50
  feeLimit: 100_000_000,
72
51
  callValue,
73
52
  };
74
- const txData = await tronWeb.transactionBuilder.triggerSmartContract(constants_1.SUNIO_SMART_ROUTER_CONTRACT, functionSelector, options, parameters, from);
53
+ const txData = await tronWeb.transactionBuilder.triggerSmartContract(constants_1.SUNIO_SMART_ROUTER_CONTRACT, buildSwapContractCall_1.SUNIO_SWAP_EXACT_INPUT_SELECTOR, options, parameters, from);
75
54
  if (!txData.result || !txData.result.result) {
76
55
  throw new Error('[Sun.io] Failed to build swap transaction');
77
56
  }
@@ -100,7 +79,7 @@ exports.sunioApi = {
100
79
  transaction,
101
80
  };
102
81
  },
103
- getTronTransactionFees: getTronTransactionFees_1.getTronTransactionFees,
82
+ getTronTransactionFees: getSunioTransactionFees_1.getSunioTransactionFees,
104
83
  checkTradeStatus: async ({ txHash, assertGetTronChainAdapter }) => {
105
84
  try {
106
85
  // Wait for TronGrid indexing to avoid false "REVERT"
@@ -111,12 +90,16 @@ exports.sunioApi = {
111
90
  return (0, utils_1.createDefaultStatusResponse)(txHash);
112
91
  }
113
92
  const contractRet = tx.ret?.[0]?.contractRet;
114
- // Only mark as confirmed if SUCCESS AND has confirmations (in a block)
115
- const status = contractRet === 'SUCCESS' && tx.confirmations > 0
116
- ? unchained_client_1.TxStatus.Confirmed
117
- : contractRet === 'REVERT'
118
- ? unchained_client_1.TxStatus.Failed
119
- : unchained_client_1.TxStatus.Pending;
93
+ // Tron reports many failure codes (REVERT, OUT_OF_ENERGY, OUT_OF_TIME, ...). A missing
94
+ // contractRet means it isn't mined yet; any non-SUCCESS value is a terminal failure.
95
+ const status = (() => {
96
+ if (!contractRet)
97
+ return unchained_client_1.TxStatus.Pending;
98
+ if (contractRet === 'SUCCESS') {
99
+ return tx.confirmations > 0 ? unchained_client_1.TxStatus.Confirmed : unchained_client_1.TxStatus.Pending;
100
+ }
101
+ return unchained_client_1.TxStatus.Failed;
102
+ })();
120
103
  return {
121
104
  status,
122
105
  buyTxHash: txHash,
@@ -0,0 +1,6 @@
1
+ import type { SwapRouteParameters } from './buildSwapRouteParameters';
2
+ export declare const SUNIO_SWAP_EXACT_INPUT_SELECTOR = "swapExactInput(address[],string[],uint256[],uint24[],(uint256,uint256,address,uint256))";
3
+ export declare const buildSwapExactInputParameters: (routeParams: SwapRouteParameters) => {
4
+ type: string;
5
+ value: unknown;
6
+ }[];
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildSwapExactInputParameters = exports.SUNIO_SWAP_EXACT_INPUT_SELECTOR = void 0;
4
+ const tronweb_1 = require("tronweb");
5
+ exports.SUNIO_SWAP_EXACT_INPUT_SELECTOR = 'swapExactInput(address[],string[],uint256[],uint24[],(uint256,uint256,address,uint256))';
6
+ const convertAddressesToEvmFormat = (value) => {
7
+ if (Array.isArray(value)) {
8
+ return value.map(v => convertAddressesToEvmFormat(v));
9
+ }
10
+ if (typeof value === 'string' && value.startsWith('T') && tronweb_1.TronWeb.isAddress(value)) {
11
+ const hex = tronweb_1.TronWeb.address.toHex(value);
12
+ return hex.replace(/^41/, '0x');
13
+ }
14
+ return value;
15
+ };
16
+ // Parameter list for the SmartExchangeRouter swapExactInput call, shared between fee
17
+ // estimation and execution so both encode the call identically.
18
+ const buildSwapExactInputParameters = (routeParams) => [
19
+ { type: 'address[]', value: routeParams.path },
20
+ { type: 'string[]', value: routeParams.poolVersion },
21
+ { type: 'uint256[]', value: routeParams.versionLen },
22
+ { type: 'uint24[]', value: routeParams.fees },
23
+ {
24
+ type: 'tuple(uint256,uint256,address,uint256)',
25
+ value: convertAddressesToEvmFormat([
26
+ routeParams.swapData.amountIn,
27
+ routeParams.swapData.amountOutMin,
28
+ routeParams.swapData.recipient,
29
+ routeParams.swapData.deadline,
30
+ ]),
31
+ },
32
+ ];
33
+ exports.buildSwapExactInputParameters = buildSwapExactInputParameters;
@@ -5,12 +5,12 @@ const utils_1 = require("@shapeshiftoss/utils");
5
5
  const buildSwapRouteParameters = (route, sellAmountCryptoBaseUnit, minBuyAmountCryptoBaseUnit, recipient, slippageTolerancePercentageDecimal) => {
6
6
  const path = route.tokens;
7
7
  const poolVersion = route.poolVersions;
8
- const versionLen = poolVersion.map((_, index) => {
9
- if (index === poolVersion.length - 1) {
10
- return path.length - index;
11
- }
12
- return 2;
13
- });
8
+ // The SmartExchangeRouter expects sum(versionLen) === path.length: the first
9
+ // pool segment consumes 2 tokens (input + output) and each subsequent pool
10
+ // reuses the previous output, consuming 1 new token. This relies on the Sun.io
11
+ // API returning poolVersions per-hop (poolVersions.length === tokens.length - 1),
12
+ // which it does — the router also accepts this un-collapsed form for same-version hops.
13
+ const versionLen = poolVersion.map((_, index) => (index === 0 ? 2 : 1));
14
14
  const fees = route.poolFees.map(fee => Number(fee));
15
15
  const amountOutWithSlippage = (0, utils_1.bn)(minBuyAmountCryptoBaseUnit)
16
16
  .times((0, utils_1.bn)(1).minus(slippageTolerancePercentageDecimal))
@@ -2,5 +2,7 @@ export declare const SUNIO_SUPPORTED_CHAIN_IDS: readonly [import("@shapeshiftoss
2
2
  export declare const SUNIO_API_BASE_URL = "https://rot.endjgfsv.link";
3
3
  export declare const SUNIO_SMART_ROUTER_CONTRACT: "TCFNp179Lg46D16zKoumd4Poa2WFFdtqYj";
4
4
  export declare const DEFAULT_SLIPPAGE_PERCENTAGE = "0.005";
5
+ export declare const SUNIO_FALLBACK_SWAP_ENERGY_NATIVE = 215000;
6
+ export declare const SUNIO_FALLBACK_SWAP_ENERGY_TRC20 = 375000;
5
7
  export declare const SUNIO_DEX_TYPES: "PSM,CURVE,CURVE_COMBINATION,WTRX,SUNSWAP_V1,SUNSWAP_V2,SUNSWAP_V3";
6
8
  export declare const SUNIO_TRON_NATIVE_ADDRESS: "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb";
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SUNIO_TRON_NATIVE_ADDRESS = exports.SUNIO_DEX_TYPES = exports.DEFAULT_SLIPPAGE_PERCENTAGE = exports.SUNIO_SMART_ROUTER_CONTRACT = exports.SUNIO_API_BASE_URL = exports.SUNIO_SUPPORTED_CHAIN_IDS = void 0;
3
+ exports.SUNIO_TRON_NATIVE_ADDRESS = exports.SUNIO_DEX_TYPES = exports.SUNIO_FALLBACK_SWAP_ENERGY_TRC20 = exports.SUNIO_FALLBACK_SWAP_ENERGY_NATIVE = exports.DEFAULT_SLIPPAGE_PERCENTAGE = exports.SUNIO_SMART_ROUTER_CONTRACT = exports.SUNIO_API_BASE_URL = exports.SUNIO_SUPPORTED_CHAIN_IDS = void 0;
4
4
  const caip_1 = require("@shapeshiftoss/caip");
5
5
  exports.SUNIO_SUPPORTED_CHAIN_IDS = [caip_1.tronChainId];
6
6
  // NOTE: This domain looks suspicious, but it's the official Sun.io backend API
@@ -11,6 +11,12 @@ exports.SUNIO_API_BASE_URL = 'https://rot.endjgfsv.link';
11
11
  // This is the current mainnet router that sun.io's frontend uses
12
12
  exports.SUNIO_SMART_ROUTER_CONTRACT = 'TCFNp179Lg46D16zKoumd4Poa2WFFdtqYj';
13
13
  exports.DEFAULT_SLIPPAGE_PERCENTAGE = '0.005';
14
+ // Energy fallbacks for when we can't simulate a swap (no address, or the simulation reverts
15
+ // pre-approval for TRC20 sells). Set to observed average energy so the 1.2x margin applied at
16
+ // estimate time lifts them to cover the worst case (native ~245k, TRC20 ~415k due to the extra
17
+ // transferFrom token pull) without double-counting safety.
18
+ exports.SUNIO_FALLBACK_SWAP_ENERGY_NATIVE = 215_000;
19
+ exports.SUNIO_FALLBACK_SWAP_ENERGY_TRC20 = 375_000;
14
20
  exports.SUNIO_DEX_TYPES = 'PSM,CURVE,CURVE_COMBINATION,WTRX,SUNSWAP_V1,SUNSWAP_V2,SUNSWAP_V3';
15
21
  // Native TRX token address (used when assetId is not a TRC-20 token)
16
22
  exports.SUNIO_TRON_NATIVE_ADDRESS = 'T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb';
@@ -0,0 +1,12 @@
1
+ import type { SunioRoute } from '../types';
2
+ type EstimateSunioNetworkFeeArgs = {
3
+ rpcUrl: string;
4
+ apiKey: string;
5
+ route: SunioRoute;
6
+ sellAmountCryptoBaseUnit: string;
7
+ isSellingNativeTrx: boolean;
8
+ address: string | undefined;
9
+ slippageTolerancePercentageDecimal: string | undefined;
10
+ };
11
+ export declare const estimateSunioNetworkFeeCryptoBaseUnit: ({ rpcUrl, apiKey, route, sellAmountCryptoBaseUnit, isSellingNativeTrx, address, slippageTolerancePercentageDecimal, }: EstimateSunioNetworkFeeArgs) => Promise<string>;
12
+ export {};
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.estimateSunioNetworkFeeCryptoBaseUnit = void 0;
4
+ const utils_1 = require("@shapeshiftoss/utils");
5
+ const tronweb_1 = require("tronweb");
6
+ const buildSwapContractCall_1 = require("./buildSwapContractCall");
7
+ const buildSwapRouteParameters_1 = require("./buildSwapRouteParameters");
8
+ const constants_1 = require("./constants");
9
+ // Estimates the network fee (in TRX base units) for a Sun.io swap. The router sponsors only ~1%
10
+ // of energy (origin_energy_usage); the user pays the rest, so we simulate the real swapExactInput
11
+ // call when we have an address to estimate from. The simulation reverts before approval for TRC20
12
+ // sells (and when the account lacks the sell balance), so we fall back to a conservative per-sell-
13
+ // type constant. Used both at quote time and re-run at confirm time, where a now-granted allowance
14
+ // lets the simulation produce the true cost.
15
+ const estimateSunioNetworkFeeCryptoBaseUnit = async ({ rpcUrl, apiKey, route, sellAmountCryptoBaseUnit, isSellingNativeTrx, address, slippageTolerancePercentageDecimal, }) => {
16
+ const tronGridHeaders = apiKey ? { 'TRON-PRO-API-KEY': apiKey } : {};
17
+ const tronWeb = new tronweb_1.TronWeb({ fullHost: rpcUrl, headers: tronGridHeaders });
18
+ // Live network prices, defaulting if the node is unavailable so we still produce a fee
19
+ const { bandwidthPrice, energyPrice } = await (async () => {
20
+ try {
21
+ const params = await tronWeb.trx.getChainParameters();
22
+ return {
23
+ bandwidthPrice: params.find(p => p.key === 'getTransactionFee')?.value ?? 1000,
24
+ energyPrice: params.find(p => p.key === 'getEnergyFee')?.value ?? 100,
25
+ };
26
+ }
27
+ catch {
28
+ return { bandwidthPrice: 1000, energyPrice: 100 };
29
+ }
30
+ })();
31
+ // Account activation (1 TRX) is only charged when the recipient receives native TRX, mirroring
32
+ // the chain adapter. A TRC20 buy doesn't incur the flat activation fee (its account-creation
33
+ // cost is folded into energy). Only checkable with an address.
34
+ const isBuyingNativeTrx = route.tokens[route.tokens.length - 1] === constants_1.SUNIO_TRON_NATIVE_ADDRESS;
35
+ const accountActivationFee = await (async () => {
36
+ if (!address || !isBuyingNativeTrx)
37
+ return 0;
38
+ try {
39
+ const recipientInfoResponse = await fetch(`${rpcUrl}/wallet/getaccount`, {
40
+ method: 'POST',
41
+ headers: { 'Content-Type': 'application/json', ...tronGridHeaders },
42
+ body: JSON.stringify({ address, visible: true }),
43
+ });
44
+ const recipientInfo = await recipientInfoResponse.json();
45
+ const recipientExists = recipientInfo && Object.keys(recipientInfo).length > 1;
46
+ return recipientExists ? 0 : 1_000_000; // 1 TRX
47
+ }
48
+ catch {
49
+ return 0;
50
+ }
51
+ })();
52
+ const energyUsed = await (async () => {
53
+ // TRC20 sells cost far more energy than native sells (the extra transferFrom token pull)
54
+ const fallbackEnergy = isSellingNativeTrx
55
+ ? constants_1.SUNIO_FALLBACK_SWAP_ENERGY_NATIVE
56
+ : constants_1.SUNIO_FALLBACK_SWAP_ENERGY_TRC20;
57
+ if (!address)
58
+ return fallbackEnergy;
59
+ try {
60
+ const routeParams = (0, buildSwapRouteParameters_1.buildSwapRouteParameters)(route, sellAmountCryptoBaseUnit, '0', address, slippageTolerancePercentageDecimal ?? constants_1.DEFAULT_SLIPPAGE_PERCENTAGE);
61
+ const callValue = isSellingNativeTrx ? Number(sellAmountCryptoBaseUnit) : 0;
62
+ const result = await tronWeb.transactionBuilder.triggerConstantContract(constants_1.SUNIO_SMART_ROUTER_CONTRACT, buildSwapContractCall_1.SUNIO_SWAP_EXACT_INPUT_SELECTOR, { callValue }, (0, buildSwapContractCall_1.buildSwapExactInputParameters)(routeParams), address);
63
+ // A reverted simulation (e.g. TRC20 sell pre-approval) can still return a small energy_used;
64
+ // only trust it when the call actually succeeded, otherwise use the conservative fallback.
65
+ if (result?.result?.result !== true || result.energy_used == null)
66
+ return fallbackEnergy;
67
+ return result.energy_used;
68
+ }
69
+ catch {
70
+ return fallbackEnergy;
71
+ }
72
+ })();
73
+ // 1.2x safety margin for energy price/usage variance between estimate and execution
74
+ const energyFee = Math.ceil(energyUsed * energyPrice * 1.2);
75
+ const bandwidthFee = 1100 * bandwidthPrice;
76
+ return (0, utils_1.bn)(energyFee).plus(bandwidthFee).plus(accountActivationFee).toFixed(0);
77
+ };
78
+ exports.estimateSunioNetworkFeeCryptoBaseUnit = estimateSunioNetworkFeeCryptoBaseUnit;
@@ -4,11 +4,11 @@ exports.getQuoteOrRate = void 0;
4
4
  const caip_1 = require("@shapeshiftoss/caip");
5
5
  const utils_1 = require("@shapeshiftoss/utils");
6
6
  const monads_1 = require("@sniptt/monads");
7
- const tronweb_1 = require("tronweb");
8
7
  const types_1 = require("../../../types");
9
8
  const utils_2 = require("../../../utils");
10
9
  const affiliateFee_1 = require("../../utils/affiliateFee");
11
10
  const constants_1 = require("./constants");
11
+ const estimateSunioNetworkFee_1 = require("./estimateSunioNetworkFee");
12
12
  const fetchFromSunio_1 = require("./fetchFromSunio");
13
13
  const helpers_1 = require("./helpers/helpers");
14
14
  const sunioService_1 = require("./sunioService");
@@ -60,83 +60,25 @@ async function getQuoteOrRate(input, deps) {
60
60
  code: types_1.TradeQuoteError.InternalError,
61
61
  }));
62
62
  }
63
- // Fetch network fees for both quotes and rates (when wallet connected)
64
- let networkFeeCryptoBaseUnit = undefined;
65
- // Estimate fees when we have an address to estimate from
66
- if (receiveAddress) {
63
+ const networkFeeCryptoBaseUnit = await (async () => {
67
64
  try {
68
- const contractAddress = (0, utils_1.contractAddressOrUndefined)(sellAsset.assetId);
69
- const isSellingNativeTrx = !contractAddress;
70
- const tronWeb = new tronweb_1.TronWeb({ fullHost: deps.config.VITE_TRON_NODE_URL });
71
- // Get chain parameters for pricing
72
- const params = await tronWeb.trx.getChainParameters();
73
- const bandwidthPrice = params.find(p => p.key === 'getTransactionFee')?.value ?? 1000;
74
- const energyPrice = params.find(p => p.key === 'getEnergyFee')?.value ?? 100;
75
- // Check if recipient needs activation (applies to all swaps)
76
- let accountActivationFee = 0;
77
- try {
78
- const recipientInfoResponse = await fetch(`${deps.config.VITE_TRON_NODE_URL}/wallet/getaccount`, {
79
- method: 'POST',
80
- headers: { 'Content-Type': 'application/json' },
81
- body: JSON.stringify({ address: receiveAddress, visible: true }),
82
- });
83
- const recipientInfo = await recipientInfoResponse.json();
84
- const recipientExists = recipientInfo && Object.keys(recipientInfo).length > 1;
85
- if (!recipientExists) {
86
- accountActivationFee = 1_000_000; // 1 TRX
87
- }
88
- }
89
- catch {
90
- // Ignore activation check errors
91
- }
92
- // For native TRX swaps, Sun.io uses a contract call with value
93
- // We need to estimate energy for the swap contract, not just bandwidth
94
- if (isSellingNativeTrx) {
95
- try {
96
- // Sun.io contract owner provides most energy (~117k), users only pay ~2k
97
- // Use fixed 2k energy estimate instead of querying (which returns total 120k)
98
- const energyUsed = 2000; // User pays ~2k energy, contract covers the rest
99
- const energyFee = energyUsed * energyPrice; // No multiplier - contract provides energy
100
- // Estimate bandwidth for contract call (much larger than simple transfer)
101
- const bandwidthFee = 1100 * bandwidthPrice; // ~1100 bytes for contract call (with safety buffer)
102
- networkFeeCryptoBaseUnit = (0, utils_1.bn)(energyFee)
103
- .plus(bandwidthFee)
104
- .plus(accountActivationFee)
105
- .toFixed(0);
106
- }
107
- catch (estimationError) {
108
- // Fallback estimate: ~2k energy + ~1100 bytes bandwidth + activation fee
109
- const fallbackEnergyFee = 2000 * energyPrice;
110
- const fallbackBandwidthFee = 1100 * bandwidthPrice;
111
- networkFeeCryptoBaseUnit = (0, utils_1.bn)(fallbackEnergyFee)
112
- .plus(fallbackBandwidthFee)
113
- .plus(accountActivationFee)
114
- .toFixed(0);
115
- }
116
- }
117
- else {
118
- // For TRC-20 swaps through Sun.io router
119
- // Same as TRX: contract owner provides most energy, user pays ~2k
120
- // Sun.io provides ~217k energy, user pays ~2k
121
- const energyFee = 2000 * energyPrice;
122
- const bandwidthFee = 1100 * bandwidthPrice;
123
- networkFeeCryptoBaseUnit = (0, utils_1.bn)(energyFee)
124
- .plus(bandwidthFee)
125
- .plus(accountActivationFee)
126
- .toFixed(0);
127
- }
65
+ return await (0, estimateSunioNetworkFee_1.estimateSunioNetworkFeeCryptoBaseUnit)({
66
+ rpcUrl: deps.config.VITE_TRON_NODE_URL,
67
+ apiKey: deps.config.VITE_TRON_GRID_API_KEY,
68
+ route: bestRoute,
69
+ sellAmountCryptoBaseUnit: sellAmountIncludingProtocolFeesCryptoBaseUnit,
70
+ isSellingNativeTrx: !(0, utils_1.contractAddressOrUndefined)(sellAsset.assetId),
71
+ address: receiveAddress,
72
+ slippageTolerancePercentageDecimal,
73
+ });
128
74
  }
129
75
  catch (error) {
130
- // For rates, fall back to '0' on estimation failure
131
- // For quotes, let it error (required for accurate swap)
132
- if (!isQuote) {
133
- networkFeeCryptoBaseUnit = '0';
134
- }
135
- else {
136
- throw error;
137
- }
76
+ // For rates, fall back to '0' on unexpected failure; quotes require an accurate fee
77
+ if (!isQuote)
78
+ return '0';
79
+ throw error;
138
80
  }
139
- }
81
+ })();
140
82
  const buyAmountCryptoBaseUnit = utils_1.BigAmount.fromPrecision({
141
83
  value: bestRoute.amountOut,
142
84
  precision: buyAsset.precision,
@@ -0,0 +1,2 @@
1
+ import type { GetUnsignedTronTransactionArgs } from '../../../types';
2
+ export declare const getSunioTransactionFees: ({ tradeQuote, stepIndex, from, slippageTolerancePercentageDecimal, assertGetTronChainAdapter, config, }: GetUnsignedTronTransactionArgs) => Promise<string>;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getSunioTransactionFees = void 0;
4
+ const caip_1 = require("@shapeshiftoss/caip");
5
+ const utils_1 = require("../../../utils");
6
+ const estimateSunioNetworkFee_1 = require("./estimateSunioNetworkFee");
7
+ const getSunioTransactionFees = async ({ tradeQuote, stepIndex, from, slippageTolerancePercentageDecimal, assertGetTronChainAdapter, config, }) => {
8
+ if (!(0, utils_1.isExecutableTradeQuote)(tradeQuote))
9
+ throw new Error('Unable to execute a trade rate quote');
10
+ const step = (0, utils_1.getExecutableTradeStep)(tradeQuote, stepIndex);
11
+ const storedNetworkFeeCryptoBaseUnit = step.feeData.networkFeeCryptoBaseUnit;
12
+ const route = step.sunioTransactionMetadata?.route;
13
+ if (!route) {
14
+ if (!storedNetworkFeeCryptoBaseUnit)
15
+ throw new Error('Missing network fee in quote');
16
+ return storedNetworkFeeCryptoBaseUnit;
17
+ }
18
+ try {
19
+ const adapter = assertGetTronChainAdapter(caip_1.tronChainId);
20
+ return await (0, estimateSunioNetworkFee_1.estimateSunioNetworkFeeCryptoBaseUnit)({
21
+ rpcUrl: adapter.httpProvider.getRpcUrl(),
22
+ apiKey: config.VITE_TRON_GRID_API_KEY,
23
+ route,
24
+ sellAmountCryptoBaseUnit: step.sellAmountIncludingProtocolFeesCryptoBaseUnit,
25
+ isSellingNativeTrx: step.sellAsset.assetId === caip_1.tronAssetId,
26
+ address: from,
27
+ slippageTolerancePercentageDecimal,
28
+ });
29
+ }
30
+ catch {
31
+ if (!storedNetworkFeeCryptoBaseUnit)
32
+ throw new Error('Missing network fee in quote');
33
+ return storedNetworkFeeCryptoBaseUnit;
34
+ }
35
+ };
36
+ exports.getSunioTransactionFees = getSunioTransactionFees;
@@ -49,6 +49,7 @@ const DAO_TREASURY_BY_CHAIN_ID = {
49
49
  [types_1.KnownChainIds.TonMainnet]: utils_1.DAO_TREASURY_TON,
50
50
  [types_1.KnownChainIds.MonadMainnet]: utils_1.DAO_TREASURY_MONAD,
51
51
  [types_1.KnownChainIds.HyperEvmMainnet]: utils_1.DAO_TREASURY_HYPEREVM,
52
+ [types_1.KnownChainIds.BobMainnet]: utils_1.DAO_TREASURY_BOB,
52
53
  };
53
54
  const getTreasuryAddressFromChainId = (chainId) => {
54
55
  const maybeTreasuryChainId = (0, utils_1.isTreasuryChainId)(chainId) ? chainId : undefined;
@@ -130,7 +130,7 @@ const getL1RateOrQuote = async (input, deps, streamingInterval, tradeType, swapp
130
130
  const protocolFees = {};
131
131
  if (!buyAssetTradeFeeBuyAssetCryptoBaseUnit.isZero()) {
132
132
  protocolFees[buyAsset.assetId] = {
133
- amountCryptoBaseUnit: buyAssetTradeFeeBuyAssetCryptoBaseUnit.toString(),
133
+ amountCryptoBaseUnit: buyAssetTradeFeeBuyAssetCryptoBaseUnit.toFixed(0),
134
134
  requiresBalance: false,
135
135
  asset: buyAsset,
136
136
  };
@@ -161,7 +161,7 @@ const getL1RateOrQuote = async (input, deps, streamingInterval, tradeType, swapp
161
161
  value: route.expectedAmountOutThorBaseUnit,
162
162
  inputExponent: buyAssetNativePrecision,
163
163
  outputExponent: buyAsset.precision,
164
- }).toFixed();
164
+ }).toFixed(0);
165
165
  const rate = (0, utils_2.getInputOutputRate)({
166
166
  sellAmountCryptoBaseUnit,
167
167
  buyAmountCryptoBaseUnit: buyAmountAfterFeesCryptoBaseUnit,
@@ -401,6 +401,9 @@ const getL1RateOrQuote = async (input, deps, streamingInterval, tradeType, swapp
401
401
  // Estimate fees using the receive address for accurate energy calculation
402
402
  const tronWeb = new tronweb_1.TronWeb({
403
403
  fullHost: deps.config.VITE_TRON_NODE_URL,
404
+ headers: deps.config.VITE_TRON_GRID_API_KEY
405
+ ? { 'TRON-PRO-API-KEY': deps.config.VITE_TRON_GRID_API_KEY }
406
+ : {},
404
407
  });
405
408
  const params = await tronWeb.trx.getChainParameters();
406
409
  const bandwidthPrice = params.find(p => p.key === 'getTransactionFee')?.value ?? 1000;
@@ -10,19 +10,10 @@ const monads_1 = require("@sniptt/monads");
10
10
  const qs_1 = __importDefault(require("qs"));
11
11
  const types_1 = require("../types");
12
12
  const utils_2 = require("../utils");
13
- const getThresholdedAffiliateBps_1 = require("./getThresholdedAffiliateBps/getThresholdedAffiliateBps");
14
13
  const index_1 = require("./index");
15
14
  const service_1 = require("./service");
16
15
  const getQuote = async (input, deps) => {
17
16
  const { buyAssetId, receiveAddress, sellAsset, sellAmountCryptoBaseUnit, streaming, streamingInterval, affiliateBps, swapperName, } = input;
18
- // don't apply an affiliate fee if it's below the outbound fee for the inbound pool
19
- const thresholdedAffiliateBps = await (0, getThresholdedAffiliateBps_1.getThresholdedAffiliateBps)({
20
- sellAsset,
21
- sellAmountCryptoBaseUnit,
22
- affiliateBps,
23
- config: deps.config,
24
- swapperName,
25
- });
26
17
  const buyPoolId = (0, index_1.getPoolAssetId)({ assetId: buyAssetId, swapperName });
27
18
  const sellPoolId = (0, index_1.getPoolAssetId)({ assetId: sellAsset.assetId, swapperName });
28
19
  const sellAmountCryptoPrecision = utils_1.BigAmount.fromBaseUnit({
@@ -43,34 +34,41 @@ const getQuote = async (input, deps) => {
43
34
  from_asset: sellPoolId,
44
35
  to_asset: buyPoolId,
45
36
  destination: parsedReceiveAddress,
46
- affiliate_bps: thresholdedAffiliateBps,
37
+ affiliate_bps: affiliateBps,
47
38
  affiliate: (0, index_1.getAffiliate)(swapperName),
48
39
  ...(streaming && { streaming_interval: streamingInterval }),
49
40
  });
50
41
  const daemonUrl = (0, index_1.getDaemonUrl)(deps.config, swapperName);
51
42
  const res = await service_1.thorService.get(`${daemonUrl}/quote/swap?${queryString}`);
52
- if (res.isErr())
53
- return (0, monads_1.Err)(res.unwrapErr());
54
- const { data } = res.unwrap();
55
- const isError = 'error' in data;
56
- const notEnoughFeeError = isError && /not enough fee/i.test(data.error);
57
- const notEnoughToPayTxFeeError = isError && /not enough to pay transaction fee/i.test(data.error);
58
- const tradingIsHaltedError = isError && /trading is halted/.test(data.error);
59
- if (notEnoughFeeError || notEnoughToPayTxFeeError)
60
- return (0, monads_1.Err)((0, utils_2.createTradeAmountTooSmallErr)());
61
- if (tradingIsHaltedError) {
62
- return (0, monads_1.Err)((0, utils_2.makeSwapErrorRight)({
63
- message: `[getQuote]: Trading is halted, cannot process swap`,
64
- code: types_1.TradeQuoteError.TradingHalted,
65
- details: { sellAssetId: sellAsset.assetId, buyAssetId },
66
- }));
67
- }
68
- if (isError) {
43
+ // Thornode returns errors as `{ error: string }` in both the 2xx body and the 4xx body.
44
+ // On 4xx axios rejects, so the body lands on `cause.response.data` instead of in the success data.
45
+ const errorMessage = (() => {
46
+ if (res.isErr()) {
47
+ const cause = res.unwrapErr().cause;
48
+ return cause?.response?.data?.error;
49
+ }
50
+ const { data } = res.unwrap();
51
+ return 'error' in data ? data.error : undefined;
52
+ })();
53
+ if (errorMessage) {
54
+ if (/not enough fee/i.test(errorMessage) ||
55
+ /not enough to pay transaction fee/i.test(errorMessage)) {
56
+ return (0, monads_1.Err)((0, utils_2.createTradeAmountTooSmallErr)());
57
+ }
58
+ if (/trading is halted/i.test(errorMessage)) {
59
+ return (0, monads_1.Err)((0, utils_2.makeSwapErrorRight)({
60
+ message: `[getQuote]: Trading is halted, cannot process swap`,
61
+ code: types_1.TradeQuoteError.TradingHalted,
62
+ details: { sellAssetId: sellAsset.assetId, buyAssetId },
63
+ }));
64
+ }
69
65
  return (0, monads_1.Err)((0, utils_2.makeSwapErrorRight)({
70
- message: data.error,
66
+ message: errorMessage,
71
67
  code: types_1.TradeQuoteError.UnknownError,
72
68
  }));
73
69
  }
74
- return (0, monads_1.Ok)(data);
70
+ if (res.isErr())
71
+ return (0, monads_1.Err)(res.unwrapErr());
72
+ return (0, monads_1.Ok)(res.unwrap().data);
75
73
  };
76
74
  exports.getQuote = getQuote;
@@ -5,9 +5,9 @@ const utils_1 = require("@shapeshiftoss/utils");
5
5
  const tronweb_1 = require("tronweb");
6
6
  const utils_2 = require("../../utils");
7
7
  const getThorTxData_1 = require("./getThorTxData");
8
- const getChainPrices = async (rpcUrl) => {
8
+ const getChainPrices = async (rpcUrl, headers) => {
9
9
  try {
10
- const tronWeb = new tronweb_1.TronWeb({ fullHost: rpcUrl });
10
+ const tronWeb = new tronweb_1.TronWeb({ fullHost: rpcUrl, headers });
11
11
  const params = await tronWeb.trx.getChainParameters();
12
12
  const bandwidthPrice = params.find(p => p.key === 'getTransactionFee')?.value ?? 1000;
13
13
  const energyPrice = params.find(p => p.key === 'getEnergyFee')?.value ?? 420;
@@ -29,11 +29,14 @@ const getTronTransactionFees = async (args, swapperName) => {
29
29
  const { vault } = await (0, getThorTxData_1.getThorTxData)({ sellAsset, config, swapperName });
30
30
  const contractAddress = (0, utils_1.contractAddressOrUndefined)(sellAsset.assetId);
31
31
  const rpcUrl = config.VITE_TRON_NODE_URL;
32
+ const tronGridHeaders = config.VITE_TRON_GRID_API_KEY
33
+ ? { 'TRON-PRO-API-KEY': config.VITE_TRON_GRID_API_KEY }
34
+ : {};
32
35
  try {
33
- const tronWeb = new tronweb_1.TronWeb({ fullHost: rpcUrl });
36
+ const tronWeb = new tronweb_1.TronWeb({ fullHost: rpcUrl, headers: tronGridHeaders });
34
37
  if (contractAddress) {
35
38
  // TRC20 transfer - estimate energy cost
36
- const { energyPrice } = await getChainPrices(rpcUrl);
39
+ const { energyPrice } = await getChainPrices(rpcUrl, tronGridHeaders);
37
40
  const result = await tronWeb.transactionBuilder.triggerConstantContract(contractAddress, 'transfer(address,uint256)', {}, [
38
41
  { type: 'address', value: vault },
39
42
  { type: 'uint256', value: sellAmountIncludingProtocolFeesCryptoBaseUnit },
@@ -44,7 +47,7 @@ const getTronTransactionFees = async (args, swapperName) => {
44
47
  }
45
48
  else {
46
49
  // TRX transfer with memo - build transaction to get accurate size
47
- const { bandwidthPrice } = await getChainPrices(rpcUrl);
50
+ const { bandwidthPrice } = await getChainPrices(rpcUrl, tronGridHeaders);
48
51
  let tx = await tronWeb.transactionBuilder.sendTrx(vault, (0, utils_1.bnOrZero)(sellAmountIncludingProtocolFeesCryptoBaseUnit).toNumber(), from);
49
52
  // Add memo to get accurate size with memo overhead
50
53
  const txWithMemo = await tronWeb.transactionBuilder.addUpdateData(tx, memo, 'utf8');
@@ -71,7 +71,7 @@ export type ThornodeQuoteResponseSuccess = {
71
71
  total_swap_seconds?: number;
72
72
  warning: string;
73
73
  };
74
- type ThornodeResponseError = {
74
+ export type ThornodeResponseError = {
75
75
  error: string;
76
76
  };
77
77
  export type ThornodeQuoteResponse = ThornodeQuoteResponseSuccess | ThornodeResponseError;