@cryptorubic/web3 0.8.17-alpha.solana.18 → 0.8.17-alpha.solana.19

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cryptorubic/web3",
3
- "version": "0.8.17-alpha.solana.18",
3
+ "version": "0.8.17-alpha.solana.19",
4
4
  "dependencies": {
5
5
  "@ethersproject/bignumber": "^5.8.0",
6
6
  "@mysten/sui": "^1.24.0",
@@ -8,6 +8,7 @@ export declare class SolanaGasService {
8
8
  private readonly logger;
9
9
  private readonly HELIUS_API_URL;
10
10
  private readonly HELIUS_API_KEY;
11
+ readonly DEFAULT_CU_LIMIT = 200000;
11
12
  constructor(httpClient: HttpClient, connection: Connection, logger: ICustomLogger | undefined, solanaConfig: SolanaAdapterConfig);
12
13
  /**
13
14
  * @returns wei ComputedUnitsLimit - like gasLimit in evm
@@ -15,15 +16,12 @@ export declare class SolanaGasService {
15
16
  getConsumedUnitsLimit(txData: string): Promise<BigNumber>;
16
17
  /**
17
18
  * @param txData base64 or hex string
18
- * @returns consumedUnitsPrice in micro-lamports(lamport * 10^-6)
19
- */
20
- getConsumedUnitsPrice(txData: string): Promise<BigNumber>;
21
- /**
22
- * @returns consumedUnitsPrice in micro-lamports(lamport * 10^-6)
19
+ * @returns prioritizationFee in micro-lamports (lamport = 1_000_000 microlamports)
23
20
  */
24
- private calculateCUPriceHelius;
21
+ getPriorityFee(txData: string): Promise<BigNumber>;
25
22
  /**
26
23
  * @returns consumedUnitsPrice in micro-lamports(lamport * 10^-6)
27
24
  */
28
- private calculateCUPriceSolWeb3;
25
+ private calculatePriorityFeeHelius;
26
+ private getRecentPriorityFeeSolWeb3;
29
27
  }
@@ -1,19 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SolanaGasService = void 0;
4
- const web3_js_1 = require("@solana/web3.js");
5
4
  const utils_1 = require("ethers/lib/utils");
6
5
  const utility_funcs_1 = require("./utility-funcs");
7
6
  const bignumber_js_1 = require("bignumber.js");
8
- const timeout_1 = require("../timeout");
9
- const DEFAULT_CU_LIMIT = 200_000; // lamports
10
- const DEFAULT_CU_PRICE = 1_000_000; // micro-lamports
7
+ // solana gas fee FORMULA: 200_000 CU * 0.02 Lamports/CU = 4000 Lamports = 0.000004 SOL
11
8
  class SolanaGasService {
12
9
  httpClient;
13
10
  connection;
14
11
  logger;
15
12
  HELIUS_API_URL = 'https://mainnet.helius-rpc.com';
16
13
  HELIUS_API_KEY;
14
+ DEFAULT_CU_LIMIT = 200_000; //in CU
17
15
  constructor(httpClient, connection, logger, solanaConfig) {
18
16
  this.httpClient = httpClient;
19
17
  this.connection = connection;
@@ -29,22 +27,22 @@ class SolanaGasService {
29
27
  const resp = await this.connection.simulateTransaction(tx, {
30
28
  replaceRecentBlockhash: true
31
29
  });
32
- return resp.value.unitsConsumed ? new bignumber_js_1.default(resp.value.unitsConsumed * 1.2) : new bignumber_js_1.default(DEFAULT_CU_LIMIT);
30
+ return resp.value.unitsConsumed ? new bignumber_js_1.default(resp.value.unitsConsumed * 1.2) : new bignumber_js_1.default(this.DEFAULT_CU_LIMIT);
33
31
  }
34
32
  catch (err) {
35
33
  console.error('[SolanaApiService_getConsumedUnitsLimit] err ==> ', err);
36
- return new bignumber_js_1.default(DEFAULT_CU_LIMIT);
34
+ return new bignumber_js_1.default(this.DEFAULT_CU_LIMIT);
37
35
  }
38
36
  }
39
37
  /**
40
38
  * @param txData base64 or hex string
41
- * @returns consumedUnitsPrice in micro-lamports(lamport * 10^-6)
39
+ * @returns prioritizationFee in micro-lamports (lamport = 1_000_000 microlamports)
42
40
  */
43
- async getConsumedUnitsPrice(txData) {
41
+ async getPriorityFee(txData) {
44
42
  if (!this.HELIUS_API_KEY) {
45
43
  console.warn('[SolanaApiService_getConsumedUnitsPrice] heliusApiKey is not provided in "createFactory"');
46
44
  }
47
- const resp = await Promise.allSettled([this.calculateCUPriceHelius(txData), this.calculateCUPriceSolWeb3()]);
45
+ const resp = await Promise.allSettled([this.calculatePriorityFeeHelius(txData), this.getRecentPriorityFeeSolWeb3()]);
48
46
  const cuPrice = resp
49
47
  .filter((r) => r.status === 'fulfilled')
50
48
  .map((r) => r.value)
@@ -54,7 +52,7 @@ class SolanaGasService {
54
52
  /**
55
53
  * @returns consumedUnitsPrice in micro-lamports(lamport * 10^-6)
56
54
  */
57
- async calculateCUPriceHelius(txData) {
55
+ async calculatePriorityFeeHelius(txData) {
58
56
  try {
59
57
  const tx = (0, utility_funcs_1.convertB64DataToTx)(txData);
60
58
  const resp = await this.httpClient.post(`${this.HELIUS_API_URL}/?api-key=${this.HELIUS_API_KEY}`, {
@@ -76,51 +74,31 @@ class SolanaGasService {
76
74
  return new bignumber_js_1.default(0);
77
75
  }
78
76
  }
79
- /**
80
- * @returns consumedUnitsPrice in micro-lamports(lamport * 10^-6)
81
- */
82
- async calculateCUPriceSolWeb3() {
83
- const estimateCULimitForTx = async (tx, idx) => {
84
- if (!tx || !tx.message)
85
- return { success: false, cuLimit: new bignumber_js_1.default(0), idx };
86
- const transaction = web3_js_1.VersionedTransaction.deserialize(Buffer.from(tx.serialize()));
87
- const simulationResp = await (0, timeout_1.withTimeout)(this.connection.simulateTransaction(transaction, { replaceRecentBlockhash: true }), 3_000, '[SolanaGasService_calculateCUPriceSolWeb3] Timeout');
88
- if (typeof simulationResp !== 'object' ||
89
- !simulationResp.context ||
90
- !simulationResp.value ||
91
- !simulationResp.value.unitsConsumed ||
92
- simulationResp.value.err) {
93
- return { success: false, cuLimit: new bignumber_js_1.default(0), idx };
94
- }
95
- return { success: true, cuLimit: new bignumber_js_1.default(simulationResp.value.unitsConsumed), idx };
77
+ async getRecentPriorityFeeSolWeb3() {
78
+ const BASE_FEE_MICROLAMPORTS = 5_000;
79
+ const lastSlot = await this.connection.getSlot();
80
+ // last slots array [1000, 1001, 1002 ...]
81
+ const last10Slots = Array.from({ length: 10 }, (_, idx) => lastSlot - idx).reverse();
82
+ // @CHECK microlamports or lamports
83
+ const getPriorityFeesFromBlock = async (slotNum) => {
84
+ const block = await this.connection.getBlock(slotNum, { maxSupportedTransactionVersion: 0, commitment: 'confirmed' });
85
+ if (!block)
86
+ return [];
87
+ return block.transactions.map((tx) => (tx.meta && tx.meta.fee ? tx.meta.fee : BASE_FEE_MICROLAMPORTS));
96
88
  };
97
- const recentFees = await this.connection.getRecentPrioritizationFees();
98
- const lastTenTxFees = recentFees.slice(recentFees.length - 10);
99
- const lastBlocksSlots = await this.connection.getBlocks(lastTenTxFees[0].slot).catch((err) => {
100
- this.logger?.customLog('SolanaGasService_calculateCUPriceSolWeb3_getBlocks ERROR', err);
101
- return [];
102
- });
103
- const lastBlocksSigs = await Promise.all(lastBlocksSlots.map((slot) => this.connection.getBlockSignatures(slot, 'confirmed')));
104
- const flattenSigs = lastBlocksSigs.flatMap((b) => b.signatures);
105
- const lastTxs = await this.connection
106
- .getTransactions(flattenSigs, { commitment: 'confirmed', maxSupportedTransactionVersion: 0 })
107
- .catch((err) => {
108
- this.logger?.customLog('SolanaGasService_calculateCUPriceSolWeb3_getTransactions ERROR', err);
109
- return [];
110
- });
111
- const serializedTxs = lastTxs
112
- .filter(Boolean)
113
- .map((tx) => web3_js_1.VersionedTransaction.deserialize(Buffer.from(tx.transaction.message.serialize())));
114
- const lastCuLimits = await Promise.all(serializedTxs.map((tx, idx) => estimateCULimitForTx(tx, idx)));
115
- const successCuLimits = lastCuLimits.filter((obj) => obj.success);
116
- const avgCuPrice = successCuLimits.reduce((acc, cuLimitInfo) => {
117
- const cuPrice = new bignumber_js_1.default(lastTenTxFees[cuLimitInfo.idx].prioritizationFee)
118
- .multipliedBy(1_000_000)
119
- .div(cuLimitInfo.cuLimit);
120
- return cuPrice.gt(acc) ? cuPrice : acc;
121
- }, new bignumber_js_1.default(0));
122
- this.logger?.customLog('SOLANA_WEB3 PRIORITY_FEE SUCCESS', { priorityFeeEstimate: avgCuPrice, lastCuLimits });
123
- return avgCuPrice;
89
+ const resp = await Promise.all(last10Slots.map((slotNum) => getPriorityFeesFromBlock(slotNum)));
90
+ const flattenPriorityFees = resp.flat();
91
+ const avgPriorityFee = flattenPriorityFees.reduce((acc, fee) => (acc.gt(fee) ? acc : new bignumber_js_1.default(fee)), new bignumber_js_1.default(0));
92
+ // const resp = await this.connection.getRecentPrioritizationFees();
93
+ // const avgPriorityFee = resp
94
+ // .reduce((acc, tx) => {
95
+ // const cuPrice = new BigNumber(tx.prioritizationFee).multipliedBy(1_000_000).div(this.DEFAULT_CU_LIMIT);
96
+ // return acc.gt(cuPrice) ? acc : cuPrice;
97
+ // }, new BigNumber(0))
98
+ // .div(resp.length)
99
+ // .dp(0, BigNumber.ROUND_CEIL);
100
+ this.logger?.customLog('SOLANA_WEB3 PRIORITY_FEE SUCCESS', { priorityFeeEstimate: avgPriorityFee.toNumber() });
101
+ return avgPriorityFee;
124
102
  }
125
103
  }
126
104
  exports.SolanaGasService = SolanaGasService;