@cryptorubic/web3 0.0.34 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/package.json +15 -2
  2. package/src/index.d.ts +1 -0
  3. package/src/index.js +1 -0
  4. package/src/lib/adapter/adapters/abstract-adapter.d.ts +5 -2
  5. package/src/lib/adapter/adapters/abstract-adapter.js +12 -2
  6. package/src/lib/adapter/adapters/constants/erc20-token-abi.js +12 -12
  7. package/src/lib/adapter/adapters/constants/trc-20-contract-abi.js +15 -15
  8. package/src/lib/adapter/adapters/constants/tron-multicall-abi.js +6 -6
  9. package/src/lib/adapter/adapters/evm-adapter.d.ts +30 -9
  10. package/src/lib/adapter/adapters/evm-adapter.js +121 -28
  11. package/src/lib/adapter/adapters/models/approve-adapter.d.ts +12 -6
  12. package/src/lib/adapter/adapters/models/evm-adapter-options.d.ts +1 -1
  13. package/src/lib/adapter/adapters/models/gas-price.d.ts +22 -0
  14. package/src/lib/adapter/adapters/models/gas-price.js +2 -0
  15. package/src/lib/adapter/adapters/models/ton-adapter-config.d.ts +2 -2
  16. package/src/lib/adapter/adapters/solana-adapter.d.ts +3 -3
  17. package/src/lib/adapter/adapters/solana-adapter.js +1 -1
  18. package/src/lib/adapter/adapters/ton-adapter.d.ts +6 -6
  19. package/src/lib/adapter/adapters/ton-adapter.js +8 -8
  20. package/src/lib/adapter/adapters/tron-adapter.d.ts +13 -14
  21. package/src/lib/adapter/adapters/tron-adapter.js +54 -39
  22. package/src/lib/adapter/adapters/utils/ton-api.service.d.ts +3 -3
  23. package/src/lib/adapter/adapters/utils/ton-api.service.js +4 -3
  24. package/src/lib/adapter/blockchain-adapter-factory.service.d.ts +6 -4
  25. package/src/lib/adapter/blockchain-adapter-factory.service.js +24 -13
  26. package/src/lib/adapter/constants/chain-configs/chain-configs.d.ts +1 -1
  27. package/src/lib/adapter/constants/chain-configs/chain-configs.js +589 -299
  28. package/src/lib/adapter/constants/models/wallet-provider.d.ts +3 -3
  29. package/src/lib/adapter/constants/viem-blockchain-mapping.d.ts +1 -1
  30. package/src/lib/adapter/constants/viem-blockchain-mapping.js +1 -1
  31. package/src/lib/utils/constants/changenow-api-blockchain.js +2 -2
  32. package/src/lib/utils/constants/web3-pure-store.d.ts +2 -2
  33. package/src/lib/utils/constants/web3-pure-store.js +33 -33
  34. package/src/lib/utils/models/contract-multicall-response.d.ts +1 -1
  35. package/src/lib/utils/models/primitive-types.d.ts +1 -1
  36. package/src/lib/utils/models/tron-transaction-config.d.ts +1 -1
  37. package/src/lib/utils/web3-pure.d.ts +2 -2
  38. package/src/lib/utils/web3-pure.js +6 -7
  39. package/src/lib/utils/web3-types/bitcoin-web3-pure.d.ts +1 -1
  40. package/src/lib/utils/web3-types/common-web3-pure.js +0 -2
  41. package/src/lib/utils/web3-types/evm-web3-pure.d.ts +1 -1
  42. package/src/lib/utils/web3-types/icp-web3-pure.d.ts +1 -1
  43. package/src/lib/utils/web3-types/icp-web3-pure.js +2 -1
  44. package/src/lib/utils/web3-types/solana-web3-pure.d.ts +1 -1
  45. package/src/lib/utils/web3-types/solana-web3-pure.js +1 -1
  46. package/src/lib/utils/web3-types/ton-web3-pure.d.ts +1 -1
  47. package/src/lib/utils/web3-types/ton-web3-pure.js +1 -1
  48. package/src/lib/utils/web3-types/tron-web3-pure.d.ts +7 -4
  49. package/src/lib/utils/web3-types/tron-web3-pure.js +22 -6
