@pancakeswap/sdk 4.0.0 → 5.1.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.
package/dist/index.mjs CHANGED
@@ -1,12 +1,9 @@
1
- import { Percent, Token, Price, ZERO, InsufficientReservesError, _9975, _10000, CurrencyAmount, InsufficientInputAmountError, ONE, sqrt, MINIMUM_LIQUIDITY, TradeType, computePriceImpact, Fraction, sortedInsert, NativeCurrency, FIVE } from '@pancakeswap/swap-sdk-core';
1
+ import { Percent, Token, BaseCurrency, Price, ZERO, InsufficientReservesError, _9975, _10000, CurrencyAmount, InsufficientInputAmountError, ONE, sqrt, MINIMUM_LIQUIDITY, TradeType, computePriceImpact, Fraction, sortedInsert, NativeCurrency, FIVE } from '@pancakeswap/swap-sdk-core';
2
2
  export * from '@pancakeswap/swap-sdk-core';
3
- import { getAddress, getCreate2Address } from '@ethersproject/address';
4
- import invariant4 from 'tiny-invariant';
3
+ import invariant5 from 'tiny-invariant';
4
+ import { createPublicClient, http, getAddress, keccak256, encodePacked, getContract, toBytes, pad, isBytes, slice, concat } from 'viem';
5
5
  import warning from 'tiny-warning';
6
- import { keccak256, pack } from '@ethersproject/solidity';
7
- import { Contract } from '@ethersproject/contracts';
8
- import { getNetwork } from '@ethersproject/networks';
9
- import { getDefaultProvider } from '@ethersproject/providers';
6
+ import { mainnet, bsc, bscTestnet, goerli } from 'viem/chains';
10
7
 
11
8
  // src/constants.ts
12
9
  function validateAndParseAddress(address) {
@@ -15,7 +12,7 @@ function validateAndParseAddress(address) {
15
12
  warning(address === checksummedAddress, `${address} is not checksummed.`);
16
13
  return checksummedAddress;
17
14
  } catch (error) {
18
- invariant4(false, `${address} is not a valid address.`);
15
+ invariant5(false, `${address} is not a valid address.`);
19
16
  }
20
17
  }
21
18
 
@@ -25,6 +22,51 @@ var ERC20Token = class extends Token {
25
22
  super(chainId, validateAndParseAddress(address), decimals, symbol, name, projectLink);
26
23
  }
27
24
  };
25
+ var OnRampCurrency = class extends BaseCurrency {
26
+ constructor(chainId, address, decimals, symbol, name, projectLink) {
27
+ super(chainId, decimals, symbol, name);
28
+ this.address = address;
29
+ this.projectLink = projectLink;
30
+ this.isNative = address === "0x" && true;
31
+ this.isToken = address !== "0x" && true;
32
+ }
33
+ /**
34
+ * Returns true if the two tokens are equivalent, i.e. have the same chainId and address.
35
+ * @param other other token to compare
36
+ */
37
+ equals(other) {
38
+ return other.isToken && this.chainId === other.chainId && this.address === other.address;
39
+ }
40
+ /**
41
+ * Returns true if the address of this token sorts before the address of the other token
42
+ * @param other other token to compare
43
+ * @throws if the tokens have the same address
44
+ * @throws if the tokens are on different chains
45
+ */
46
+ sortsBefore(other) {
47
+ if (!other.isToken)
48
+ return false;
49
+ invariant5(this.chainId === other.chainId, "CHAIN_IDS");
50
+ invariant5(this.address !== other.address, "ADDRESSES");
51
+ return this.address.toLowerCase() < other.address.toLowerCase();
52
+ }
53
+ /**
54
+ * Return this token, which does not need to be wrapped
55
+ */
56
+ get wrapped() {
57
+ return this;
58
+ }
59
+ get serialize() {
60
+ return {
61
+ address: this.address,
62
+ chainId: this.chainId,
63
+ decimals: this.decimals,
64
+ symbol: this.symbol,
65
+ name: this.name,
66
+ projectLink: this.projectLink
67
+ };
68
+ }
69
+ };
28
70
 
29
71
  // src/constants.ts
