@across-protocol/sdk 4.1.19 → 4.1.21

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 (192) hide show
  1. package/dist/cjs/caching/Memory/MemoryCacheClient.d.ts +6 -0
  2. package/dist/cjs/caching/Memory/MemoryCacheClient.js +32 -0
  3. package/dist/cjs/caching/Memory/MemoryCacheClient.js.map +1 -0
  4. package/dist/cjs/caching/Memory/index.d.ts +1 -0
  5. package/dist/cjs/caching/Memory/index.js +5 -0
  6. package/dist/cjs/caching/Memory/index.js.map +1 -0
  7. package/dist/cjs/caching/index.d.ts +1 -0
  8. package/dist/cjs/caching/index.js +1 -0
  9. package/dist/cjs/caching/index.js.map +1 -1
  10. package/dist/cjs/clients/HubPoolClient.d.ts +1 -1
  11. package/dist/cjs/clients/HubPoolClient.js.map +1 -1
  12. package/dist/cjs/clients/SpokePoolClient.d.ts +2 -1
  13. package/dist/cjs/clients/SpokePoolClient.js +61 -71
  14. package/dist/cjs/clients/SpokePoolClient.js.map +1 -1
  15. package/dist/cjs/index.d.ts +1 -0
  16. package/dist/cjs/index.js +2 -1
  17. package/dist/cjs/index.js.map +1 -1
  18. package/dist/cjs/lpFeeCalculator/lpFeeCalculator.js +2 -1
  19. package/dist/cjs/lpFeeCalculator/lpFeeCalculator.js.map +1 -1
  20. package/dist/cjs/providers/cachedProvider.js +21 -20
  21. package/dist/cjs/providers/cachedProvider.js.map +1 -1
  22. package/dist/cjs/providers/solana/baseRpcFactories.d.ts +2 -2
  23. package/dist/cjs/providers/solana/baseRpcFactories.js +2 -2
  24. package/dist/cjs/providers/solana/baseRpcFactories.js.map +1 -1
  25. package/dist/cjs/providers/solana/cachedRpcFactory.d.ts +16 -0
  26. package/dist/cjs/providers/solana/cachedRpcFactory.js +121 -0
  27. package/dist/cjs/providers/solana/cachedRpcFactory.js.map +1 -0
  28. package/dist/cjs/providers/solana/defaultRpcFactory.d.ts +1 -1
  29. package/dist/cjs/providers/solana/defaultRpcFactory.js +2 -2
  30. package/dist/cjs/providers/solana/defaultRpcFactory.js.map +1 -1
  31. package/dist/cjs/providers/solana/index.d.ts +1 -0
  32. package/dist/cjs/providers/solana/index.js +1 -0
  33. package/dist/cjs/providers/solana/index.js.map +1 -1
  34. package/dist/cjs/providers/solana/rateLimitedRpcFactory.d.ts +2 -2
  35. package/dist/cjs/svm/eventsClient.d.ts +15 -0
  36. package/dist/cjs/svm/eventsClient.js +164 -0
  37. package/dist/cjs/svm/eventsClient.js.map +1 -0
  38. package/dist/cjs/svm/index.d.ts +1 -0
  39. package/dist/cjs/svm/index.js +5 -0
  40. package/dist/cjs/svm/index.js.map +1 -0
  41. package/dist/cjs/svm/types.d.ts +29 -0
  42. package/dist/cjs/svm/types.js +21 -0
  43. package/dist/cjs/svm/types.js.map +1 -0
  44. package/dist/cjs/svm/utils/events.d.ts +3 -0
  45. package/dist/cjs/svm/utils/events.js +38 -0
  46. package/dist/cjs/svm/utils/events.js.map +1 -0
  47. package/dist/cjs/svm/utils/helpers.d.ts +2 -0
  48. package/dist/cjs/svm/utils/helpers.js +19 -0
  49. package/dist/cjs/svm/utils/helpers.js.map +1 -0
  50. package/dist/cjs/utils/DepositUtils.js +2 -3
  51. package/dist/cjs/utils/DepositUtils.js.map +1 -1
  52. package/dist/cjs/utils/JSONUtils.d.ts +2 -0
  53. package/dist/cjs/utils/JSONUtils.js +9 -1
  54. package/dist/cjs/utils/JSONUtils.js.map +1 -1
  55. package/dist/cjs/utils/SpokeUtils.d.ts +9 -0
  56. package/dist/cjs/utils/SpokeUtils.js +29 -1
  57. package/dist/cjs/utils/SpokeUtils.js.map +1 -1
  58. package/dist/cjs/utils/index.d.ts +0 -1
  59. package/dist/cjs/utils/index.js +0 -1
  60. package/dist/cjs/utils/index.js.map +1 -1
  61. package/dist/esm/caching/Memory/MemoryCacheClient.d.ts +9 -0
  62. package/dist/esm/caching/Memory/MemoryCacheClient.js +32 -0
  63. package/dist/esm/caching/Memory/MemoryCacheClient.js.map +1 -0
  64. package/dist/esm/caching/Memory/index.d.ts +1 -0
  65. package/dist/esm/caching/Memory/index.js +2 -0
  66. package/dist/esm/caching/Memory/index.js.map +1 -0
  67. package/dist/esm/caching/index.d.ts +1 -0
  68. package/dist/esm/caching/index.js +1 -0
  69. package/dist/esm/caching/index.js.map +1 -1
  70. package/dist/esm/clients/HubPoolClient.d.ts +1 -1
  71. package/dist/esm/clients/HubPoolClient.js.map +1 -1
  72. package/dist/esm/clients/SpokePoolClient.d.ts +2 -1
  73. package/dist/esm/clients/SpokePoolClient.js +61 -70
  74. package/dist/esm/clients/SpokePoolClient.js.map +1 -1
  75. package/dist/esm/index.d.ts +1 -0
  76. package/dist/esm/index.js +2 -0
  77. package/dist/esm/index.js.map +1 -1
  78. package/dist/esm/lpFeeCalculator/lpFeeCalculator.js +2 -1
  79. package/dist/esm/lpFeeCalculator/lpFeeCalculator.js.map +1 -1
  80. package/dist/esm/providers/cachedProvider.js +21 -20
  81. package/dist/esm/providers/cachedProvider.js.map +1 -1
  82. package/dist/esm/providers/solana/baseRpcFactories.d.ts +2 -2
  83. package/dist/esm/providers/solana/baseRpcFactories.js +1 -1
  84. package/dist/esm/providers/solana/baseRpcFactories.js.map +1 -1
  85. package/dist/esm/providers/solana/cachedRpcFactory.d.ts +16 -0
  86. package/dist/esm/providers/solana/cachedRpcFactory.js +128 -0
  87. package/dist/esm/providers/solana/cachedRpcFactory.js.map +1 -0
  88. package/dist/esm/providers/solana/defaultRpcFactory.d.ts +1 -1
  89. package/dist/esm/providers/solana/defaultRpcFactory.js +1 -1
  90. package/dist/esm/providers/solana/defaultRpcFactory.js.map +1 -1
  91. package/dist/esm/providers/solana/index.d.ts +1 -0
  92. package/dist/esm/providers/solana/index.js +1 -0
  93. package/dist/esm/providers/solana/index.js.map +1 -1
  94. package/dist/esm/providers/solana/rateLimitedRpcFactory.d.ts +2 -2
  95. package/dist/esm/svm/eventsClient.d.ts +51 -0
  96. package/dist/esm/svm/eventsClient.js +202 -0
  97. package/dist/esm/svm/eventsClient.js.map +1 -0
  98. package/dist/esm/svm/index.d.ts +1 -0
  99. package/dist/esm/svm/index.js +2 -0
  100. package/dist/esm/svm/index.js.map +1 -0
  101. package/dist/esm/svm/types.d.ts +29 -0
  102. package/dist/esm/svm/types.js +18 -0
  103. package/dist/esm/svm/types.js.map +1 -0
  104. package/dist/esm/svm/utils/events.d.ts +9 -0
  105. package/dist/esm/svm/utils/events.js +43 -0
  106. package/dist/esm/svm/utils/events.js.map +1 -0
  107. package/dist/esm/svm/utils/helpers.d.ts +5 -0
  108. package/dist/esm/svm/utils/helpers.js +18 -0
  109. package/dist/esm/svm/utils/helpers.js.map +1 -0
  110. package/dist/esm/utils/DepositUtils.js +1 -2
  111. package/dist/esm/utils/DepositUtils.js.map +1 -1
  112. package/dist/esm/utils/JSONUtils.d.ts +8 -0
  113. package/dist/esm/utils/JSONUtils.js +12 -0
  114. package/dist/esm/utils/JSONUtils.js.map +1 -1
  115. package/dist/esm/utils/SpokeUtils.d.ts +9 -0
  116. package/dist/esm/utils/SpokeUtils.js +34 -1
  117. package/dist/esm/utils/SpokeUtils.js.map +1 -1
  118. package/dist/esm/utils/index.d.ts +0 -1
  119. package/dist/esm/utils/index.js +0 -1
  120. package/dist/esm/utils/index.js.map +1 -1
  121. package/dist/types/caching/Memory/MemoryCacheClient.d.ts +10 -0
  122. package/dist/types/caching/Memory/MemoryCacheClient.d.ts.map +1 -0
  123. package/dist/types/caching/Memory/index.d.ts +2 -0
  124. package/dist/types/caching/Memory/index.d.ts.map +1 -0
  125. package/dist/types/caching/index.d.ts +1 -0
  126. package/dist/types/caching/index.d.ts.map +1 -1
  127. package/dist/types/clients/HubPoolClient.d.ts +1 -1
  128. package/dist/types/clients/HubPoolClient.d.ts.map +1 -1
  129. package/dist/types/clients/SpokePoolClient.d.ts +2 -1
  130. package/dist/types/clients/SpokePoolClient.d.ts.map +1 -1
  131. package/dist/types/index.d.ts +1 -0
  132. package/dist/types/index.d.ts.map +1 -1
  133. package/dist/types/lpFeeCalculator/lpFeeCalculator.d.ts.map +1 -1
  134. package/dist/types/providers/solana/baseRpcFactories.d.ts +2 -2
  135. package/dist/types/providers/solana/baseRpcFactories.d.ts.map +1 -1
  136. package/dist/types/providers/solana/cachedRpcFactory.d.ts +17 -0
  137. package/dist/types/providers/solana/cachedRpcFactory.d.ts.map +1 -0
  138. package/dist/types/providers/solana/defaultRpcFactory.d.ts +1 -1
  139. package/dist/types/providers/solana/defaultRpcFactory.d.ts.map +1 -1
  140. package/dist/types/providers/solana/index.d.ts +1 -0
  141. package/dist/types/providers/solana/index.d.ts.map +1 -1
  142. package/dist/types/providers/solana/rateLimitedRpcFactory.d.ts +2 -2
  143. package/dist/types/providers/solana/rateLimitedRpcFactory.d.ts.map +1 -1
  144. package/dist/types/svm/eventsClient.d.ts +52 -0
  145. package/dist/types/svm/eventsClient.d.ts.map +1 -0
  146. package/dist/types/svm/index.d.ts +2 -0
  147. package/dist/types/svm/index.d.ts.map +1 -0
  148. package/dist/types/svm/types.d.ts +30 -0
  149. package/dist/types/svm/types.d.ts.map +1 -0
  150. package/dist/types/svm/utils/events.d.ts +10 -0
  151. package/dist/types/svm/utils/events.d.ts.map +1 -0
  152. package/dist/types/svm/utils/helpers.d.ts +6 -0
  153. package/dist/types/svm/utils/helpers.d.ts.map +1 -0
  154. package/dist/types/utils/DepositUtils.d.ts.map +1 -1
  155. package/dist/types/utils/JSONUtils.d.ts +8 -0
  156. package/dist/types/utils/JSONUtils.d.ts.map +1 -1
  157. package/dist/types/utils/SpokeUtils.d.ts +9 -0
  158. package/dist/types/utils/SpokeUtils.d.ts.map +1 -1
  159. package/dist/types/utils/index.d.ts +0 -1
  160. package/dist/types/utils/index.d.ts.map +1 -1
  161. package/package.json +9 -4
  162. package/src/caching/Memory/MemoryCacheClient.ts +35 -0
  163. package/src/caching/Memory/index.ts +1 -0
  164. package/src/caching/index.ts +1 -0
  165. package/src/clients/HubPoolClient.ts +2 -2
  166. package/src/clients/SpokePoolClient.ts +16 -17
  167. package/src/index.ts +1 -0
  168. package/src/lpFeeCalculator/lpFeeCalculator.ts +6 -1
  169. package/src/providers/cachedProvider.ts +34 -34
  170. package/src/providers/solana/baseRpcFactories.ts +1 -1
  171. package/src/providers/solana/cachedRpcFactory.ts +124 -0
  172. package/src/providers/solana/defaultRpcFactory.ts +1 -1
  173. package/src/providers/solana/index.ts +1 -0
  174. package/src/providers/solana/rateLimitedRpcFactory.ts +2 -2
  175. package/src/svm/eventsClient.ts +205 -0
  176. package/src/svm/index.ts +1 -0
  177. package/src/svm/types.ts +47 -0
  178. package/src/svm/utils/events.ts +46 -0
  179. package/src/svm/utils/helpers.ts +9 -0
  180. package/src/utils/DepositUtils.ts +1 -2
  181. package/src/utils/JSONUtils.ts +14 -0
  182. package/src/utils/SpokeUtils.ts +42 -1
  183. package/src/utils/index.ts +0 -1
  184. package/dist/cjs/utils/FlowUtils.d.ts +0 -11
  185. package/dist/cjs/utils/FlowUtils.js +0 -34
  186. package/dist/cjs/utils/FlowUtils.js.map +0 -1
  187. package/dist/esm/utils/FlowUtils.d.ts +0 -11
  188. package/dist/esm/utils/FlowUtils.js +0 -36
  189. package/dist/esm/utils/FlowUtils.js.map +0 -1
  190. package/dist/types/utils/FlowUtils.d.ts +0 -12
  191. package/dist/types/utils/FlowUtils.d.ts.map +0 -1
  192. package/src/utils/FlowUtils.ts +0 -44