package/package.json CHANGED
@@ -1,8 +1,21 @@
1
1
  {
2
2
  "name": "@cryptorubic/web3",
3
- "version": "0.0.34",
3
+ "version": "0.2.1",
4
4
  "dependencies": {
5
- "tslib": "^2.3.0"
5
+ "tslib": "^2.3.0",
6
+ "bignumber.js": "9.1.2",
7
+ "@cryptorubic/core": "0.2.1",
8
+ "viem": "^2.19.1",
9
+ "web3-utils": "^4.3.1",
10
+ "@ton/ton": "^15.1.0",
11
+ "@solana/web3.js": "1.95.3",
12
+ "@solflare-wallet/utl-sdk": "^1.4.0",
13
+ "@ethersproject/bignumber": "^5.7.0",
14
+ "@cryptorubic/tron-types": "0.2.1",
15
+ "bitcoin-address-validation": "^2.2.3",
16
+ "axios": "0.27.2",
17
+ "crc-32": "^1.2.2",
18
+ "tronweb": "^6.0.0-beta.4"
6
19
  },
7
20
  "type": "commonjs",
8
21
  "main": "./src/index.js",
package/src/index.d.ts CHANGED
@@ -22,6 +22,7 @@ export * from './lib/adapter/adapters/models/ton-api-config';
22
22
  export * from './lib/adapter/adapters/models/tonapi-models';
23
23
  export * from './lib/adapter/adapters/models/toncenter-types';
24
24
  export * from './lib/adapter/adapters/models/approve-adapter';
25
+ export * from './lib/adapter/adapters/models/gas-price';
25
26
  export * from './lib/utils/web3-pure';
26
27
  export * from './lib/utils/models/evm-transaction-config';
27
28
  export * from './lib/utils/web3-types/bitcoin-web3-pure';
package/src/index.js CHANGED
@@ -22,6 +22,7 @@ tslib_1.__exportStar(require("./lib/adapter/adapters/models/ton-api-config"), ex
22
22
  tslib_1.__exportStar(require("./lib/adapter/adapters/models/tonapi-models"), exports);
23
23
  tslib_1.__exportStar(require("./lib/adapter/adapters/models/toncenter-types"), exports);
24
24
  tslib_1.__exportStar(require("./lib/adapter/adapters/models/approve-adapter"), exports);
25
+ tslib_1.__exportStar(require("./lib/adapter/adapters/models/gas-price"), exports);
25
26
  // utils aka web3pure
26
27
  tslib_1.__exportStar(require("./lib/utils/web3-pure"), exports);
27
28
  tslib_1.__exportStar(require("./lib/utils/models/evm-transaction-config"), exports);
@@ -1,5 +1,5 @@
1
- import BigNumber from "bignumber.js";
2
- import { ICustomLogger, Token, TokenAmount, BlockchainName } from "@cryptorubic/core";
1
+ import BigNumber from 'bignumber.js';
2
+ import { ICustomLogger, Token, TokenAmount, BlockchainName } from '@cryptorubic/core';
3
3
  export declare abstract class AbstractAdapter<P, W, B extends BlockchainName> {
4
4
  protected readonly logger?: ICustomLogger;
5
5
  protected readonly blockchain: B;
@@ -9,6 +9,9 @@ export declare abstract class AbstractAdapter<P, W, B extends BlockchainName> {
9
9
  private _wallet;
10
10
  set wallet(value: W | null);
11
11
  get wallet(): W;
12
+ private _walletAddress;
13
+ set walletAddress(value: string | null);
14
+ get walletAddress(): string;
12
15
  protected constructor(blockchain: B, logger?: ICustomLogger);
13
16
  abstract callForTokensInfo(tokenAddresses: string[] | ReadonlyArray<string>): Promise<Token<BlockchainName>[]>;
14
17
  needPreswapAction(token: TokenAmount, contractAddress: string, walletAddress: string, amount: string | BigNumber): Promise<boolean>;
@@ -25,9 +25,21 @@ class AbstractAdapter {
25
25
  }
26
26
  return this._wallet;
27
27
  }
28
+ set walletAddress(value) {
29
+ this._walletAddress = value;
30
+ }
31
+ get walletAddress() {
32
+ if (!this._walletAddress) {
33
+ const msg = 'Trying to access undefined walletAddress';
34
+ this.logger?.customLog(msg);
35
+ throw new Error(msg);
36
+ }
37
+ return this._walletAddress;
38
+ }
28
39
  constructor(blockchain, logger) {
29
40
  this._public = null;
30
41
  this._wallet = null;
42
+ this._walletAddress = null;
31
43
  this.blockchain = blockchain;
32
44
  if (logger) {
33
45
  this.logger = logger;
@@ -36,11 +48,9 @@ class AbstractAdapter {
36
48
  needPreswapAction(token, contractAddress, walletAddress, amount) {
37
49
  return Promise.resolve(false);
38
50
  }
39
- ;
40
51
  handlePreswap(contractAddress, walletAddress, tokenAmount) {
41
52
  return Promise.resolve();
42
53
  }
43
- ;
44
54
  static getRandomBytes(bytes) {
45
55
  const randomBytes = crypto.getRandomValues(new Uint8Array(bytes));
46
56
  return (0, viem_1.bytesToHex)(randomBytes);
@@ -9,19 +9,19 @@ exports.erc20TokenAbi = [
9
9
  outputs: [{ name: '', type: 'string' }],
10
10
  payable: false,
11
11
  stateMutability: 'view',
12
- type: 'function'
12
+ type: 'function',
13
13
  },
14
14
  {
15
15
  constant: false,
16
16
  inputs: [
17
17
  { name: '_spender', type: 'address' },
18
- { name: '_value', type: 'uint256' }
18
+ { name: '_value', type: 'uint256' },
19
19
  ],
20
20
  name: 'approve',
21
21
  outputs: [],
22
22
  payable: false,
23
23
  stateMutability: 'nonpayable',
24
- type: 'function'
24
+ type: 'function',
25
25
  },
26
26
  {
27
27
  constant: true,
@@ -30,7 +30,7 @@ exports.erc20TokenAbi = [
30
30
  outputs: [{ name: '', type: 'uint256' }],
31
31
  payable: false,
32
32
  stateMutability: 'view',
33
- type: 'function'
33
+ type: 'function',
34
34
  },
35
35
  {
36
36
  constant: true,
@@ -39,7 +39,7 @@ exports.erc20TokenAbi = [
39
39
  outputs: [{ name: '', type: 'uint256' }],
40
40
  payable: false,
41
41
  stateMutability: 'view',
42
- type: 'function'
42
+ type: 'function',
43
43
  },
44
44
  {
45
45
  constant: true,
@@ -48,7 +48,7 @@ exports.erc20TokenAbi = [
48
48
  outputs: [{ name: '', type: 'uint256' }],
49
49
  payable: false,
50
50
  stateMutability: 'view',
51
- type: 'function'
51
+ type: 'function',
52
52
  },
53
53
  {
54
54
  constant: true,
@@ -57,30 +57,30 @@ exports.erc20TokenAbi = [
57
57
  outputs: [{ name: '', type: 'string' }],
58
58
  payable: false,
59
59
  stateMutability: 'view',
60
- type: 'function'
60
+ type: 'function',
61
61
  },
62
62
  {
63
63
  constant: false,
64
64
  inputs: [
65
65
  { name: '_to', type: 'address' },
66
- { name: '_value', type: 'uint256' }
66
+ { name: '_value', type: 'uint256' },
67
67
  ],
68
68
  name: 'transfer',
69
69
  outputs: [],
70
70
  payable: false,
71
71
  stateMutability: 'nonpayable',
72
- type: 'function'
72
+ type: 'function',
73
73
  },
74
74
  {
75
75
  constant: true,
76
76
  inputs: [
77
77
  { name: '_owner', type: 'address' },
78
- { name: '_spender', type: 'address' }
78
+ { name: '_spender', type: 'address' },
79
79
  ],
80
80
  name: 'allowance',
81
81
  outputs: [{ name: 'remaining', type: 'uint256' }],
82
82
  payable: false,
83
83
  stateMutability: 'view',
84
- type: 'function'
85
- }
84
+ type: 'function',
85
+ },
86
86
  ];
@@ -7,65 +7,65 @@ exports.TRC20_CONTRACT_ABI = [
7
7
  name: 'symbol',
8
8
  outputs: [{ type: 'string' }],
9
9
  stateMutability: 'view',
10
- type: 'function'
10
+ type: 'function',
11
11
  },
12
12
  {
13
13
  inputs: [
14
14
  { name: 'owner', type: 'address' },
15
- { name: 'spender', type: 'address' }
15
+ { name: 'spender', type: 'address' },
16
16
  ],
17
17
  name: 'allowance',
18
18
  outputs: [{ type: 'uint256' }],
19
19
  stateMutability: 'view',
20
- type: 'function'
20
+ type: 'function',
21
21
  },
22
22
  {
23
23
  inputs: [
24
24
  { name: 'spender', type: 'address' },
25
- { name: 'value', type: 'uint256' }
25
+ { name: 'value', type: 'uint256' },
26
26
  ],
27
27
  name: 'approve',
28
28
  outputs: [{ type: 'bool' }],
29
29
  stateMutability: 'nonpayable',
30
- type: 'function'
30
+ type: 'function',
31
31
  },
32
32
  {
33
33
  inputs: [{ name: 'account', type: 'address' }],
34
34
  name: 'balanceOf',
35
35
  outputs: [{ type: 'uint256' }],
36
36
  stateMutability: 'view',
37
- type: 'function'
37
+ type: 'function',
38
38
  },
39
39
  {
40
40
  inputs: [],
41
41
  name: 'decimals',
42
42
  outputs: [{ type: 'uint8' }],
43
43
  stateMutability: 'view',
44
- type: 'function'
44
+ type: 'function',
45
45
  },
46
46
  {
47
47
  inputs: [],
48
48
  name: 'name',
49
49
  outputs: [{ type: 'string' }],
50
50
  stateMutability: 'view',
51
- type: 'function'
51
+ type: 'function',
52
52
  },
53
53
  {
54
54
  inputs: [],
55
55
  name: 'totalSupply',
56
56
  outputs: [{ type: 'uint256' }],
57
57
  stateMutability: 'view',
58
- type: 'function'
58
+ type: 'function',
59
59
  },
60
60
  {
61
61
  inputs: [
62
62
  { name: 'to', type: 'address' },
63
- { name: 'value', type: 'uint256' }
63
+ { name: 'value', type: 'uint256' },
64
64
  ],
65
65
  name: 'transfer',
66
66
  outputs: [{ type: 'bool' }],
67
67
  stateMutability: 'nonpayable',
68
- type: 'function'
68
+ type: 'function',
69
69
  },
70
70
  {
71
71
  inputs: [
@@ -73,12 +73,12 @@ exports.TRC20_CONTRACT_ABI = [
73
73
  { name: 'to', type: 'address' },
74
74
  {
75
75
  name: 'value',
76
- type: 'uint256'
77
- }
76
+ type: 'uint256',
77
+ },
78
78
  ],
79
79
  name: 'transferFrom',
80
80
  outputs: [{ type: 'bool' }],
81
81
  stateMutability: 'nonpayable',
82
- type: 'function'
83
- }
82
+ type: 'function',
83
+ },
84
84
  ];
@@ -7,20 +7,20 @@ exports.TRON_MULTICALL_ABI = [
7
7
  {
8
8
  components: [
9
9
  { internalType: 'address', name: 'target', type: 'address' },
10
- { internalType: 'bytes', name: 'callData', type: 'bytes' }
10
+ { internalType: 'bytes', name: 'callData', type: 'bytes' },
11
11
  ],
12
12
  internalType: 'struct Multicall.Call[]',
13
13
  name: 'calls',
14
- type: 'tuple[]'
15
- }
14
+ type: 'tuple[]',
15
+ },
16
16
  ],
17
17
  name: 'aggregateViewCalls',
18
18
  outputs: [
19
19
  { internalType: 'uint256', name: 'blockNumber', type: 'uint256' },
20
20
  { internalType: 'bytes[]', name: 'returnData', type: 'bytes[]' },
21
- { internalType: 'bool[]', name: 'results', type: 'bool[]' }
21
+ { internalType: 'bool[]', name: 'results', type: 'bool[]' },
22
22
  ],
23
23
  stateMutability: 'view',
24
- type: 'function'
25
- }
24
+ type: 'function',
25
+ },
26
26
  ];
@@ -1,23 +1,24 @@
1
- import { Abi, MulticallResponse, MulticallParameters, PublicActions, PublicClient, WalletClient, WalletActions } from 'viem';
1
+ import { Abi, MulticallResponse, MulticallParameters, PublicActions, PublicClient, WalletClient, WalletActions, BlockNumber, BlockTag, GetBlockReturnType } from 'viem';
2
2
  import { AbstractAdapter } from './abstract-adapter';
3
3
  import { EvmBlockchainName, ICustomLogger, Token, TokenAmount, PriceTokenAmount } from '@cryptorubic/core';
4
- import BigNumber from "bignumber.js";
5
- import { EvmAdapterOptions } from "./models/evm-adapter-options";
6
- import { EvmTransactionConfig } from "../../utils/models/evm-transaction-config";
7
- import { ApproveAdapter } from "./models/approve-adapter";
8
- import { AllowanceInfo } from "./models/common-types";
9
- export declare class EvmAdapter extends AbstractAdapter<PublicActions & PublicClient, WalletClient & WalletActions, EvmBlockchainName> implements ApproveAdapter {
4
+ import BigNumber from 'bignumber.js';
5
+ import { EvmAdapterOptions } from './models/evm-adapter-options';
6
+ import { EvmTransactionConfig } from '../../utils/models/evm-transaction-config';
7
+ import { ApproveAdapter } from './models/approve-adapter';
8
+ import { AllowanceInfo } from './models/common-types';
9
+ import { GasPrice } from './models/gas-price';
10
+ export declare class EvmAdapter extends AbstractAdapter<PublicActions & PublicClient, WalletClient & WalletActions, EvmBlockchainName> implements ApproveAdapter<EvmTransactionConfig> {
10
11
  needPreswapAction(token: TokenAmount, contractAddress: string, walletAddress: string, amount: string): Promise<boolean>;
11
12
  handlePreswap(contractAddress: string, walletAddress: string, tokenAmount: TokenAmount): Promise<void>;
12
13
  constructor(adapterOptions: EvmAdapterOptions, logger?: ICustomLogger);
13
- protected createPublicClient(rpcList: string[]): PublicActions & PublicClient | null;
14
+ protected createPublicClient(rpcList: string[]): (PublicActions & PublicClient) | null;
14
15
  read<T>(address: string, abi: Abi, method: string, methodArgs?: unknown[]): Promise<T>;
15
16
  writeContract(address: string, abi: Abi, method: string, value?: string, methodArgs?: unknown[]): Promise<string>;
16
17
  write(address: string, to: string, value: string, data: string): Promise<string>;
17
18
  multicallByContract<T>(contracts: MulticallParameters, allowErrors?: boolean): Promise<MulticallResponse<T>[]>;
18
19
  multicallByAddress<T>(address: string, abi: Abi, method: string, methodArgs?: unknown[][], allowErrors?: boolean): Promise<MulticallResponse<T>[]>;
19
20
  static encodeMethodCall(contractAddress: string, contractAbi: Abi, method: string, parameters?: unknown[], value?: string): EvmTransactionConfig;
20
- simulateTransaction(config: EvmTransactionConfig, from: string): Promise<void>;
21
+ simulateTransaction(config: EvmTransactionConfig, from: string): Promise<string>;
21
22
  callForTokensInfo(tokenAddresses: string[] | ReadonlyArray<string>): Promise<Token<EvmBlockchainName>[]>;
22
23
  getGasPrice(): Promise<string>;
23
24
  checkEnoughBalance(token: TokenAmount | PriceTokenAmount, walletAddress: string, amount?: BigNumber): Promise<boolean>;
@@ -31,4 +32,24 @@ export declare class EvmAdapter extends AbstractAdapter<PublicActions & PublicCl
31
32
  getAllowance(fromTokenAddress: string, walletAddress: string, spenderAddress: string): Promise<AllowanceInfo>;
32
33
  encodeApprove(tokenAddress: string, spenderAddress: string, amount?: string): EvmTransactionConfig;
33
34
  needApprove(token: TokenAmount, contractAddress: string, walletAddress: string, amount: string): Promise<boolean>;
35
+ approve(fromAddress: string, tokenAddress: string, spenderAddress: string, amount?: string): Promise<string>;
36
+ /**
37
+ * Calculates EIP-1559 specific gas details.
38
+ * @see {@link https://github.com/ethers-io/ethers.js/blob/master/packages/abstract-provider/src.ts/index.ts#L235}
39
+ * @returns block baseFee, average maxPriorityFeePerGas, and maxFeePerGas.
40
+ */
41
+ getPriorityFeeGas(): Promise<GasPrice>;
42
+ /**
43
+ * Gets block by block id.
44
+ * @param [blockId] Block id: hash, number ... Default is 'latest'.
45
+ * @returns Block by blockId parameter.
46
+ */
47
+ getBlock(blockType?: BlockNumber | BlockTag): Promise<GetBlockReturnType>;
48
+ /**
49
+ * Estimates average maxPriorityFeePerGas for EIP-1559 transactions based on last 20 blocks.
50
+ * @see {@link https://docs.alchemy.com/docs/how-to-build-a-gas-fee-estimator-using-eip-1559}
51
+ * @returns Average maxPriorityFeePerGas in wei
52
+ */
53
+ getMaxPriorityFeePerGas(): Promise<number>;
54
+ getBaseFeePerGas(blockNumber: bigint): Promise<number>;
34
55
  }
@@ -21,13 +21,13 @@ class EvmAdapter extends abstract_adapter_1.AbstractAdapter {
21
21
  const fromTokenAddress = isNative && tokenAmount.blockchain === core_1.BLOCKCHAIN_NAME.METIS
22
22
  ? '0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000'
23
23
  : tokenAmount.blockchain;
24
- await this.writeContract(fromTokenAddress, erc20_token_abi_1.erc20TokenAbi, 'approve', '0', [approveAmount]);
24
+ await this.writeContract(fromTokenAddress, erc20_token_abi_1.erc20TokenAbi, 'approve', '0', [
25
+ approveAmount,
26
+ ]);
25
27
  }
26
28
  constructor(adapterOptions, logger) {
27
29
  super(adapterOptions.blockchain, logger);
28
30
  this.public = this.createPublicClient(adapterOptions.rpcList);
29
- if (adapterOptions?.walletAddress) {
30
- }
31
31
  }
32
32
  createPublicClient(rpcList) {
33
33
  if (!rpcList?.[0]) {
@@ -43,15 +43,15 @@ class EvmAdapter extends abstract_adapter_1.AbstractAdapter {
43
43
  },
44
44
  retryCount: 5,
45
45
  retryDelay: 100,
46
- timeout: 5000
46
+ timeout: 5000,
47
47
  }));
48
48
  const chain = viem_blockchain_mapping_1.viemBlockchainMapping[this.blockchain];
49
49
  return (0, viem_1.createPublicClient)({
50
50
  // @ts-ignore
51
51
  chain,
52
52
  transport: (0, viem_1.fallback)(transports, {
53
- rank: true
54
- })
53
+ rank: true,
54
+ }),
55
55
  });
56
56
  }