30
72
  var ChainId = /* @__PURE__ */ ((ChainId3) => {
@@ -32,6 +74,13 @@ var ChainId = /* @__PURE__ */ ((ChainId3) => {
32
74
  ChainId3[ChainId3["GOERLI"] = 5] = "GOERLI";
33
75
  ChainId3[ChainId3["BSC"] = 56] = "BSC";
34
76
  ChainId3[ChainId3["BSC_TESTNET"] = 97] = "BSC_TESTNET";
77
+ ChainId3[ChainId3["ZKSYNC_TESTNET"] = 280] = "ZKSYNC_TESTNET";
78
+ ChainId3[ChainId3["ZKSYNC"] = 324] = "ZKSYNC";
79
+ ChainId3[ChainId3["POLYGON_ZKEVM"] = 1101] = "POLYGON_ZKEVM";
80
+ ChainId3[ChainId3["POLYGON_ZKEVM_TESTNET"] = 1442] = "POLYGON_ZKEVM_TESTNET";
81
+ ChainId3[ChainId3["ARBITRUM_ONE"] = 42161] = "ARBITRUM_ONE";
82
+ ChainId3[ChainId3["ARBITRUM_GOERLI"] = 421613] = "ARBITRUM_GOERLI";
83
+ ChainId3[ChainId3["LINEA_TESTNET"] = 59140] = "LINEA_TESTNET";
35
84
  return ChainId3;
36
85
  })(ChainId || {});
37
86
  var ZERO_PERCENT = new Percent("0");
@@ -42,7 +91,14 @@ var FACTORY_ADDRESS_MAP = {
42
91
  [1 /* ETHEREUM */]: FACTORY_ADDRESS_ETH,
43
92
  [5 /* GOERLI */]: FACTORY_ADDRESS_ETH,
44
93
  [56 /* BSC */]: FACTORY_ADDRESS,
45
- [97 /* BSC_TESTNET */]: "0x6725f303b657a9451d8ba641348b6761a6cc7a17"
94
+ [97 /* BSC_TESTNET */]: "0x6725f303b657a9451d8ba641348b6761a6cc7a17",
95
+ [42161 /* ARBITRUM_ONE */]: "0x02a84c1b3BBD7401a5f7fa98a384EBC70bB5749E",
96
+ [421613 /* ARBITRUM_GOERLI */]: "0x333EAE459075b1d7dE8eb57997b5d4eee5F1070a",
97
+ [1101 /* POLYGON_ZKEVM */]: "0x02a84c1b3BBD7401a5f7fa98a384EBC70bB5749E",
98
+ [1442 /* POLYGON_ZKEVM_TESTNET */]: "0xBA40c83026213F9cbc79998752721a0312bdB74a",
99
+ [324 /* ZKSYNC */]: "0x0F70cE1e2c0FB5FC3B67E13ed4F422fE82d832bD",
100
+ [280 /* ZKSYNC_TESTNET */]: "0x48a33610Cd0E130af2024D55F67aE72a8C51aC27",
101
+ [59140 /* LINEA_TESTNET */]: "0xB6FAfd4ADbCd21cF665909767e0eD0D05709abfB"
46
102
  };
47
103
  var INIT_CODE_HASH = "0x00fb7f630766e6a796048ea87d01acd3068e8ff67d078148a3fa3f4a84f69bd5";
48
104
  var INIT_CODE_HASH_ETH = "0x57224589c67f3f30a6b0d7a1b54cf3153ab84563bc609ef41dfb34f8b2974d2d";
@@ -50,7 +106,15 @@ var INIT_CODE_HASH_MAP = {
50
106
  [1 /* ETHEREUM */]: INIT_CODE_HASH_ETH,
51
107
  [5 /* GOERLI */]: INIT_CODE_HASH_ETH,
52
108
  [56 /* BSC */]: INIT_CODE_HASH,
53
- [97 /* BSC_TESTNET */]: "0xd0d4c4cd0848c93cb4fd1f498d7013ee6bfb25783ea21593d5834f5d250ece66"
109
+ [97 /* BSC_TESTNET */]: "0xd0d4c4cd0848c93cb4fd1f498d7013ee6bfb25783ea21593d5834f5d250ece66",
110
+ [42161 /* ARBITRUM_ONE */]: INIT_CODE_HASH_ETH,
111
+ [421613 /* ARBITRUM_GOERLI */]: INIT_CODE_HASH_ETH,
112
+ [1101 /* POLYGON_ZKEVM */]: INIT_CODE_HASH_ETH,
113
+ [1442 /* POLYGON_ZKEVM_TESTNET */]: INIT_CODE_HASH_ETH,
114
+ // TODO: new chains
115
+ [324 /* ZKSYNC */]: "0x1cb011040b91cd937ddff2327f17c9690653b05b6506e830baadf2493468d657",
116
+ [280 /* ZKSYNC_TESTNET */]: "0x0100045707a42494392b3558029b9869f865ff9df8f375dc1bf20b0555093f43",
117
+ [59140 /* LINEA_TESTNET */]: INIT_CODE_HASH_ETH
54
118
  };
55
119
  var WETH9 = {
56
120
  [1 /* ETHEREUM */]: new ERC20Token(
@@ -84,6 +148,62 @@ var WETH9 = {
84
148
  "ETH",
85
149
  "ETH",
86
150
  "https://ethereum.org"
151
+ ),
152
+ [42161 /* ARBITRUM_ONE */]: new ERC20Token(
153
+ 42161 /* ARBITRUM_ONE */,
154
+ "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
155
+ 18,
156
+ "WETH",
157
+ "Wrapped Ether",
158
+ "https://weth.io"
159
+ ),
160
+ [421613 /* ARBITRUM_GOERLI */]: new ERC20Token(
161
+ 421613 /* ARBITRUM_GOERLI */,
162
+ "0xEe01c0CD76354C383B8c7B4e65EA88D00B06f36f",
163
+ 18,
164
+ "WETH",
165
+ "Wrapped Ether",
166
+ "https://weth.io"
167
+ ),
168
+ [324 /* ZKSYNC */]: new ERC20Token(
169
+ 324 /* ZKSYNC */,
170
+ "0x5AEa5775959fBC2557Cc8789bC1bf90A239D9a91",
171
+ 18,
172
+ "WETH",
173
+ "Wrapped Ether",
174
+ "https://weth.io"
175
+ ),
176
+ [280 /* ZKSYNC_TESTNET */]: new ERC20Token(
177
+ 280 /* ZKSYNC_TESTNET */,
178
+ "0x02968DB286f24cB18bB5b24903eC8eBFAcf591C0",
179
+ 18,
180
+ "WETH",
181
+ "Wrapped Ether",
182
+ "https://weth.io"
183
+ ),
184
+ [1101 /* POLYGON_ZKEVM */]: new ERC20Token(
185
+ 1101 /* POLYGON_ZKEVM */,
186
+ "0x4F9A0e7FD2Bf6067db6994CF12E4495Df938E6e9",
187
+ 18,
188
+ "WETH",
189
+ "Wrapped Ether",
190
+ "https://weth.io"
191
+ ),
192
+ [1442 /* POLYGON_ZKEVM_TESTNET */]: new ERC20Token(
193
+ 1442 /* POLYGON_ZKEVM_TESTNET */,
194
+ "0x30ec47F7DFae72eA79646e6cf64a8A7db538915b",
195
+ 18,
196
+ "WETH",
197
+ "Wrapped Ether",
198
+ "https://weth.io"
199
+ ),
200
+ [59140 /* LINEA_TESTNET */]: new ERC20Token(
201
+ 59140 /* LINEA_TESTNET */,
202
+ "0x2C1b868d6596a18e32E61B901E4060C872647b6C",
203
+ 18,
204
+ "WETH",
205
+ "Wrapped Ether",
206
+ "https://weth.io"
87
207
  )
88
208
  };
89
209
  var WBNB = {
@@ -116,10 +236,18 @@ var WNATIVE = {
116
236
  [1 /* ETHEREUM */]: WETH9[1 /* ETHEREUM */],
117
237
  [5 /* GOERLI */]: WETH9[5 /* GOERLI */],
118
238
  [56 /* BSC */]: WBNB[56 /* BSC */],
119
- [97 /* BSC_TESTNET */]: WBNB[97 /* BSC_TESTNET */]
239
+ [97 /* BSC_TESTNET */]: WBNB[97 /* BSC_TESTNET */],
240
+ [42161 /* ARBITRUM_ONE */]: WETH9[42161 /* ARBITRUM_ONE */],
241
+ [421613 /* ARBITRUM_GOERLI */]: WETH9[421613 /* ARBITRUM_GOERLI */],
242
+ [1101 /* POLYGON_ZKEVM */]: WETH9[1101 /* POLYGON_ZKEVM */],
243
+ [1442 /* POLYGON_ZKEVM_TESTNET */]: WETH9[1442 /* POLYGON_ZKEVM_TESTNET */],
244
+ [324 /* ZKSYNC */]: WETH9[324 /* ZKSYNC */],
245
+ [280 /* ZKSYNC_TESTNET */]: WETH9[280 /* ZKSYNC_TESTNET */],
246
+ [59140 /* LINEA_TESTNET */]: WETH9[59140 /* LINEA_TESTNET */]
120
247
  };
248
+ var ETHER = { name: "Ether", symbol: "ETH", decimals: 18 };
121
249
  var NATIVE = {
122
- [1 /* ETHEREUM */]: { name: "Ether", symbol: "ETH", decimals: 18 },
250
+ [1 /* ETHEREUM */]: ETHER,
123
251
  [5 /* GOERLI */]: { name: "Goerli Ether", symbol: "GOR", decimals: 18 },
124
252
  [56 /* BSC */]: {
125
253
  name: "Binance Chain Native Token",
@@ -130,7 +258,18 @@ var NATIVE = {
130
258
  name: "Binance Chain Native Token",
131
259
  symbol: "tBNB",
132
260
  decimals: 18
133
- }
261
+ },
262
+ [42161 /* ARBITRUM_ONE */]: ETHER,
263
+ [421613 /* ARBITRUM_GOERLI */]: {
264
+ name: "Arbitrum Goerli Ether",
265
+ symbol: "AGOR",
266
+ decimals: 18
267
+ },
268
+ [1101 /* POLYGON_ZKEVM */]: ETHER,
269
+ [1442 /* POLYGON_ZKEVM_TESTNET */]: ETHER,
270
+ [324 /* ZKSYNC */]: ETHER,
271
+ [280 /* ZKSYNC_TESTNET */]: ETHER,
272
+ [59140 /* LINEA_TESTNET */]: ETHER
134
273
  };
135
274
 
136
275
  // src/trade.ts
@@ -151,6 +290,20 @@ function isTradeBetter(tradeA, tradeB, minimumDelta = ZERO_PERCENT) {
151
290
  }
152
291
  var PAIR_ADDRESS_CACHE = {};
153
292
  var composeKey = (token0, token1) => `${token0.chainId}-${token0.address}-${token1.address}`;
293
+ function getCreate2Address(from_, salt_, initCodeHash) {
294
+ const from = toBytes(getAddress(from_));
295
+ const salt = pad(isBytes(salt_) ? salt_ : toBytes(salt_), {
296
+ size: 32
297
+ });
298
+ return getAddress(slice(keccak256(concat([toBytes("0xff"), from, salt, toBytes(initCodeHash)])), 12));
299
+ }
300
+ var EMPTY_INPU_HASH = "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470";
301
+ var ZKSYNC_PREFIX = "0x2020dba91b30cc0006188af794c2fb30dd8520db7e2c088b7fc7c103c00ca494";
302
+ function getCreate2AddressZkSync(from, salt, initCodeHash) {
303
+ return getAddress(
304
+ `0x${keccak256(concat([ZKSYNC_PREFIX, pad(from, { size: 32 }), salt, initCodeHash, EMPTY_INPU_HASH])).slice(26)}`
305
+ );
306
+ }
154
307
  var computePairAddress = ({
155
308
  factoryAddress,
156
309
  tokenA,
@@ -159,11 +312,12 @@ var computePairAddress = ({
159
312
  const [token0, token1] = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA];
160
313
  const key = composeKey(token0, token1);
161
314
  if (PAIR_ADDRESS_CACHE?.[key] === void 0) {
315
+ const getCreate2Address_ = token0.chainId === 280 /* ZKSYNC_TESTNET */ || token1.chainId === 324 /* ZKSYNC */ ? getCreate2AddressZkSync : getCreate2Address;
162
316
  PAIR_ADDRESS_CACHE = {
163
317
  ...PAIR_ADDRESS_CACHE,
164
- [key]: getCreate2Address(
318
+ [key]: getCreate2Address_(
165
319
  factoryAddress,
166
- keccak256(["bytes"], [pack(["address", "address"], [token0.address, token1.address])]),
320
+ keccak256(encodePacked(["address", "address"], [token0.address, token1.address])),
167
321
  INIT_CODE_HASH_MAP[token0.chainId]
168
322
  )
169
323
  };
@@ -172,7 +326,11 @@ var computePairAddress = ({
172
326
  };
173
327
  var Pair = class {
174
328
  static getAddress(tokenA, tokenB) {
175
- return computePairAddress({ factoryAddress: FACTORY_ADDRESS_MAP[tokenA.chainId], tokenA, tokenB });
329
+ return computePairAddress({
330
+ factoryAddress: FACTORY_ADDRESS_MAP[tokenA.chainId],
331
+ tokenA,
332
+ tokenB
333
+ });
176
334
  }
177
335
  constructor(currencyAmountA, tokenAmountB) {
178
336
  const tokenAmounts = currencyAmountA.currency.sortsBefore(tokenAmountB.currency) ? [currencyAmountA, tokenAmountB] : [tokenAmountB, currencyAmountA];
@@ -211,7 +369,7 @@ var Pair = class {
211
369
  * @param token token to return price of
212
370
  */
213
371
  priceOf(token) {
214
- invariant4(this.involvesToken(token), "TOKEN");
372
+ invariant5(this.involvesToken(token), "TOKEN");
215
373
  return token.equals(this.token0) ? this.token0Price : this.token1Price;
216
374
  }
217
375
  /**
@@ -233,11 +391,11 @@ var Pair = class {
233
391
  return this.tokenAmounts[1];
234
392
  }
235
393
  reserveOf(token) {
236
- invariant4(this.involvesToken(token), "TOKEN");
394
+ invariant5(this.involvesToken(token), "TOKEN");
237
395
  return token.equals(this.token0) ? this.reserve0 : this.reserve1;
238
396
  }
239
397
  getOutputAmount(inputAmount) {
240
- invariant4(this.involvesToken(inputAmount.currency), "TOKEN");
398
+ invariant5(this.involvesToken(inputAmount.currency), "TOKEN");
241
399
  if (this.reserve0.quotient === ZERO || this.reserve1.quotient === ZERO) {
242
400
  throw new InsufficientReservesError();
243
401
  }
@@ -256,7 +414,7 @@ var Pair = class {
256
414
  return [outputAmount, new Pair(inputReserve.add(inputAmount), outputReserve.subtract(outputAmount))];
257
415
  }
258
416
  getInputAmount(outputAmount) {
259
- invariant4(this.involvesToken(outputAmount.currency), "TOKEN");
417
+ invariant5(this.involvesToken(outputAmount.currency), "TOKEN");
260
418
  if (this.reserve0.quotient === ZERO || this.reserve1.quotient === ZERO || outputAmount.quotient >= this.reserveOf(outputAmount.currency).quotient) {
261
419
  throw new InsufficientReservesError();
262
420
  }
@@ -271,9 +429,9 @@ var Pair = class {
271
429
  return [inputAmount, new Pair(inputReserve.add(inputAmount), outputReserve.subtract(outputAmount))];
272
430
  }
273
431
  getLiquidityMinted(totalSupply, tokenAmountA, tokenAmountB) {
274
- invariant4(totalSupply.currency.equals(this.liquidityToken), "LIQUIDITY");
432
+ invariant5(totalSupply.currency.equals(this.liquidityToken), "LIQUIDITY");
275
433
  const tokenAmounts = tokenAmountA.currency.sortsBefore(tokenAmountB.currency) ? [tokenAmountA, tokenAmountB] : [tokenAmountB, tokenAmountA];
276
- invariant4(tokenAmounts[0].currency.equals(this.token0) && tokenAmounts[1].currency.equals(this.token1), "TOKEN");
434
+ invariant5(tokenAmounts[0].currency.equals(this.token0) && tokenAmounts[1].currency.equals(this.token1), "TOKEN");
277
435
  let liquidity;
278
436
  if (totalSupply.quotient === ZERO) {
279
437
  liquidity = sqrt(tokenAmounts[0].quotient * tokenAmounts[1].quotient) - MINIMUM_LIQUIDITY;
@@ -288,15 +446,15 @@ var Pair = class {
288
446
  return CurrencyAmount.fromRawAmount(this.liquidityToken, liquidity);
289
447
  }
290
448
  getLiquidityValue(token, totalSupply, liquidity, feeOn = false, kLast) {
291
- invariant4(this.involvesToken(token), "TOKEN");
292
- invariant4(totalSupply.currency.equals(this.liquidityToken), "TOTAL_SUPPLY");
293
- invariant4(liquidity.currency.equals(this.liquidityToken), "LIQUIDITY");
294
- invariant4(liquidity.quotient <= totalSupply.quotient, "LIQUIDITY");
449
+ invariant5(this.involvesToken(token), "TOKEN");
450
+ invariant5(totalSupply.currency.equals(this.liquidityToken), "TOTAL_SUPPLY");
451
+ invariant5(liquidity.currency.equals(this.liquidityToken), "LIQUIDITY");
452
+ invariant5(liquidity.quotient <= totalSupply.quotient, "LIQUIDITY");
295
453
  let totalSupplyAdjusted;
296
454
  if (!feeOn) {
297
455
  totalSupplyAdjusted = totalSupply;
298
456
  } else {
299
- invariant4(!!kLast, "K_LAST");
457
+ invariant5(!!kLast, "K_LAST");
300
458
  const kLastParsed = BigInt(kLast);
301
459
  if (!(kLastParsed === ZERO)) {
302
460
  const rootK = sqrt(this.reserve0.quotient * this.reserve1.quotient);
@@ -322,19 +480,19 @@ var Pair = class {
322
480
  var Route = class {
323
481
  constructor(pairs, input, output) {
324
482
  this._midPrice = null;
325
- invariant4(pairs.length > 0, "PAIRS");
483
+ invariant5(pairs.length > 0, "PAIRS");
326
484
  const { chainId } = pairs[0];
327
- invariant4(
485
+ invariant5(
328
486
  pairs.every((pair) => pair.chainId === chainId),
329
487
  "CHAIN_IDS"
330
488
  );
331
489
  const wrappedInput = input.wrapped;
332
- invariant4(pairs[0].involvesToken(wrappedInput), "INPUT");
333
- invariant4(typeof output === "undefined" || pairs[pairs.length - 1].involvesToken(output.wrapped), "OUTPUT");
490
+ invariant5(pairs[0].involvesToken(wrappedInput), "INPUT");
491
+ invariant5(typeof output === "undefined" || pairs[pairs.length - 1].involvesToken(output.wrapped), "OUTPUT");
334
492
  const path = [wrappedInput];
335
493
  for (const [i, pair] of pairs.entries()) {
336
494
  const currentInput = path[i];
337
- invariant4(currentInput.equals(pair.token0) || currentInput.equals(pair.token1), "PATH");
495
+ invariant5(currentInput.equals(pair.token0) || currentInput.equals(pair.token1), "PATH");
338
496
  const output2 = currentInput.equals(pair.token0) ? pair.token1 : pair.token0;
339
497
  path.push(output2);
340
498
  }
@@ -360,8 +518,8 @@ var Route = class {
360
518
  }
361
519
  };
362
520
  function inputOutputComparator(a, b) {
363
- invariant4(a.inputAmount.currency.equals(b.inputAmount.currency), "INPUT_CURRENCY");
364
- invariant4(a.outputAmount.currency.equals(b.outputAmount.currency), "OUTPUT_CURRENCY");
521
+ invariant5(a.inputAmount.currency.equals(b.inputAmount.currency), "INPUT_CURRENCY");
522
+ invariant5(a.outputAmount.currency.equals(b.outputAmount.currency), "OUTPUT_CURRENCY");
365
523
  if (a.outputAmount.equalTo(b.outputAmount)) {
366
524
  if (a.inputAmount.equalTo(b.inputAmount)) {
367
525
  return 0;
@@ -411,7 +569,7 @@ var Trade = class {
411
569
  this.tradeType = tradeType;
412
570
  const tokenAmounts = new Array(route.path.length);
413
571
  if (tradeType === TradeType.EXACT_INPUT) {
414
- invariant4(amount.currency.equals(route.input), "INPUT");
572
+ invariant5(amount.currency.equals(route.input), "INPUT");
415
573
  tokenAmounts[0] = amount.wrapped;
416
574
  for (let i = 0; i < route.path.length - 1; i++) {
417
575
  const pair = route.pairs[i];
@@ -425,7 +583,7 @@ var Trade = class {
425
583
  tokenAmounts[tokenAmounts.length - 1].denominator
426
584
  );
427
585
  } else {
428
- invariant4(amount.currency.equals(route.output), "OUTPUT");
586
+ invariant5(amount.currency.equals(route.output), "OUTPUT");
429
587
  tokenAmounts[tokenAmounts.length - 1] = amount.wrapped;
430
588
  for (let i = route.path.length - 1; i > 0; i--) {
431
589
  const pair = route.pairs[i - 1];
@@ -452,7 +610,7 @@ var Trade = class {
452
610
  * @param slippageTolerance tolerance of unfavorable slippage from the execution price of this trade
453
611
  */
454
612
  minimumAmountOut(slippageTolerance) {
455
- invariant4(!slippageTolerance.lessThan(ZERO), "SLIPPAGE_TOLERANCE");
613
+ invariant5(!slippageTolerance.lessThan(ZERO), "SLIPPAGE_TOLERANCE");
456
614
  if (this.tradeType === TradeType.EXACT_OUTPUT) {
457
615
  return this.outputAmount;
458
616
  }
@@ -464,7 +622,7 @@ var Trade = class {
464
622
  * @param slippageTolerance tolerance of unfavorable slippage from the execution price of this trade
465
623
  */
466
624
  maximumAmountIn(slippageTolerance) {
467
- invariant4(!slippageTolerance.lessThan(ZERO), "SLIPPAGE_TOLERANCE");
625
+ invariant5(!slippageTolerance.lessThan(ZERO), "SLIPPAGE_TOLERANCE");
468
626
  if (this.tradeType === TradeType.EXACT_INPUT) {
469
627
  return this.inputAmount;
470
628
  }
@@ -486,9 +644,9 @@ var Trade = class {
486
644
  * @param bestTrades used in recursion; the current list of best trades
487
645
  */
488
646
  static bestTradeExactIn(pairs, currencyAmountIn, currencyOut, { maxNumResults = 3, maxHops = 3 } = {}, currentPairs = [], nextAmountIn = currencyAmountIn, bestTrades = []) {
489
- invariant4(pairs.length > 0, "PAIRS");
490
- invariant4(maxHops > 0, "MAX_HOPS");
491
- invariant4(currencyAmountIn === nextAmountIn || currentPairs.length > 0, "INVALID_RECURSION");
647
+ invariant5(pairs.length > 0, "PAIRS");
648
+ invariant5(maxHops > 0, "MAX_HOPS");
649
+ invariant5(currencyAmountIn === nextAmountIn || currentPairs.length > 0, "INVALID_RECURSION");
492
650
  const amountIn = nextAmountIn.wrapped;
493
651
  const tokenOut = currencyOut.wrapped;
494
652
  for (let i = 0; i < pairs.length; i++) {
@@ -564,9 +722,9 @@ var Trade = class {
564
722
  * @param bestTrades used in recursion; the current list of best trades
565
723
  */
566
724
  static bestTradeExactOut(pairs, currencyIn, currencyAmountOut, { maxNumResults = 3, maxHops = 3 } = {}, currentPairs = [], nextAmountOut = currencyAmountOut, bestTrades = []) {
567
- invariant4(pairs.length > 0, "PAIRS");
568
- invariant4(maxHops > 0, "MAX_HOPS");
569
- invariant4(currencyAmountOut === nextAmountOut || currentPairs.length > 0, "INVALID_RECURSION");
725
+ invariant5(pairs.length > 0, "PAIRS");
726
+ invariant5(maxHops > 0, "MAX_HOPS");
727
+ invariant5(currencyAmountOut === nextAmountOut || currentPairs.length > 0, "INVALID_RECURSION");
570
728
  const amountOut = nextAmountOut.wrapped;
571
729
  const tokenIn = currencyIn.wrapped;
572
730
  for (let i = 0; i < pairs.length; i++) {
@@ -626,14 +784,14 @@ var _Native = class extends NativeCurrency {
626
784
  }
627
785
  get wrapped() {
628
786
  const wnative = WNATIVE[this.chainId];
629
- invariant4(!!wnative, "WRAPPED");
787
+ invariant5(!!wnative, "WRAPPED");
630
788
  return wnative;
631
789
  }
632
790
  static onChain(chainId) {
633
791
  if (chainId in this.cache) {
634
792
  return this.cache[chainId];
635
793
  }
636
- invariant4(!!NATIVE[chainId], "NATIVE_CURRENCY");
794
+ invariant5(!!NATIVE[chainId], "NATIVE_CURRENCY");
637
795
  const { decimals, name, symbol } = NATIVE[chainId];
638
796
  return this.cache[chainId] = new _Native({ chainId, decimals, symbol, name });
639
797
  }
@@ -656,8 +814,8 @@ var Router = class {
656
814
  static swapCallParameters(trade, options) {
657
815
  const etherIn = trade.inputAmount.currency.isNative;
658
816
  const etherOut = trade.outputAmount.currency.isNative;
659
- invariant4(!(etherIn && etherOut), "ETHER_IN_OUT");
660
- invariant4(!("ttl" in options) || options.ttl > 0, "TTL");
817
+ invariant5(!(etherIn && etherOut), "ETHER_IN_OUT");
818
+ invariant5(!("ttl" in options) || options.ttl > 0, "TTL");
661
819
  const to = validateAndParseAddress(options.recipient);
662
820
  const amountIn = toHex(trade.maximumAmountIn(options.allowedSlippage));
663
821
  const amountOut = toHex(trade.minimumAmountOut(options.allowedSlippage));
@@ -684,7 +842,7 @@ var Router = class {
684
842
  }
685
843
  break;
686
844
  case TradeType.EXACT_OUTPUT:
687
- invariant4(!useFeeOnTransfer, "EXACT_OUT_FOT");
845
+ invariant5(!useFeeOnTransfer, "EXACT_OUT_FOT");
688
846
  if (etherIn) {
689
847
  methodName = "swapETHForExactTokens";
690
848
  args = [amountOut, path, to, deadline];
@@ -713,7 +871,7 @@ var _Ether = class extends NativeCurrency {
713
871
  }
714
872
  get wrapped() {
715
873
  const weth9 = WETH9[this.chainId];
716
- invariant4(!!weth9, "WRAPPED");
874
+ invariant5(!!weth9, "WRAPPED");
717
875
  return weth9;
718
876
  }
719
877
  static onChain(chainId) {
@@ -729,8 +887,8 @@ var _Ether = class extends NativeCurrency {
729
887
  var Ether = _Ether;
730
888
  Ether._etherCache = {};
731
889
 
732
- // src/abis/ERC20.json
733
- var ERC20_default = [
890
+ // src/abis/ERC20.ts
891
+ var erc20ABI = [
734
892
  {
735
893
  constant: true,
736
894
  inputs: [],
@@ -751,8 +909,8 @@ var ERC20_default = [
751
909
  }
752
910
  ];
753
911
 
754
- // src/abis/IPancakePair.json
755
- var IPancakePair_default = [
912
+ // src/abis/IPancakePair.ts
913
+ var pancakePairV2ABI = [
756
914
  {
757
915
  anonymous: false,
758
916
  inputs: [
@@ -1464,6 +1622,24 @@ var IPancakePair_default = [
1464
1622
  var TOKEN_DECIMALS_CACHE = {
1465
1623
  [56 /* BSC */]: {}
1466
1624
  };
1625
+ var ethClient = createPublicClient({ chain: mainnet, transport: http() });
1626
+ var bscClient = createPublicClient({ chain: bsc, transport: http() });
1627
+ var bscTestnetClient = createPublicClient({ chain: bscTestnet, transport: http() });
1628
+ var goerliClient = createPublicClient({ chain: goerli, transport: http() });
1629
+ var getDefaultClient = (chainId) => {
1630
+ switch (chainId) {
1631
+ case 1 /* ETHEREUM */:
1632
+ return ethClient;
1633
+ case 56 /* BSC */:
1634
+ return bscClient;
1635
+ case 97 /* BSC_TESTNET */:
1636
+ return bscTestnetClient;
1637
+ case 5 /* GOERLI */:
1638
+ return goerliClient;
1639
+ default:
1640
+ return bscClient;
1641
+ }
1642
+ };
1467
1643
  var Fetcher = class {
1468
1644
  /**
1469
1645
  * Cannot be constructed.
@@ -1472,15 +1648,20 @@ var Fetcher = class {
1472
1648
  constructor() {
1473
1649
  }
1474
1650
  /**
1475
- * Fetch information for a given token on the given chain, using the given ethers provider.
1651
+ * Fetch information for a given token on the given chain, using the given viem provider.
1476
1652
  * @param chainId chain of the token
1477
1653
  * @param address address of the token on the chain
1478
1654
  * @param provider provider used to fetch the token
1479
1655
  * @param symbol symbol of the token
1480
1656
  * @param name optional name of the token
1481
1657
  */
1482
- static async fetchTokenData(chainId, address, provider = getDefaultProvider(getNetwork(chainId)), symbol, name) {
1483
- const parsedDecimals = typeof TOKEN_DECIMALS_CACHE?.[chainId]?.[address] === "number" ? TOKEN_DECIMALS_CACHE[chainId][address] : await new Contract(address, ERC20_default, provider).decimals().then((decimals) => {
1658
+ static async fetchTokenData(chainId, address, publicClient = getDefaultClient(chainId), symbol, name) {
1659
+ const erc20 = getContract({
1660
+ abi: erc20ABI,
1661
+ address,
1662
+ publicClient
1663
+ });
1664
+ const parsedDecimals = typeof TOKEN_DECIMALS_CACHE?.[chainId]?.[address] === "number" ? TOKEN_DECIMALS_CACHE[chainId][address] : await erc20.read.decimals().then((decimals) => {
1484
1665
  TOKEN_DECIMALS_CACHE = {
1485
1666
  ...TOKEN_DECIMALS_CACHE,
1486
1667
  [chainId]: {
@@ -1498,10 +1679,15 @@ var Fetcher = class {
1498
1679
  * @param tokenB second token
1499
1680
  * @param provider the provider to use to fetch the data
1500
1681
  */
1501
- static async fetchPairData(tokenA, tokenB, provider = getDefaultProvider(getNetwork(tokenA.chainId))) {
1502
- invariant4(tokenA.chainId === tokenB.chainId, "CHAIN_ID");
1682
+ static async fetchPairData(tokenA, tokenB, publicClient = getDefaultClient(tokenA.chainId)) {
1683
+ invariant5(tokenA.chainId === tokenB.chainId, "CHAIN_ID");
1503
1684
  const address = Pair.getAddress(tokenA, tokenB);
1504
- const [reserves0, reserves1] = await new Contract(address, IPancakePair_default, provider).getReserves();
1685
+ const pairContract = getContract({
1686
+ abi: pancakePairV2ABI,
1687
+ address,
1688
+ publicClient
1689
+ });
1690
+ const [reserves0, reserves1] = await pairContract.read.getReserves();
1505
1691
  const balances = tokenA.sortsBefore(tokenB) ? [reserves0, reserves1] : [reserves1, reserves0];
1506
1692
  return new Pair(
1507
1693
  CurrencyAmount.fromRawAmount(tokenA, balances[0]),
@@ -1510,4 +1696,4 @@ var Fetcher = class {
1510
1696
  }
1511
1697
  };
1512
1698
 
1513
- export { ChainId, ERC20Token, Ether, FACTORY_ADDRESS, FACTORY_ADDRESS_MAP, Fetcher, INIT_CODE_HASH, INIT_CODE_HASH_MAP, NATIVE, Native, ONE_HUNDRED_PERCENT, Pair, Route, Router, Trade, WBNB, WETH9, WNATIVE, ZERO_PERCENT, computePairAddress, inputOutputComparator, isTradeBetter, tradeComparator, validateAndParseAddress };
1699
+ export { ChainId, ERC20Token, Ether, FACTORY_ADDRESS, FACTORY_ADDRESS_MAP, Fetcher, INIT_CODE_HASH, INIT_CODE_HASH_MAP, NATIVE, Native, ONE_HUNDRED_PERCENT, OnRampCurrency, Pair, Route, Router, Trade, WBNB, WETH9, WNATIVE, ZERO_PERCENT, computePairAddress, inputOutputComparator, isTradeBetter, pancakePairV2ABI, tradeComparator, validateAndParseAddress };
package/dist/router.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { TradeType, Currency, Percent } from '@pancakeswap/swap-sdk-core';
2
+ import { Hex } from 'viem';
2
3
  import { Trade } from './entities';
3
4
  /**
4
5
  * Options for producing the arguments to send call to the router.
@@ -41,11 +42,11 @@ export interface SwapParameters {
41
42
  /**
42
43
  * The arguments to pass to the method, all hex encoded.
43
44
  */
44
- args: (string | string[])[];
45
+ args: (Hex | Hex[])[];
45
46
  /**
46
47
  * The amount of wei to send in hex.
47
48
  */
48
- value: string;
49
+ value: Hex;
49
50
  }
50
51
  /**
51
52
  * Represents the Pancake Router, and has static methods for helping execute trades.
@@ -1 +1 @@
1
- {"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAyB,QAAQ,EAAE,OAAO,EAAE,MAAM,4BAA4B,CAAA;AAEhG,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAA;AAGlC;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B;;OAEG;IACH,eAAe,EAAE,OAAO,CAAA;IACxB;;;;OAIG;IACH,GAAG,EAAE,MAAM,CAAA;IACX;;OAEG;IACH,SAAS,EAAE,MAAM,CAAA;IAEjB;;OAEG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;CACxB;AAED,MAAM,WAAW,oBAAqB,SAAQ,IAAI,CAAC,YAAY,EAAE,KAAK,CAAC;IACrE;;;OAGG;IACH,QAAQ,EAAE,MAAM,CAAA;CACjB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,UAAU,EAAE,MAAM,CAAA;IAClB;;OAEG;IACH,IAAI,EAAE,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC,EAAE,CAAA;IAC3B;;OAEG;IACH,KAAK,EAAE,MAAM,CAAA;CACd;AAQD;;GAEG;AACH,8BAAsB,MAAM;IAC1B;;;;OAIG;WACW,kBAAkB,CAC9B,KAAK,EAAE,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,EAC3C,OAAO,EAAE,YAAY,GAAG,oBAAoB,GAC3C,cAAc;CAuElB"}
1
+ {"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAyB,QAAQ,EAAE,OAAO,EAAE,MAAM,4BAA4B,CAAA;AAEhG,OAAO,EAAW,GAAG,EAAE,MAAM,MAAM,CAAA;AACnC,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAA;AAGlC;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B;;OAEG;IACH,eAAe,EAAE,OAAO,CAAA;IACxB;;;;OAIG;IACH,GAAG,EAAE,MAAM,CAAA;IACX;;OAEG;IACH,SAAS,EAAE,MAAM,CAAA;IAEjB;;OAEG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;CACxB;AAED,MAAM,WAAW,oBAAqB,SAAQ,IAAI,CAAC,YAAY,EAAE,KAAK,CAAC;IACrE;;;OAGG;IACH,QAAQ,EAAE,MAAM,CAAA;CACjB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,UAAU,EAAE,MAAM,CAAA;IAClB;;OAEG;IACH,IAAI,EAAE,CAAC,GAAG,GAAG,GAAG,EAAE,CAAC,EAAE,CAAA;IACrB;;OAEG;IACH,KAAK,EAAE,GAAG,CAAA;CACX;AAQD;;GAEG;AACH,8BAAsB,MAAM;IAC1B;;;;OAIG;WACW,kBAAkB,CAC9B,KAAK,EAAE,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,EAC3C,OAAO,EAAE,YAAY,GAAG,oBAAoB,GAC3C,cAAc;CAuElB"}
package/dist/utils.d.ts CHANGED
@@ -1,2 +1,3 @@
1
- export declare function validateAndParseAddress(address: string): string;
1
+ import { Address } from 'viem';
2
+ export declare function validateAndParseAddress(address: string): Address;
2
3
  //# sourceMappingURL=utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAMA,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAQ/D"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAc,MAAM,MAAM,CAAA;AAM1C,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAQhE"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@pancakeswap/sdk",
3
3
  "license": "MIT",
4
- "version": "4.0.0",
4
+ "version": "5.1.0",
5
5
  "description": "🛠 An SDK for building applications on top of Pancakeswap.",
6
6
  "main": "dist/index.js",
7
7
  "typings": "dist/index.d.ts",
@@ -32,23 +32,10 @@
32
32
  "tiny-invariant": "^1.1.0",
33
33
  "tiny-warning": "^1.0.3",
34
34
  "toformat": "^2.0.0",
35
+ "viem": "^1.2.9",
35
36
  "@pancakeswap/swap-sdk-core": "1.0.0"
36
37
  },
37
- "peerDependencies": {
38
- "@ethersproject/address": "^5.0.0",
39
- "@ethersproject/contracts": "^5.0.0",
40
- "@ethersproject/networks": "^5.0.0",
41
- "@ethersproject/providers": "^5.0.0",
42
- "@ethersproject/solidity": "^5.0.0"
43
- },
44
38
  "devDependencies": {
45
- "@ethersproject/address": "^5.0.0",
46
- "@ethersproject/contracts": "^5.0.0",
47
- "@ethersproject/networks": "^5.0.0",
48
- "@ethersproject/providers": "^5.0.0",
49
- "@ethersproject/solidity": "^5.0.0",
50
- "@swc/core": "^1.2.215",
51
- "@swc/jest": "^0.2.21",
52
39
  "@types/big.js": "^4.0.5",
53
40
  "tsup": "^6.7.0"
54
41
  },