@@ -21,6 +21,7 @@ import {
21
21
  isValidEvmAddress,
22
22
  isZeroAddress,
23
23
  toAddress,
24
+ validateFillForDeposit,
24
25
  } from "../utils";
25
26
  import {
26
27
  duplicateEvent,
@@ -29,7 +30,6 @@ import {
29
30
  spreadEvent,
30
31
  spreadEventWithBlockNumber,
31
32
  } from "../utils/EventUtils";
32
- import { validateFillForDeposit } from "../utils/FlowUtils";
33
33
  import { ZERO_ADDRESS } from "../constants";
34
34
  import {
35
35
  Deposit,
@@ -84,6 +84,7 @@ export class SpokePoolClient extends BaseAbstractClient {
84
84
  protected relayerRefundExecutions: RelayerRefundExecutionWithBlock[] = [];
85
85
  protected queryableEventNames: string[] = [];
86
86
  protected configStoreClient: AcrossConfigStoreClient | undefined;
87
+ protected invalidFills: Set<string> = new Set();
87
88
  public earliestDepositIdQueried = MAX_BIG_INT;
88
89
  public latestDepositIdQueried = bnZero;
89
90
  public firstDepositIdForSpokePool = MAX_BIG_INT;
@@ -380,7 +381,7 @@ export class SpokePoolClient extends BaseAbstractClient {
380
381
  public getValidUnfilledAmountForDeposit(deposit: Deposit): {
381
382
  unfilledAmount: BigNumber;
382
383
  fillCount: number;
383
- invalidFills: Fill[];
384
+ invalidFills: FillWithBlock[];
384
385
  } {
385
386
  const { outputAmount } = deposit;
386
387
  const fillsForDeposit = this.depositHashesToFills[this.getDepositHash(deposit)];
@@ -390,7 +391,10 @@ export class SpokePoolClient extends BaseAbstractClient {
390
391
  }
391
392
 
392
393
  const { validFills, invalidFills, unrepayableFills } = fillsForDeposit.reduce(
393
- (groupedFills: { validFills: Fill[]; invalidFills: Fill[]; unrepayableFills: Fill[] }, fill: Fill) => {
394
+ (
395
+ groupedFills: { validFills: FillWithBlock[]; invalidFills: FillWithBlock[]; unrepayableFills: FillWithBlock[] },
396
+ fill: FillWithBlock
397
+ ) => {
394
398
  if (validateFillForDeposit(fill, deposit).valid) {
395
399
  const repaymentChainId = getRepaymentChainId(fill, deposit);
396
400
  // In order to keep this function sync, we can't call verifyFillRepayment so we'll log any fills that
@@ -423,7 +427,15 @@ export class SpokePoolClient extends BaseAbstractClient {
423
427
  );
424
428
 
425
429
  // Log any invalid deposits with same deposit id but different params.
426
- const invalidFillsForDeposit = invalidFills.filter((x) => x.depositId.eq(deposit.depositId));
430
+ const invalidFillsForDeposit = invalidFills.filter((x) => {
431
+ const txnUid = `${x.transactionHash}:${x.logIndex}`;
432
+ // if txnUid doesn't exist in the invalidFills set, add it now, but log the corresponding fill.
433
+ const newInvalidFill = x.depositId.eq(deposit.depositId) && !this.invalidFills.has(txnUid);
434
+ if (newInvalidFill) {
435
+ this.invalidFills.add(txnUid);
436
+ }
437
+ return newInvalidFill;
438
+ });
427
439
  if (invalidFillsForDeposit.length > 0) {
428
440
  this.logger.warn({
429
441
  at: "SpokePoolClient",
@@ -606,19 +618,6 @@ export class SpokePoolClient extends BaseAbstractClient {
606
618
  const { events: queryResults, currentTime, searchEndBlock } = update;
607
619
 
608
620
  if (eventsToQuery.includes("TokensBridged")) {
609
- // Temporarily query old spoke pool events as well to ease migration:
610
- const legacySpokePoolAbi = [
611
- "event TokensBridged(uint256 amountToReturn,uint256 indexed chainId,uint32 indexed leafId,address indexed l2TokenAddress,address caller)",
612
- ];
613
- const prevSpoke = new Contract(this.spokePool.address, legacySpokePoolAbi, this.spokePool.provider);
614
- const legacyQueryResults = await paginatedEventQuery(
615
- prevSpoke,
616
- prevSpoke.filters.TokensBridged(),
617
- (await this.updateSearchConfig(this.spokePool.provider)) as EventSearchConfig
618
- );
619
- for (const event of legacyQueryResults) {
620
- this.tokensBridged.push(spreadEventWithBlockNumber(event) as TokensBridged);
621
- }
622
621
  for (const event of queryResults[eventsToQuery.indexOf("TokensBridged")]) {
623
622
  this.tokensBridged.push(spreadEventWithBlockNumber(event) as TokensBridged);
624
623
  }
package/src/index.ts CHANGED
@@ -14,3 +14,4 @@ export * as clients from "./clients";
14
14
  export * as typechain from "./typechain";
15
15
  export * as caching from "./caching";
16
16
  export * as providers from "./providers";
17
+ export * as svm from "./svm";
@@ -14,6 +14,8 @@ export interface RateModel {
14
14
  R2: BigNumberish; // R_0+R_1+R_2 is the interest rate charged at 100% utilization
15
15
  }
16
16
 
17
+ const ONE_HUNDRED_PERCENT = toBN(10).pow(18);
18
+
17
19
  // converts an APY rate to a one week rate. Uses the Decimal library to take a fractional exponent
18
20
  function convertApyToWeeklyFee(apy: BN): BN {
19
21
  // R_week = (1 + apy)^(1/52) - 1
@@ -99,7 +101,10 @@ export class LPFeeCalculator {
99
101
  const apy = this.calculateApyFromUtilization(toBN(utilizationBeforeDeposit), toBN(utilizationAfterDeposit));
100
102
 
101
103
  // ACROSS UMIP requires that the realized fee percent is floor rounded as decimal to 6 decimals.
102
- return truncateDecimals ? truncate18DecimalBN(convertApyToWeeklyFee(apy), 6) : convertApyToWeeklyFee(apy);
104
+ return min(
105
+ ONE_HUNDRED_PERCENT,
106
+ truncateDecimals ? truncate18DecimalBN(convertApyToWeeklyFee(apy), 6) : convertApyToWeeklyFee(apy)
107
+ );
103
108
  }
104
109
  /**
105
110
  * Calculate the realized yearly LP Fee APY Percent for a given rate model, utilization before and after the deposit.
@@ -42,49 +42,49 @@ export class CacheProvider extends RateLimitedProvider {
42
42
  override async send(method: string, params: Array<unknown>): Promise<unknown> {
43
43
  let cacheType = this.redisClient ? await this.cacheType(method, params) : CacheType.NONE;
44
44
 
45
- if (cacheType !== CacheType.NONE) {
46
- const redisKey = this.buildRedisKey(method, params);
45
+ if (cacheType === CacheType.NONE) {
46
+ return await super.send(method, params);
47
+ }
47
48
 
48
- // Attempt to pull the result from the cache.
49
- const redisResult = await this.redisClient?.get<string>(redisKey);
49
+ const redisKey = this.buildRedisKey(method, params);
50
50
 
51
- // If cache has the result, parse the json and return it.
52
- if (redisResult) {
53
- return JSON.parse(redisResult);
54
- }
51
+ // Attempt to pull the result from the cache.
52
+ const redisResult = await this.redisClient?.get<string>(redisKey);
55
53
 
56
- // Cache does not have the result. Query it directly and cache.
57
- const result = await super.send(method, params);
54
+ // If cache has the result, parse the json and return it.
55
+ if (redisResult) {
56
+ return JSON.parse(redisResult);
57
+ }
58
58
 
59
- if (cacheType === CacheType.DECIDE_TTL_POST_SEND) {
60
- const blockNumber = this.getBlockNumberFromRpcResponse(method, result);
61
- cacheType = await this.cacheTypeForBlock(blockNumber);
62
- if (cacheType === CacheType.NONE) {
63
- return result;
64
- }
65
- }
59
+ // Cache does not have the result. Query it directly and cache.
60
+ const result = await super.send(method, params);
66
61
 
67
- // Note: use swtich to ensure all enum cases are handled.
68
- switch (cacheType) {
69
- case CacheType.WITH_TTL:
70
- {
71
- // Apply a random margin to spread expiry over a larger time window.
72
- const ttl = this.baseTTL + Math.ceil(random(-ttl_modifier, ttl_modifier, true) * this.baseTTL);
73
- await this.redisClient?.set(redisKey, JSON.stringify(result), ttl);
74
- }
75
- break;
76
- case CacheType.NO_TTL:
77
- await this.redisClient?.set(redisKey, JSON.stringify(result), Number.POSITIVE_INFINITY);
78
- break;
79
- default:
80
- throw new Error(`Unexpected Cache type: ${cacheType}`);
62
+ if (cacheType === CacheType.DECIDE_TTL_POST_SEND) {
63
+ const blockNumber = this.getBlockNumberFromRpcResponse(method, result);
64
+ cacheType = await this.cacheTypeForBlock(blockNumber);
65
+ if (cacheType === CacheType.NONE) {
66
+ return result;
81
67
  }
68
+ }
82
69
 
83
- // Return the cached result.
84
- return result;
70
+ // Note: use swtich to ensure all enum cases are handled.
71
+ switch (cacheType) {
72
+ case CacheType.WITH_TTL:
73
+ {
74
+ // Apply a random margin to spread expiry over a larger time window.
75
+ const ttl = this.baseTTL + Math.ceil(random(-ttl_modifier, ttl_modifier, true) * this.baseTTL);
76
+ await this.redisClient?.set(redisKey, JSON.stringify(result), ttl);
77
+ }
78
+ break;
79
+ case CacheType.NO_TTL:
80
+ await this.redisClient?.set(redisKey, JSON.stringify(result), Number.POSITIVE_INFINITY);
81
+ break;
82
+ default:
83
+ throw new Error(`Unexpected Cache type: ${cacheType}`);
85
84
  }
86
85
 
87
- return await super.send(method, params);
86
+ // Return the cached result.
87
+ return result;
88
88
  }
89
89
 
90
90
  private buildRedisKey(method: string, params: Array<unknown>) {
@@ -1,4 +1,4 @@
1
- import { ClusterUrl, createSolanaRpcFromTransport, RpcTransport } from "@solana/web3.js";
1
+ import { ClusterUrl, createSolanaRpcFromTransport, RpcTransport } from "@solana/kit";
2
2
 
3
3
  // This is abstract base class for creating Solana RPC clients and transports.
4
4
  export abstract class SolanaBaseRpcFactory {
@@ -0,0 +1,124 @@
1
+ import { RpcTransport, GetTransactionApi, RpcFromTransport, SolanaRpcApiFromTransport } from "@solana/kit";
2
+ import { is, object, optional, string, tuple } from "superstruct";
3
+ import { CachingMechanismInterface } from "../../interfaces";
4
+ import { SolanaClusterRpcFactory } from "./baseRpcFactories";
5
+ import { RateLimitedSolanaRpcFactory } from "./rateLimitedRpcFactory";
6
+ import { CacheType } from "../utils";
7
+ import { jsonReplacerWithBigInts, jsonReviverWithBigInts } from "../../utils";
8
+
9
+ export class CachedSolanaRpcFactory extends SolanaClusterRpcFactory {
10
+ public readonly getTransactionCachePrefix: string;
11
+
12
+ // Holds the underlying transport that the cached transport wraps.
13
+ protected rateLimitedTransport: RpcTransport;
14
+
15
+ // RPC client based on the rate limited transport, used internally to check confirmation status.
16
+ protected rateLimitedRpcClient: RpcFromTransport<SolanaRpcApiFromTransport<RpcTransport>, RpcTransport>;
17
+
18
+ constructor(
19
+ providerCacheNamespace: string,
20
+ readonly redisClient?: CachingMechanismInterface,
21
+ ...rateLimitedConstructorParams: ConstructorParameters<typeof RateLimitedSolanaRpcFactory>
22
+ ) {
23
+ // SolanaClusterRpcFactory shares the last two constructor parameters with RateLimitedSolanaRpcFactory.
24
+ const superParams = rateLimitedConstructorParams.slice(-2) as [
25
+ ConstructorParameters<typeof SolanaClusterRpcFactory>[0], // clusterUrl: ClusterUrl
26
+ ConstructorParameters<typeof SolanaClusterRpcFactory>[1], // chainId: number
27
+ ];
28
+ super(...superParams);
29
+
30
+ // Create the rate limited transport and RPC client.
31
+ const rateLimitedRpcFactory = new RateLimitedSolanaRpcFactory(...rateLimitedConstructorParams);
32
+ this.rateLimitedTransport = rateLimitedRpcFactory.createTransport();
33
+ this.rateLimitedRpcClient = rateLimitedRpcFactory.createRpcClient();
34
+
35
+ // Pre-compute as much of the redis key as possible.
36
+ const cachePrefix = `${providerCacheNamespace},${new URL(this.clusterUrl).hostname},${this.chainId}`;
37
+ this.getTransactionCachePrefix = `${cachePrefix}:getTransaction,`;
38
+ }
39
+
40
+ public createTransport(): RpcTransport {
41
+ return async <TResponse>(...args: Parameters<RpcTransport>): Promise<TResponse> => {
42
+ const { method, params } = args[0].payload as { method: string; params?: unknown[] };
43
+ const cacheType = this.redisClient ? this.cacheType(method) : CacheType.NONE;
44
+
45
+ if (cacheType === CacheType.NONE) {
46
+ return this.rateLimitedTransport<TResponse>(...args);
47
+ }
48
+
49
+ const redisKey = this.buildRedisKey(method, params);
50
+
51
+ // Attempt to pull the result from the cache.
52
+ const redisResult = await this.redisClient?.get<string>(redisKey);
53
+
54
+ // If cache has the result, parse the json and return it.
55
+ if (redisResult) {
56
+ return JSON.parse(redisResult, jsonReviverWithBigInts);
57
+ }
58
+
59
+ // Cache does not have the result. Query it directly and cache it if finalized.
60
+ return this.requestAndCacheFinalized<TResponse>(...args);
61
+ };
62
+ }
63
+
64
+ private async requestAndCacheFinalized<TResponse>(...args: Parameters<RpcTransport>): Promise<TResponse> {
65
+ const { method, params } = args[0].payload as { method: string; params?: unknown[] };
66
+
67
+ // Only handles getTransaction right now.
68
+ if (method !== "getTransaction") return this.rateLimitedTransport<TResponse>(...args);
69
+
70
+ // Do not throw if params are not valid, just skip caching and pass through to the underlying transport.
71
+ if (!this.isGetTransactionParams(params)) return this.rateLimitedTransport<TResponse>(...args);
72
+
73
+ // Check the confirmation status first to avoid caching non-finalized transactions.
74
+ const getSignatureStatusesResponse = await this.rateLimitedRpcClient
75
+ .getSignatureStatuses([params[0]], {
76
+ searchTransactionHistory: true,
77
+ })
78
+ .send();
79
+
80
+ const getTransactionResponse = await this.rateLimitedTransport<TResponse>(...args);
81
+
82
+ // Cache the transaction only if it is finalized.
83
+ if (getSignatureStatusesResponse.value[0]?.confirmationStatus === "finalized") {
84
+ const redisKey = this.buildRedisKey(method, params);
85
+ await this.redisClient?.set(
86
+ redisKey,
87
+ JSON.stringify(getTransactionResponse, jsonReplacerWithBigInts),
88
+ Number.POSITIVE_INFINITY
89
+ );
90
+ }
91
+
92
+ return getTransactionResponse;
93
+ }
94
+
95
+ private buildRedisKey(method: string, params?: unknown[]) {
96
+ // Only handles getTransaction right now.
97
+ switch (method) {
98
+ case "getTransaction":
99
+ return this.getTransactionCachePrefix + JSON.stringify(params, jsonReplacerWithBigInts);
100
+ default:
101
+ throw new Error(`CachedSolanaRpcFactory::buildRedisKey: invalid JSON-RPC method ${method}`);
102
+ }
103
+ }
104
+
105
+ private cacheType(method: string): CacheType {
106
+ // Today, we only cache getTransaction.
107
+ if (method === "getTransaction") {
108
+ // We only store finalized transactions in the cache, hence TTL is not required.
109
+ return CacheType.NO_TTL;
110
+ } else {
111
+ return CacheType.NONE;
112
+ }
113
+ }
114
+
115
+ private isGetTransactionParams(params: unknown): params is Parameters<GetTransactionApi["getTransaction"]> {
116
+ return is(
117
+ params,
118
+ tuple([
119
+ string(), // Signature (Base58 string)
120
+ optional(object()), // We use only the tx signature to get its commitment, but pass through the options as is.
121
+ ])
122
+ );
123
+ }
124
+ }
@@ -1,4 +1,4 @@
1
- import { createDefaultRpcTransport, RpcTransport } from "@solana/web3.js";
1
+ import { createDefaultRpcTransport, RpcTransport } from "@solana/kit";
2
2
  import { SolanaClusterRpcFactory } from "./baseRpcFactories";
3
3
 
4
4
  // Exposes default RPC transport for Solana in the SolanaClusterRpcFactory class.
@@ -1,4 +1,5 @@
1
1
  export * from "./baseRpcFactories";
2
+ export * from "./cachedRpcFactory";
2
3
  export * from "./defaultRpcFactory";
3
4
  export * from "./rateLimitedRpcFactory";
4
5
  export * from "./utils";
@@ -1,4 +1,4 @@
1
- import { RpcResponse, RpcTransport } from "@solana/web3.js";
1
+ import { RpcResponse, RpcTransport } from "@solana/kit";
2
2
  import { QueueObject, queue } from "async";
3
3
  import winston, { Logger } from "winston";
4
4
  import { SolanaClusterRpcFactory } from "./baseRpcFactories";
@@ -13,7 +13,7 @@ export class RateLimitedSolanaRpcFactory extends SolanaClusterRpcFactory {
13
13
  private queue: QueueObject<SolanaRateLimitTask>;
14
14
 
15
15
  // Holds the underlying transport that the rate limiter wraps.
16
- private readonly defaultTransport: RpcTransport;
16
+ protected defaultTransport: RpcTransport;
17
17
 
18
18
  // Takes the same arguments as the SolanaDefaultRpcFactory, but it has an additional parameters to control
19
19
  // concurrency and logging at the beginning of the list.
@@ -0,0 +1,205 @@
1
+ import { getDeployedAddress, SvmSpokeIdl } from "@across-protocol/contracts";
2
+ import { getSolanaChainId } from "@across-protocol/contracts/dist/src/svm/web3-v1";
3
+ import { BorshEventCoder, utils } from "@coral-xyz/anchor";
4
+ import web3, {
5
+ Address,
6
+ Commitment,
7
+ GetSignaturesForAddressApi,
8
+ GetTransactionApi,
9
+ RpcTransport,
10
+ Signature,
11
+ } from "@solana/kit";
12
+ import { EventData, EventName, EventWithData } from "./types";
13
+ import { getEventName, parseEventData } from "./utils/events";
14
+ import { isDevnet } from "./utils/helpers";
15
+
16
+ // Utility type to extract the return type for the JSON encoding overload. We only care about the overload where the
17
+ // configuration parameter (C) has the optional property 'encoding' set to 'json'.
18
+ type ExtractJsonOverload<T> = T extends (signature: infer _S, config: infer C) => infer R
19
+ ? C extends { encoding?: "json" }
20
+ ? R
21
+ : never
22
+ : never;
23
+
24
+ type GetTransactionReturnType = ExtractJsonOverload<GetTransactionApi["getTransaction"]>;
25
+ type GetSignaturesForAddressConfig = Parameters<GetSignaturesForAddressApi["getSignaturesForAddress"]>[1];
26
+ type GetSignaturesForAddressTransaction = ReturnType<GetSignaturesForAddressApi["getSignaturesForAddress"]>[number];
27
+ type GetSignaturesForAddressApiResponse = readonly GetSignaturesForAddressTransaction[];
28
+
29
+ export class SvmSpokeEventsClient {
30
+ private rpc: web3.Rpc<web3.SolanaRpcApiFromTransport<RpcTransport>>;
31
+ private svmSpokeAddress: Address;
32
+ private svmSpokeEventAuthority: Address;
33
+
34
+ /**
35
+ * Private constructor. Use the async create() method to instantiate.
36
+ */
37
+ private constructor(
38
+ rpc: web3.Rpc<web3.SolanaRpcApiFromTransport<RpcTransport>>,
39
+ svmSpokeAddress: Address,
40
+ eventAuthority: Address
41
+ ) {
42
+ this.rpc = rpc;
43
+ this.svmSpokeAddress = svmSpokeAddress;
44
+ this.svmSpokeEventAuthority = eventAuthority;
45
+ }
46
+
47
+ /**
48
+ * Factory method to asynchronously create an instance of SvmSpokeEventsClient.
49
+ */
50
+ public static async create(
51
+ rpc: web3.Rpc<web3.SolanaRpcApiFromTransport<RpcTransport>>
52
+ ): Promise<SvmSpokeEventsClient> {
53
+ const isTestnet = await isDevnet(rpc);
54
+ const programId = getDeployedAddress("SvmSpoke", getSolanaChainId(isTestnet ? "devnet" : "mainnet").toString());
55
+ if (!programId) throw new Error("Program not found");
56
+ const svmSpokeAddress = web3.address(programId);
57
+ const [svmSpokeEventAuthority] = await web3.getProgramDerivedAddress({
58
+ programAddress: svmSpokeAddress,
59
+ seeds: ["__event_authority"],
60
+ });
61
+ return new SvmSpokeEventsClient(rpc, svmSpokeAddress, svmSpokeEventAuthority);
62
+ }
63
+
64
+ /**
65
+ * Queries events for the SvmSpoke program filtered by event name.
66
+ *
67
+ * @param eventName - The name of the event to filter by.
68
+ * @param fromSlot - Optional starting slot.
69
+ * @param toSlot - Optional ending slot.
70
+ * @param options - Options for fetching signatures.
71
+ * @returns A promise that resolves to an array of events matching the eventName.
72
+ */
73
+ public async queryEvents<T extends EventData>(
74
+ eventName: EventName,
75
+ fromSlot?: bigint,
76
+ toSlot?: bigint,
77
+ options: GetSignaturesForAddressConfig = { limit: 1000, commitment: "confirmed" }
78
+ ): Promise<EventWithData<T>[]> {
79
+ const events = await this.queryAllEvents(fromSlot, toSlot, options);
80
+ return events.filter((event) => event.name === eventName) as EventWithData<T>[];
81
+ }
82
+
83
+ /**
84
+ * Queries all events for a specific program.
85
+ *
86
+ * @param fromSlot - Optional starting slot.
87
+ * @param toSlot - Optional ending slot.
88
+ * @param options - Options for fetching signatures.
89
+ * @returns A promise that resolves to an array of all events with additional metadata.
90
+ */
91
+ private async queryAllEvents(
92
+ fromSlot?: bigint,
93
+ toSlot?: bigint,
94
+ options: GetSignaturesForAddressConfig = { limit: 1000, commitment: "confirmed" }
95
+ ): Promise<EventWithData<EventData>[]> {
96
+ const allSignatures: GetSignaturesForAddressTransaction[] = [];
97
+ let hasMoreSignatures = true;
98
+ let currentOptions = options;
99
+
100
+ while (hasMoreSignatures) {
101
+ const signatures: GetSignaturesForAddressApiResponse = await this.rpc
102
+ .getSignaturesForAddress(this.svmSpokeAddress, currentOptions)
103
+ .send();
104
+ // Signatures are sorted by slot in descending order.
105
+ allSignatures.push(...signatures);
106
+
107
+ // Update options for the next batch. Set "before" to the last fetched signature.
108
+ if (signatures.length > 0) {
109
+ currentOptions = { ...currentOptions, before: signatures[signatures.length - 1].signature };
110
+ }
111
+
112
+ if (fromSlot && allSignatures.length > 0 && allSignatures[allSignatures.length - 1].slot < fromSlot) {
113
+ hasMoreSignatures = false;
114
+ }
115
+
116
+ hasMoreSignatures = Boolean(
117
+ hasMoreSignatures && currentOptions.limit && signatures.length === currentOptions.limit
118
+ );
119
+ }
120
+
121
+ const filteredSignatures = allSignatures.filter((signatureTransaction) => {
122
+ if (fromSlot && signatureTransaction.slot < fromSlot) return false;
123
+ if (toSlot && signatureTransaction.slot > toSlot) return false;
124
+ return true;
125
+ });
126
+
127
+ // Fetch events for all signatures in parallel.
128
+ const eventsWithSlots = await Promise.all(
129
+ filteredSignatures.map(async (signatureTransaction) => {
130
+ const events = await this.readEventsFromSignature(signatureTransaction.signature, options.commitment);
131
+ return events.map((event) => ({
132
+ ...event,
133
+ confirmationStatus: signatureTransaction.confirmationStatus,
134
+ blockTime: signatureTransaction.blockTime,
135
+ signature: signatureTransaction.signature,
136
+ slot: signatureTransaction.slot,
137
+ }));
138
+ })
139
+ );
140
+ return eventsWithSlots.flat();
141
+ }
142
+
143
+ /**
144
+ * Reads events from a transaction signature.
145
+ *
146
+ * @param txSignature - The transaction signature.
147
+ * @param commitment - Commitment level.
148
+ * @returns A promise that resolves to an array of events.
149
+ */
150
+ private async readEventsFromSignature(txSignature: Signature, commitment: Commitment = "confirmed") {
151
+ const txResult = await this.rpc
152
+ .getTransaction(txSignature, { commitment, maxSupportedTransactionVersion: 0 })
153
+ .send();
154
+
155
+ if (txResult === null) return [];
156
+ return this.processEventFromTx(txResult);
157
+ }
158
+
159
+ /**
160
+ * Processes events from a transaction.
161
+ *
162
+ * @param txResult - The transaction result.
163
+ * @returns A promise that resolves to an array of events with their data and name.
164
+ */
165
+ private processEventFromTx(
166
+ txResult: GetTransactionReturnType
167
+ ): { program: Address; data: EventData; name: EventName }[] {
168
+ if (!txResult) return [];
169
+ const events: { program: Address; data: EventData; name: EventName }[] = [];
170
+
171
+ const accountKeys = txResult.transaction.message.accountKeys;
172
+ const messageAccountKeys = [...accountKeys];
173
+ // Writable accounts come first, then readonly.
174
+ // See https://docs.anza.xyz/proposals/versioned-transactions#new-transaction-format
175
+ messageAccountKeys.push(...(txResult?.meta?.loadedAddresses?.writable ?? []));
176
+ messageAccountKeys.push(...(txResult?.meta?.loadedAddresses?.readonly ?? []));
177
+
178
+ for (const ixBlock of txResult.meta?.innerInstructions ?? []) {
179
+ for (const ix of ixBlock.instructions) {
180
+ const ixProgramId = messageAccountKeys[ix.programIdIndex];
181
+ const singleIxAccount = ix.accounts.length === 1 ? messageAccountKeys[ix.accounts[0]] : undefined;
182
+ if (
183
+ ixProgramId !== undefined &&
184
+ singleIxAccount !== undefined &&
185
+ this.svmSpokeAddress === ixProgramId &&
186
+ this.svmSpokeEventAuthority === singleIxAccount
187
+ ) {
188
+ const ixData = utils.bytes.bs58.decode(ix.data);
189
+ // Skip the first 8 bytes (assumed header) and encode the rest.
190
+ const eventData = utils.bytes.base64.encode(Buffer.from(new Uint8Array(ixData).slice(8)));
191
+ const event = new BorshEventCoder(SvmSpokeIdl).decode(eventData);
192
+ if (!event?.name) throw new Error("Event name is undefined");
193
+ const name = getEventName(event.name);
194
+ events.push({
195
+ program: this.svmSpokeAddress,
196
+ data: parseEventData(event?.data),
197
+ name,
198
+ });
199
+ }
200
+ }
201
+ }
202
+
203
+ return events;
204
+ }
205
+ }
@@ -0,0 +1 @@
1
+ export * from "./eventsClient";
@@ -0,0 +1,47 @@
1
+ import { Signature, Address, UnixTimestamp } from "@solana/kit";
2
+ import { SvmSpokeClient } from "@across-protocol/contracts";
3
+
4
+ export type EventData =
5
+ | SvmSpokeClient.BridgedToHubPool
6
+ | SvmSpokeClient.TokensBridged
7
+ | SvmSpokeClient.ExecutedRelayerRefundRoot
8
+ | SvmSpokeClient.RelayedRootBundle
9
+ | SvmSpokeClient.PausedDeposits
10
+ | SvmSpokeClient.PausedFills
11
+ | SvmSpokeClient.SetXDomainAdmin
12
+ | SvmSpokeClient.EnabledDepositRoute
13
+ | SvmSpokeClient.FilledRelay
14
+ | SvmSpokeClient.FundsDeposited
15
+ | SvmSpokeClient.EmergencyDeletedRootBundle
16
+ | SvmSpokeClient.RequestedSlowFill
17
+ | SvmSpokeClient.ClaimedRelayerRefund
18
+ | SvmSpokeClient.TransferredOwnership;
19
+
20
+ export enum SVMEventNames {
21
+ FilledRelay = "FilledRelay",
22
+ FundsDeposited = "FundsDeposited",
23
+ EnabledDepositRoute = "EnabledDepositRoute",
24
+ RelayedRootBundle = "RelayedRootBundle",
25
+ ExecutedRelayerRefundRoot = "ExecutedRelayerRefundRoot",
26
+ BridgedToHubPool = "BridgedToHubPool",
27
+ PausedDeposits = "PausedDeposits",
28
+ PausedFills = "PausedFills",
29
+ SetXDomainAdmin = "SetXDomainAdmin",
30
+ EmergencyDeletedRootBundle = "EmergencyDeletedRootBundle",
31
+ RequestedSlowFill = "RequestedSlowFill",
32
+ ClaimedRelayerRefund = "ClaimedRelayerRefund",
33
+ TokensBridged = "TokensBridged",
34
+ TransferredOwnership = "TransferredOwnership",
35
+ }
36
+
37
+ export type EventName = keyof typeof SVMEventNames;
38
+
39
+ export type EventWithData<T extends EventData> = {
40
+ confirmationStatus: string | null;
41
+ blockTime: UnixTimestamp | null;
42
+ signature: Signature;
43
+ slot: bigint;
44
+ name: EventName;
45
+ data: T;
46
+ program: Address;
47
+ };
@@ -0,0 +1,46 @@
1
+ import { BN } from "@coral-xyz/anchor";
2
+ import web3 from "@solana/kit";
3
+ import { EventName, SVMEventNames } from "../types";
4
+
5
+ /**
6
+ * Parses event data from a transaction.
7
+ */
8
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
9
+ export function parseEventData(eventData: any): any {
10
+ if (!eventData) return eventData;
11
+
12
+ if (Array.isArray(eventData)) {
13
+ return eventData.map(parseEventData);
14
+ }
15
+
16
+ if (typeof eventData === "object") {
17
+ if (eventData.constructor.name === "PublicKey") {
18
+ return web3.address(eventData.toString());
19
+ }
20
+ if (BN.isBN(eventData)) {
21
+ return BigInt(eventData.toString());
22
+ }
23
+
24
+ // Convert each key from snake_case to camelCase and process the value recursively.
25
+ return Object.fromEntries(
26
+ Object.entries(eventData).map(([key, value]) => [snakeToCamel(key), parseEventData(value)])
27
+ );
28
+ }
29
+
30
+ return eventData;
31
+ }
32
+
33
+ /**
34
+ * Converts a snake_case string to camelCase.
35
+ */
36
+ function snakeToCamel(s: string): string {
37
+ return s.replace(/(_\w)/g, (match) => match[1].toUpperCase());
38
+ }
39
+
40
+ /**
41
+ * Gets the event name from a raw name.
42
+ */
43
+ export function getEventName(rawName: string): EventName {
44
+ if (Object.values(SVMEventNames).some((name) => rawName.includes(name))) return rawName as EventName;
45
+ throw new Error(`Unknown event name: ${rawName}`);
46
+ }
@@ -0,0 +1,9 @@
1
+ import web3, { RpcTransport } from "@solana/kit";
2
+
3
+ /**
4
+ * Helper to determine if the current RPC network is devnet.
5
+ */
6
+ export async function isDevnet(rpc: web3.Rpc<web3.SolanaRpcApiFromTransport<RpcTransport>>): Promise<boolean> {
7
+ const genesisHash = await rpc.getGenesisHash().send();
8
+ return genesisHash === "EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG";
9
+ }