57
57
  async read(address, abi, method, methodArgs = []) {
@@ -59,7 +59,7 @@ class EvmAdapter extends abstract_adapter_1.AbstractAdapter {
59
59
  abi,
60
60
  address: address,
61
61
  args: methodArgs,
62
- functionName: method
62
+ functionName: method,
63
63
  });
64
64
  return result;
65
65
  }
@@ -71,7 +71,7 @@ class EvmAdapter extends abstract_adapter_1.AbstractAdapter {
71
71
  args: methodArgs,
72
72
  functionName: method,
73
73
  chain: this.public.chain,
74
- value: (0, viem_1.parseEther)(value)
74
+ value: (0, viem_1.parseEther)(value),
75
75
  });
76
76
  return result;
77
77
  }
@@ -81,7 +81,7 @@ class EvmAdapter extends abstract_adapter_1.AbstractAdapter {
81
81
  to: to,
82
82
  value: (0, viem_1.parseEther)(value),
83
83
  data: data,
84
- chain: this.public.chain
84
+ chain: this.public.chain,
85
85
  });
86
86
  return result;
87
87
  }
@@ -97,7 +97,9 @@ class EvmAdapter extends abstract_adapter_1.AbstractAdapter {
97
97
  }
98
98
  const hasErrors = results.find((result) => {
99
99
  if (result?.error || result.status !== 'success') {
100
- this.logger?.customWarn('Multicall error', result?.error?.data || result?.error?.message || result?.error);
100
+ this.logger?.customWarn('Multicall error', result?.error?.data ||
101
+ result?.error?.message ||
102
+ result?.error);
101
103
  return true;
102
104
  }
103
105
  return false;
@@ -108,20 +110,28 @@ class EvmAdapter extends abstract_adapter_1.AbstractAdapter {
108
110
  return results;
109
111
  }
110
112
  async multicallByAddress(address, abi, method, methodArgs = [], allowErrors = true) {
111
- const contract = { abi, address: address, functionName: method };
113
+ const contract = {
114
+ abi,
115
+ address: address,
116
+ functionName: method,
117
+ };
112
118
  const contracts = methodArgs.map((multicallArguments) => ({
113
119
  ...contract,
114
- args: multicallArguments
120
+ args: multicallArguments,
115
121
  }));
116
122
  return this.multicallByContract({ contracts }, allowErrors);
117
123
  }
118
124
  static encodeMethodCall(contractAddress, contractAbi, method, parameters = [], value) {
119
125
  try {
120
- const data = (0, viem_1.encodeFunctionData)({ abi: contractAbi, args: parameters, functionName: method });
126
+ const data = (0, viem_1.encodeFunctionData)({
127
+ abi: contractAbi,
128
+ args: parameters,
129
+ functionName: method,
130
+ });
121
131
  return {
122
132
  data: data,
123
133
  to: contractAddress,
124
- value: value || '0'
134
+ value: value || '0',
125
135
  };
126
136
  }
127
137
  catch (err) {
@@ -134,10 +144,10 @@ class EvmAdapter extends abstract_adapter_1.AbstractAdapter {
134
144
  account: from,
135
145
  data: config.data,
136
146
  to: config.to,
137
- ...(config.value && { value: BigInt(config.value) })
147
+ ...(config.value && { value: BigInt(config.value) }),
138
148
  };
139
- // @ts-ignore
140
- await this.core.call(callParams);
149
+ const gasLimitWei = await this.public.estimateGas(callParams);
150
+ return gasLimitWei.toString();
141
151
  }
142
152
  catch (err) {
143
153
  this.logger?.customError('Error while simulating transaction', err);
@@ -150,11 +160,15 @@ class EvmAdapter extends abstract_adapter_1.AbstractAdapter {
150
160
  const contracts = filteredTokenAddresses.flatMap((contractAddress) => {
151
161
  const contract = {
152
162
  abi: erc20_token_abi_1.erc20TokenAbi,
153
- address: contractAddress
163
+ address: contractAddress,
154
164
  };
155
165
  return ['decimals', 'symbol', 'name'].map((method) => ({ ...contract, functionName: method }));
156
166
  });
157
- const results = contracts.length ? (await this.multicallByContract({ contracts })) : [];
167
+ const results = contracts.length
168
+ ? (await this.multicallByContract({
169
+ contracts,
170
+ }))
171
+ : [];
158
172
  const tokens = [];
159
173
  for (let i = 0; i < results.length; i += 3) {
160
174
  try {
@@ -166,7 +180,7 @@ class EvmAdapter extends abstract_adapter_1.AbstractAdapter {
166
180
  blockchain: this.blockchain,
167
181
  decimals,
168
182
  name,
169
- symbol
183
+ symbol,
170
184
  });
171
185
  tokens.push(token);
172
186
  }
@@ -199,7 +213,7 @@ class EvmAdapter extends abstract_adapter_1.AbstractAdapter {
199
213
  async getBalance(walletAddress, tokenAddress) {
200
214
  if (!tokenAddress) {
201
215
  const nativeBalance = await this.public.getBalance({
202
- address: walletAddress
216
+ address: walletAddress,
203
217
  });
204
218
  return new bignumber_js_1.default(nativeBalance.toString());
205
219
  }
@@ -208,40 +222,119 @@ class EvmAdapter extends abstract_adapter_1.AbstractAdapter {
208
222
  }
209
223
  async getTransactionCount(walletAddress) {
210
224
  const transactionCount = await this.public?.getTransactionCount({
211
- address: walletAddress
225
+ address: walletAddress,
212
226
  });
213
227
  return transactionCount ?? 0;
214
228
  }
215
229
  async getAllowance(fromTokenAddress, walletAddress, spenderAddress) {
216
230
  const [decimals, allowance] = await Promise.all([
217
231
  this.read(fromTokenAddress, erc20_token_abi_1.erc20TokenAbi, 'decimals'),
218
- this.read(fromTokenAddress, erc20_token_abi_1.erc20TokenAbi, 'allowance', [walletAddress, spenderAddress])
232
+ this.read(fromTokenAddress, erc20_token_abi_1.erc20TokenAbi, 'allowance', [
233
+ walletAddress,
234
+ spenderAddress,
235
+ ]),
219
236
  ]);
220
237
  const allowanceWeiBN = new bignumber_js_1.default(allowance);
221
238
  const allowanceNonWei = core_1.Token.fromWei(allowanceWeiBN, Number(decimals));
222
239
  return { allowanceNonWei, allowanceWei: allowanceWeiBN };
223
240
  }
224
- ;
225
241
  encodeApprove(tokenAddress, spenderAddress, amount) {
226
242
  const amountWei = amount ?? new bignumber_js_1.default(2).pow(256).minus(1).toFixed();
227
243
  const tx = EvmAdapter.encodeMethodCall(tokenAddress, erc20_token_abi_1.erc20TokenAbi, 'approve', [spenderAddress, amountWei]);
228
244
  return {
229
245
  data: tx.data,
230
246
  to: tx.to,
231
- value: tx.value
247
+ value: tx.value,
232
248
  };
233
249
  }
234
- ;
235
250
  async needApprove(token, contractAddress, walletAddress, amount) {
236
251
  // Native coin in METIS can be Token required approve
237
252
  if (token.isNative && token.blockchain !== core_1.BLOCKCHAIN_NAME.METIS) {
238
253
  return false;
239
254
  }
240
255
  // Special native address for METIS native coin
241
- const fromTokenAddress = token.isNative && token.blockchain === core_1.BLOCKCHAIN_NAME.METIS ? '0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000' : token.address;
256
+ const fromTokenAddress = token.isNative && token.blockchain === core_1.BLOCKCHAIN_NAME.METIS
257
+ ? '0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000'
258
+ : token.address;
242
259
  const { allowanceWei } = await this.getAllowance(fromTokenAddress, walletAddress, contractAddress);
243
260
  return allowanceWei.lt(token.weiAmount);
244
261
  }
245
- ;
262
+ async approve(fromAddress, tokenAddress, spenderAddress, amount) {
263
+ const config = this.encodeApprove(tokenAddress, spenderAddress, amount);
264
+ return this.write(fromAddress, config.to, config.value, config.data);
265
+ }
266
+ /**
267
+ * Calculates EIP-1559 specific gas details.
268
+ * @see {@link https://github.com/ethers-io/ethers.js/blob/master/packages/abstract-provider/src.ts/index.ts#L235}
269
+ * @returns block baseFee, average maxPriorityFeePerGas, and maxFeePerGas.
270
+ */
271
+ async getPriorityFeeGas() {
272
+ const block = await this.getBlock('latest');
273
+ let lastBaseFeePerGas = null;
274
+ let maxFeePerGas = null;
275
+ let maxPriorityFeePerGas = null;
276
+ if (block && block.baseFeePerGas) {
277
+ const baseFeePerGas = await this.getBaseFeePerGas(block.number);
278
+ try {
279
+ lastBaseFeePerGas = baseFeePerGas;
280
+ maxPriorityFeePerGas = await this.getMaxPriorityFeePerGas();
281
+ maxFeePerGas = baseFeePerGas * 2 + maxPriorityFeePerGas;
282
+ }
283
+ catch (err) {
284
+ console.debug(err);
285
+ }
286
+ }
287
+ return {
288
+ baseFee: lastBaseFeePerGas?.toFixed(),
289
+ maxFeePerGas: maxFeePerGas?.toFixed(),
290
+ maxPriorityFeePerGas: maxPriorityFeePerGas?.toFixed(),
291
+ };
292
+ }
293
+ /**
294
+ * Gets block by block id.
295
+ * @param [blockId] Block id: hash, number ... Default is 'latest'.
296
+ * @returns Block by blockId parameter.
297
+ */
298
+ getBlock(blockType = 'latest') {
299
+ if (typeof blockType === 'string') {
300
+ // @TODO FIX TYPE
301
+ return this.public.getBlock({ blockTag: blockType });
302
+ }
303
+ return this.public.getBlock({ blockNumber: blockType });
304
+ }
305
+ /**
306
+ * Estimates average maxPriorityFeePerGas for EIP-1559 transactions based on last 20 blocks.
307
+ * @see {@link https://docs.alchemy.com/docs/how-to-build-a-gas-fee-estimator-using-eip-1559}
308
+ * @returns Average maxPriorityFeePerGas in wei
309
+ */
310
+ async getMaxPriorityFeePerGas() {
311
+ const HISTORICAL_BLOCKS = 20;
312
+ const feeHistory = await this.public.getFeeHistory({
313
+ blockCount: HISTORICAL_BLOCKS,
314
+ rewardPercentiles: [50],
315
+ blockTag: 'pending',
316
+ });
317
+ if (!feeHistory?.reward) {
318
+ throw new Error('No fee history found');
319
+ }
320
+ const blocks = feeHistory.reward.map((x) => x.map((reward) => Number(reward)));
321
+ const rewardSum = blocks
322
+ .map((x) => x[0])
323
+ .reduce((acc, v) => acc + (v || 0), 0);
324
+ return Math.round(rewardSum / blocks.length);
325
+ }
326
+ async getBaseFeePerGas(blockNumber) {
327
+ const feeHistory = await this.public.getFeeHistory({
328
+ blockCount: 1,
329
+ rewardPercentiles: [50],
330
+ // blockTag: 'pending',
331
+ blockNumber: blockNumber,
332
+ });
333
+ if (!feeHistory?.baseFeePerGas.length) {
334
+ throw new Error('No fee history found');
335
+ }
336
+ const feedSum = feeHistory.baseFeePerGas.reduce((acc, v) => acc.plus(v.toString() || 0), new bignumber_js_1.default(0));
337
+ return feedSum.dividedBy(feeHistory.baseFeePerGas.length).toNumber();
338
+ }
246
339
  }
247
340
  exports.EvmAdapter = EvmAdapter;