@imtbl/sdk 0.35.0 → 0.35.2

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/checkout.js CHANGED
@@ -14673,7 +14673,6 @@ class UniswapV3Pool__factory extends ContractFactory {
14673
14673
  }
14674
14674
  }
14675
14675
 
14676
- const DEFAULT_GAS_QUOTE = 2000000;
14677
14676
  // TODO: Better description of function and args
14678
14677
  async function multicallSingleCallDataMultipleContracts(multicallContract, functionName, addresses) {
14679
14678
  // Encode args - generate calldata for contract
@@ -14695,22 +14694,6 @@ async function multicallSingleCallDataMultipleContracts(multicallContract, funct
14695
14694
  }
14696
14695
  return multicallContract.callStatic.multicall(calls);
14697
14696
  }
14698
- // TODO: Better description of function and args
14699
- async function multicallMultipleCallDataSingContract(multicallContract, calldata, address, options) {
14700
- // Create call objects
14701
- const calls = new Array(calldata.length);
14702
- // TODO: use object.keys of something similar to avoid iterating over
14703
- // entire object prototype
14704
- // eslint-disable-next-line no-restricted-syntax, guard-for-in
14705
- for (const i in calldata) {
14706
- calls[i] = {
14707
- target: address,
14708
- callData: calldata[i],
14709
- gasLimit: options?.gasRequired ?? DEFAULT_GAS_QUOTE,
14710
- };
14711
- }
14712
- return multicallContract.callStatic.multicall(calls);
14713
- }
14714
14697
  const getCallData = (methodName, contractInterface) => {
14715
14698
  // Create ethers function fragment
14716
14699
  const fragment = contractInterface?.getFunction(methodName);
@@ -14870,35 +14853,27 @@ const getDefaultDeadlineSeconds = () => Math.floor(Date.now() / 1000) + DEFAULT_
14870
14853
 
14871
14854
  const amountIndex = 0;
14872
14855
  const gasEstimateIndex = 3;
14873
- async function getQuotesForRoutes(multicallContract, quoterContractAddress, routes, amountSpecified, tradeType) {
14874
- const callData = routes.map((route) => SwapQuoter.quoteCallParameters(route, toCurrencyAmount(amountSpecified), tradeType, {
14856
+ async function getQuotesForRoutes(provider, quoterContractAddress, routes, amountSpecified, tradeType) {
14857
+ const callDatas = routes.map((route) => SwapQuoter.quoteCallParameters(route, toCurrencyAmount(amountSpecified), tradeType, {
14875
14858
  useQuoterV2: true,
14876
14859
  }).calldata);
14877
- let quoteResults;
14878
- try {
14879
- quoteResults = await multicallMultipleCallDataSingContract(multicallContract, callData, quoterContractAddress);
14880
- }
14881
- catch (e) {
14882
- const message = e instanceof Error ? e.message : 'Unknown Error';
14883
- throw new ProviderCallError(`failed multicall: ${message}`);
14884
- }
14885
- const decodedQuoteResults = [];
14886
- // TODO: for..in loops iterate over the entire prototype chain,
14887
- // Use Object.{keys,values,entries}, and iterate over the resulting array.
14888
- // eslint-disable-next-line no-restricted-syntax, guard-for-in
14889
- for (const i in quoteResults.returnData) {
14890
- const functionSig = callData[i].substring(0, 10);
14860
+ const promises = await Promise.allSettled(callDatas.map((data) => provider.send('eth_call', [
14861
+ { to: quoterContractAddress, data }, 'latest',
14862
+ ])));
14863
+ const decodedQuoteResults = promises.reduce((quoteResults, promiseResult, i) => {
14864
+ if (promiseResult.status === 'rejected')
14865
+ return quoteResults;
14866
+ const functionSig = callDatas[i].substring(0, 10);
14891
14867
  const returnTypes = quoteReturnMapping[functionSig];
14892
14868
  if (!returnTypes) {
14893
14869
  throw new Error('No quoting function signature found');
14894
14870
  }
14895
- if (quoteResults.returnData[i].returnData === '0x') {
14871
+ if (promiseResult.value === '0x') {
14896
14872
  // There is no quote result for the swap using this route, so don't include it in results
14897
- // eslint-disable-next-line no-continue
14898
- continue;
14873
+ return quoteResults;
14899
14874
  }
14900
14875
  try {
14901
- const decodedQuoteResult = ethers.utils.defaultAbiCoder.decode(returnTypes, quoteResults.returnData[i].returnData);
14876
+ const decodedQuoteResult = utils.defaultAbiCoder.decode(returnTypes, promiseResult.value);
14902
14877
  if (decodedQuoteResult) {
14903
14878
  // The 0th element in each decoded data is going to be the amountOut or amountIn.
14904
14879
  const quoteAmount = decodedQuoteResult[amountIndex];
@@ -14906,11 +14881,11 @@ async function getQuotesForRoutes(multicallContract, quoterContractAddress, rout
14906
14881
  throw new Error('Expected BigNumber');
14907
14882
  const input = uniswapTokenToERC20(routes[i].input);
14908
14883
  const output = uniswapTokenToERC20(routes[i].output);
14909
- decodedQuoteResults.push({
14884
+ quoteResults.push({
14910
14885
  route: routes[i],
14911
14886
  amountIn: tradeType === TradeType.EXACT_INPUT ? amountSpecified : newAmount(quoteAmount, input),
14912
14887
  amountOut: tradeType === TradeType.EXACT_INPUT ? newAmount(quoteAmount, output) : amountSpecified,
14913
- gasEstimate: ethers.BigNumber.from(decodedQuoteResult[gasEstimateIndex]),
14888
+ gasEstimate: BigNumber$1.from(decodedQuoteResult[gasEstimateIndex]),
14914
14889
  tradeType,
14915
14890
  });
14916
14891
  }
@@ -14920,7 +14895,8 @@ async function getQuotesForRoutes(multicallContract, quoterContractAddress, rout
14920
14895
  // Other quotes for routes may still succeed, so do nothing
14921
14896
  // and continue processing
14922
14897
  }
14923
- }
14898
+ return quoteResults;
14899
+ }, new Array());
14924
14900
  return decodedQuoteResults;
14925
14901
  }
14926
14902
 
@@ -15048,19 +15024,24 @@ const fetchValidPools = async (multicallContract, erc20Pair, commonRoutingERC20s
15048
15024
 
15049
15025
  class Router {
15050
15026
  provider;
15027
+ multicallContract;
15051
15028
  routingTokens;
15052
15029
  routingContracts;
15053
- constructor(provider, routingTokens, routingContracts) {
15030
+ constructor(provider, multicallContract, routingTokens, routingContracts) {
15054
15031
  this.provider = provider;
15032
+ this.multicallContract = multicallContract;
15033
+ this.routingTokens = routingTokens;
15034
+ this.routingContracts = routingContracts;
15035
+ this.provider = provider;
15036
+ this.multicallContract = multicallContract;
15055
15037
  this.routingTokens = routingTokens;
15056
15038
  this.routingContracts = routingContracts;
15057
15039
  }
15058
15040
  async findOptimalRoute(amountSpecified, otherToken, tradeType, maxHops = 2) {
15059
15041
  const [tokenIn, tokenOut] = this.determineERC20InAndERC20Out(tradeType, amountSpecified, otherToken);
15060
- const multicallContract = Multicall__factory.connect(this.routingContracts.multicallAddress, this.provider);
15061
15042
  const erc20Pair = [tokenIn, tokenOut];
15062
15043
  // Get all pools and use these to get all possible routes.
15063
- const pools = await fetchValidPools(multicallContract, erc20Pair, this.routingTokens, this.routingContracts.factoryAddress);
15044
+ const pools = await fetchValidPools(this.multicallContract, erc20Pair, this.routingTokens, this.routingContracts.coreFactory);
15064
15045
  const noValidPools = pools.length === 0;
15065
15046
  if (noValidPools) {
15066
15047
  throw new NoRoutesAvailableError();
@@ -15074,10 +15055,10 @@ class Router {
15074
15055
  throw new NoRoutesAvailableError();
15075
15056
  }
15076
15057
  // Get the best quote from all of the given routes
15077
- return await this.getBestQuoteFromRoutes(multicallContract, routes, amountSpecified, tradeType);
15058
+ return await this.getBestQuoteFromRoutes(routes, amountSpecified, tradeType);
15078
15059
  }
15079
- async getBestQuoteFromRoutes(multicallContract, routes, amountSpecified, tradeType) {
15080
- const quotes = await getQuotesForRoutes(multicallContract, this.routingContracts.quoterAddress, routes, amountSpecified, tradeType);
15060
+ async getBestQuoteFromRoutes(routes, amountSpecified, tradeType) {
15061
+ const quotes = await getQuotesForRoutes(this.provider, this.routingContracts.quoterV2, routes, amountSpecified, tradeType);
15081
15062
  if (quotes.length === 0) {
15082
15063
  throw new NoRoutesAvailableError();
15083
15064
  }
@@ -15153,36 +15134,38 @@ startTokenIn = tokenIn) => {
15153
15134
  return routes;
15154
15135
  };
15155
15136
 
15156
- /**
15157
- * Determines whether or not the chain supports EIP-1559 by checking for the existence
15158
- * of {@link FeeData.maxFeePerGas} and {@link FeeData.maxPriorityFeePerGas}
15159
- *
15160
- * @param {FeeData} fee - The fee data for the chain
15161
- */
15162
- const doesChainSupportEIP1559$1 = (fee) => {
15163
- const supportsEIP1559 = !!fee.maxFeePerGas && !!fee.maxPriorityFeePerGas;
15164
- return supportsEIP1559;
15137
+ const getFeeData = async (provider) => {
15138
+ const [block, maxPriorityFeePerGas] = await Promise.all([
15139
+ provider.getBlock('latest'),
15140
+ provider.send('eth_maxPriorityFeePerGas', []),
15141
+ ]);
15142
+ if (!block.baseFeePerGas)
15143
+ throw new Error('Base fee per gas not found in block');
15144
+ return {
15145
+ // https://www.blocknative.com/blog/eip-1559-fees
15146
+ maxFeePerGas: block.baseFeePerGas.mul(2).add(maxPriorityFeePerGas),
15147
+ maxPriorityFeePerGas,
15148
+ lastBaseFeePerGas: block.baseFeePerGas,
15149
+ };
15165
15150
  };
15166
15151
  /**
15167
15152
  * Fetch the current gas price estimate. Supports both EIP-1559 and non-EIP1559 chains
15168
- * @param {JsonRpcProvider} provider - The JSON RPC provider used to fetch fee data
15153
+ * @param {Provider} provider - The JSON RPC provider used to fetch fee data
15169
15154
  * @param {Native} nativeToken - The native token of the chain. Gas prices will be denominated in this token
15170
- * @returns {Amount | null} - The gas price in the smallest denomination of the chain's currency,
15155
+ * @returns {CoinAmount<Native> | null} - The gas price in the smallest denomination of the chain's currency,
15171
15156
  * or null if no gas price is available
15172
15157
  */
15158
+ // eslint-disable-next-line max-len
15173
15159
  const fetchGasPrice = async (provider, nativeToken) => {
15174
- const feeData = await provider.getFeeData().catch(() => null);
15160
+ const feeData = await getFeeData(provider).catch(() => null);
15175
15161
  if (!feeData)
15176
15162
  return null;
15177
- if (doesChainSupportEIP1559$1(feeData)) {
15178
- return newAmount(feeData.maxFeePerGas.add(feeData.maxPriorityFeePerGas), nativeToken);
15179
- }
15180
- return feeData.gasPrice ? newAmount(feeData.gasPrice, nativeToken) : null;
15163
+ return newAmount(feeData.maxFeePerGas, nativeToken);
15181
15164
  };
15182
15165
  /**
15183
15166
  * Calculate the gas fee from the gas price and gas units used for the transaction
15184
15167
  *
15185
- * @param {Amount} gasPrice - The price of gas
15168
+ * @param {CoinAmount<Native>} gasPrice - The price of gas
15186
15169
  * @param {BigNumber} gasEstimate - The total gas units that will be used for the transaction
15187
15170
  * @returns - The cost of the transaction in the gas token's smallest denomination (e.g. WEI)
15188
15171
  */
@@ -15806,6 +15789,7 @@ const toPublicQuote = (amount, amountWithMaxSlippage, slippage, fees) => ({
15806
15789
  });
15807
15790
  class Exchange {
15808
15791
  provider;
15792
+ batchProvider;
15809
15793
  router;
15810
15794
  chainId;
15811
15795
  nativeToken;
@@ -15823,12 +15807,16 @@ class Exchange {
15823
15807
  this.secondaryFees = config.secondaryFees;
15824
15808
  this.routerContractAddress = config.chain.contracts.peripheryRouter;
15825
15809
  this.secondaryFeeContractAddress = config.chain.contracts.secondaryFee;
15826
- this.provider = new ethers.providers.JsonRpcProvider(config.chain.rpcUrl);
15827
- this.router = new Router(this.provider, config.chain.commonRoutingTokens, {
15828
- multicallAddress: config.chain.contracts.multicall,
15829
- factoryAddress: config.chain.contracts.coreFactory,
15830
- quoterAddress: config.chain.contracts.quoterV2,
15831
- });
15810
+ this.provider = new ethers.providers.StaticJsonRpcProvider({
15811
+ url: config.chain.rpcUrl,
15812
+ skipFetchSetup: true,
15813
+ }, config.chain.chainId);
15814
+ this.batchProvider = new ethers.providers.JsonRpcBatchProvider({
15815
+ url: config.chain.rpcUrl,
15816
+ skipFetchSetup: true,
15817
+ }, config.chain.chainId);
15818
+ const multicallContract = Multicall__factory.connect(config.chain.contracts.multicall, this.provider);
15819
+ this.router = new Router(this.batchProvider, multicallContract, config.chain.commonRoutingTokens, config.chain.contracts);
15832
15820
  }
15833
15821
  static validate(tokenInAddress, tokenOutAddress, maxHops, slippagePercent, fromAddress) {
15834
15822
  assert(isValidNonZeroAddress(fromAddress), new InvalidAddressError('invalid from address'));
@@ -15840,11 +15828,11 @@ class Exchange {
15840
15828
  assert(slippagePercent <= 50, new InvalidSlippageError('slippage percent must be less than or equal to 50'));
15841
15829
  assert(slippagePercent >= 0, new InvalidSlippageError('slippage percent must be greater than or equal to 0'));
15842
15830
  }
15843
- async getSecondaryFees() {
15831
+ async getSecondaryFees(provider) {
15844
15832
  if (this.secondaryFees.length === 0) {
15845
15833
  return [];
15846
15834
  }
15847
- const secondaryFeeContract = SecondaryFee__factory.connect(this.secondaryFeeContractAddress, this.provider);
15835
+ const secondaryFeeContract = SecondaryFee__factory.connect(this.secondaryFeeContractAddress, provider);
15848
15836
  if (await secondaryFeeContract.paused()) {
15849
15837
  // Do not use secondary fees if the contract is paused
15850
15838
  return [];
@@ -15865,11 +15853,13 @@ class Exchange {
15865
15853
  async getUnsignedSwapTx(fromAddress, tokenInLiteral, tokenOutLiteral, amount, slippagePercent, maxHops, deadline, tradeType) {
15866
15854
  Exchange.validate(tokenInLiteral, tokenOutLiteral, maxHops, slippagePercent, fromAddress);
15867
15855
  // get the decimals of the tokens that will be swapped
15868
- const [tokenInDecimals, tokenOutDecimals, secondaryFees] = await Promise.all([
15869
- getTokenDecimals(tokenInLiteral, this.provider, this.nativeToken),
15870
- getTokenDecimals(tokenOutLiteral, this.provider, this.nativeToken),
15871
- this.getSecondaryFees(),
15872
- ]);
15856
+ const promises = [
15857
+ getTokenDecimals(tokenInLiteral, this.batchProvider, this.nativeToken),
15858
+ getTokenDecimals(tokenOutLiteral, this.batchProvider, this.nativeToken),
15859
+ this.getSecondaryFees(this.batchProvider),
15860
+ fetchGasPrice(this.batchProvider, this.nativeToken),
15861
+ ];
15862
+ const [tokenInDecimals, tokenOutDecimals, secondaryFees, gasPrice] = await Promise.all(promises);
15873
15863
  const tokenIn = this.parseTokenLiteral(tokenInLiteral, tokenInDecimals);
15874
15864
  const tokenOut = this.parseTokenLiteral(tokenOutLiteral, tokenOutDecimals);
15875
15865
  // determine which amount was specified for the swap from the TradeType
@@ -15878,10 +15868,7 @@ class Exchange {
15878
15868
  const fees = new Fees(secondaryFees, tokenIn);
15879
15869
  const ourQuoteReqAmount = getOurQuoteReqAmount(amountSpecified, fees, tradeType, this.nativeTokenService);
15880
15870
  // Quotes will always use ERC20s. If the user-specified token is Native, we use the Wrapped Native Token pool
15881
- const [ourQuote, gasPrice] = await Promise.all([
15882
- this.router.findOptimalRoute(ourQuoteReqAmount, this.nativeTokenService.maybeWrapToken(otherToken), tradeType, maxHops),
15883
- fetchGasPrice(this.provider, this.nativeToken),
15884
- ]);
15871
+ const ourQuote = await this.router.findOptimalRoute(ourQuoteReqAmount, this.nativeTokenService.maybeWrapToken(otherToken), tradeType, maxHops);
15885
15872
  const adjustedQuote = adjustQuoteWithFees(ourQuote, amountSpecified, fees, this.nativeTokenService);
15886
15873
  const swap = getSwap(tokenIn, tokenOut, adjustedQuote, fromAddress, slippagePercent, deadline, this.routerContractAddress, this.secondaryFeeContractAddress, gasPrice, secondaryFees);
15887
15874
  const { quotedAmount, quotedAmountWithMaxSlippage } = prepareUserQuote(this.nativeTokenService, adjustedQuote, slippagePercent, otherToken);
@@ -20999,7 +20986,7 @@ class APIError extends Error {
20999
20986
 
21000
20987
  /* eslint-disable implicit-arrow-linebreak */
21001
20988
  const defaultHeaders = {
21002
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.35.0',
20989
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.35.2',
21003
20990
  };
21004
20991
  /**
21005
20992
  * createAPIConfiguration to create a custom Configuration
@@ -22276,7 +22263,7 @@ const GAS_OVERRIDES = {
22276
22263
  maxPriorityFeePerGas: BigNumber$1.from(101e9),
22277
22264
  };
22278
22265
 
22279
- const SDK_VERSION_MARKER = '0.35.0';
22266
+ const SDK_VERSION_MARKER = '0.35.2';
22280
22267
  // This SDK version is replaced by the `yarn build` command ran on the root level
22281
22268
  const globalPackageVersion = () => SDK_VERSION_MARKER;
22282
22269
 
@@ -17,7 +17,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
17
17
  chainID,
18
18
  coreContractAddress,
19
19
  registrationContractAddress,
20
- sdkVersion: 'ts-immutable-sdk-0.35.0',
20
+ sdkVersion: 'ts-immutable-sdk-0.35.2',
21
21
  });
22
22
  /**
23
23
  * Sets `sdkVersion` at the time of build