@xyo-network/chain-bridge 1.20.15 → 1.20.17

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 (147) hide show
  1. package/README.md +9 -75
  2. package/dist/node/index.mjs +44 -0
  3. package/dist/node/index.mjs.map +1 -1
  4. package/dist/node/queue/flows/createXl1ToEthBridgeJob/getJobIdForXl1ToEthBridgeJob.d.ts +1 -1
  5. package/dist/node/queue/flows/createXl1ToEthBridgeJob/getJobIdForXl1ToEthBridgeJob.d.ts.map +1 -1
  6. package/dist/node/server/routes/addProbeRoutes.d.ts +3 -0
  7. package/dist/node/server/routes/addProbeRoutes.d.ts.map +1 -0
  8. package/dist/node/server/routes/addRoutes.d.ts.map +1 -1
  9. package/dist/node/server/routes/bridge/routeDefinitions/routes/bridgeConfig.d.ts +7 -7
  10. package/dist/node/server/routes/{healthz → livez}/get.d.ts +1 -1
  11. package/dist/node/server/routes/livez/get.d.ts.map +1 -0
  12. package/dist/node/server/routes/livez/index.d.ts.map +1 -0
  13. package/dist/node/server/routes/readyz/get.d.ts +4 -0
  14. package/dist/node/server/routes/readyz/get.d.ts.map +1 -0
  15. package/dist/node/server/routes/readyz/index.d.ts +2 -0
  16. package/dist/node/server/routes/readyz/index.d.ts.map +1 -0
  17. package/dist/node/server/routes/startupz/get.d.ts +4 -0
  18. package/dist/node/server/routes/startupz/get.d.ts.map +1 -0
  19. package/dist/node/server/routes/startupz/index.d.ts +2 -0
  20. package/dist/node/server/routes/startupz/index.d.ts.map +1 -0
  21. package/package.json +143 -54
  22. package/dist/node/server/routes/healthz/get.d.ts.map +0 -1
  23. package/dist/node/server/routes/healthz/index.d.ts.map +0 -1
  24. package/src/BridgeActor.ts +0 -51
  25. package/src/config/asChainId.ts +0 -7
  26. package/src/config/asToken.ts +0 -7
  27. package/src/config/getBridgeEscrowAddress.ts +0 -13
  28. package/src/config/getBridgeFeesAddress.ts +0 -13
  29. package/src/config/getBridgeSettings.ts +0 -24
  30. package/src/config/getBridgeWalletAccount.ts +0 -37
  31. package/src/config/getFeeStructure.ts +0 -8
  32. package/src/config/getMaxBridgeAmount.ts +0 -7
  33. package/src/config/getMinBridgeAmount.ts +0 -7
  34. package/src/config/getRemoteChainId.ts +0 -10
  35. package/src/config/getRemoteTokenAddress.ts +0 -10
  36. package/src/config/getTestGateway.ts +0 -24
  37. package/src/config/getTransferAddresses.ts +0 -17
  38. package/src/config/getXl1ChainId.ts +0 -13
  39. package/src/config/getXl1TokenAddress.ts +0 -12
  40. package/src/config/index.ts +0 -15
  41. package/src/index.ts +0 -1
  42. package/src/interface/index.ts +0 -4
  43. package/src/interface/interface/ChainBridgeRelayInterface.ts +0 -9
  44. package/src/interface/interface/IntentIndexerInterface.ts +0 -8
  45. package/src/interface/interface/LockingProcessorInterface.ts +0 -10
  46. package/src/interface/interface/ObservationIndexerInterface.ts +0 -12
  47. package/src/interface/interface/Params.ts +0 -26
  48. package/src/interface/interface/RelayInterface.ts +0 -8
  49. package/src/interface/interface/index.ts +0 -6
  50. package/src/interface/repository/RepositoryInterface.ts +0 -28
  51. package/src/interface/repository/index.ts +0 -1
  52. package/src/interface/service/Observer/ERC20TransferObserver/ERC20TransferObserver.ts +0 -180
  53. package/src/interface/service/Observer/ERC20TransferObserver/index.ts +0 -1
  54. package/src/interface/service/Observer/LiquidityPoolBridgeObserver/LiquidityPoolBridgeObserver.ts +0 -210
  55. package/src/interface/service/Observer/LiquidityPoolBridgeObserver/index.ts +0 -1
  56. package/src/interface/service/Observer/Observer.ts +0 -48
  57. package/src/interface/service/Observer/index.ts +0 -1
  58. package/src/interface/service/Relay/ChainBridgeRelay/ChainBridgeRelayInterface.ts +0 -11
  59. package/src/interface/service/Relay/ChainBridgeRelay/ChainBridgeRelayService.ts +0 -116
  60. package/src/interface/service/Relay/ChainBridgeRelay/index.ts +0 -1
  61. package/src/interface/service/Relay/LiquidityPoolBridgeRelay/LiquidityPoolBridgeRelay.ts +0 -227
  62. package/src/interface/service/Relay/LiquidityPoolBridgeRelay/index.ts +0 -1
  63. package/src/interface/service/Relay/index.ts +0 -1
  64. package/src/interface/service/index.ts +0 -2
  65. package/src/interface/util/getBridgeIntentIdentifier.ts +0 -18
  66. package/src/interface/util/index.ts +0 -1
  67. package/src/modules/EVMLiquidityBridgeTransactionCompletionMonitorSentinel/EVMLiquidityBridgeTransactionCompletionMonitorSentinel.ts +0 -235
  68. package/src/modules/EVMLiquidityBridgeTransactionCompletionMonitorSentinel/index.ts +0 -1
  69. package/src/modules/index.ts +0 -1
  70. package/src/queue/connection.ts +0 -16
  71. package/src/queue/flowProducer.ts +0 -16
  72. package/src/queue/flows/createEthToXl1BridgeJob.ts +0 -71
  73. package/src/queue/flows/createXl1ToEthBridgeJob/createXl1ToEthBridgeJob.ts +0 -127
  74. package/src/queue/flows/createXl1ToEthBridgeJob/getJobIdForXl1ToEthBridgeJob.ts +0 -18
  75. package/src/queue/flows/createXl1ToEthBridgeJob/getXl1ToEthBridgeJob.ts +0 -11
  76. package/src/queue/flows/createXl1ToEthBridgeJob/index.ts +0 -3
  77. package/src/queue/flows/index.ts +0 -2
  78. package/src/queue/getXl1ToEthQueueJobs.ts +0 -57
  79. package/src/queue/getXl1ToEthQueues.ts +0 -39
  80. package/src/queue/index.ts +0 -8
  81. package/src/queue/prefix.ts +0 -1
  82. package/src/queue/telemetry.ts +0 -12
  83. package/src/queue/workers/EthToXl1BridgeParent.ts +0 -40
  84. package/src/queue/workers/EthTransactionMonitor.ts +0 -59
  85. package/src/queue/workers/EthTransactionPreparation.ts +0 -83
  86. package/src/queue/workers/EthTransactionSubmission.ts +0 -63
  87. package/src/queue/workers/EthTransactionSubmissionStorage.ts +0 -76
  88. package/src/queue/workers/WorkerDescription.ts +0 -10
  89. package/src/queue/workers/Xl1ToEthBridgeParent.ts +0 -41
  90. package/src/queue/workers/Xl1TransactionJobData.ts +0 -12
  91. package/src/queue/workers/Xl1TransactionMonitor.ts +0 -82
  92. package/src/queue/workers/Xl1TransactionPreparation.ts +0 -52
  93. package/src/queue/workers/Xl1TransactionSubmission.ts +0 -70
  94. package/src/queue/workers/Xl1TransactionSubmissionStorage.ts +0 -77
  95. package/src/queue/workers/createWorkers.ts +0 -29
  96. package/src/queue/workers/index.ts +0 -11
  97. package/src/queue/workers/util/index.ts +0 -2
  98. package/src/queue/workers/util/submitEthTransaction.ts +0 -32
  99. package/src/queue/workers/util/submitXl1Transaction.ts +0 -26
  100. package/src/server/addFlowProducer.ts +0 -14
  101. package/src/server/addWorkers.ts +0 -13
  102. package/src/server/app.ts +0 -20
  103. package/src/server/index.ts +0 -19
  104. package/src/server/instrumentation.ts +0 -15
  105. package/src/server/routes/addRoutes.ts +0 -9
  106. package/src/server/routes/bridge/addBridgeRoutes.ts +0 -12
  107. package/src/server/routes/bridge/index.ts +0 -1
  108. package/src/server/routes/bridge/routeDefinitions/getRouteDefinitions.ts +0 -18
  109. package/src/server/routes/bridge/routeDefinitions/index.ts +0 -1
  110. package/src/server/routes/bridge/routeDefinitions/pathParams/ChainIdPathParam.ts +0 -21
  111. package/src/server/routes/bridge/routeDefinitions/pathParams/index.ts +0 -1
  112. package/src/server/routes/bridge/routeDefinitions/routes/bridgeConfig.ts +0 -46
  113. package/src/server/routes/bridge/routeDefinitions/routes/bridgeFromRemoteStatus.ts +0 -58
  114. package/src/server/routes/bridge/routeDefinitions/routes/bridgeToRemote.ts +0 -93
  115. package/src/server/routes/bridge/routeDefinitions/routes/bridgeToRemoteEstimate.ts +0 -69
  116. package/src/server/routes/bridge/routeDefinitions/routes/bridgeToRemoteMaxEstimate.ts +0 -64
  117. package/src/server/routes/bridge/routeDefinitions/routes/bridgeToRemoteStatus.ts +0 -98
  118. package/src/server/routes/bridge/routeDefinitions/routes/index.ts +0 -6
  119. package/src/server/routes/healthz/get.ts +0 -20
  120. package/src/server/routes/healthz/index.ts +0 -1
  121. package/src/server/routes/index.ts +0 -1
  122. package/src/server/server.ts +0 -21
  123. package/src/services/EthTxState.ts +0 -5
  124. package/src/services/IBridgeServiceCollection.ts +0 -19
  125. package/src/services/TxState.ts +0 -14
  126. package/src/services/Xl1TxState.ts +0 -9
  127. package/src/services/getIterableMap.ts +0 -34
  128. package/src/services/getServices.ts +0 -41
  129. package/src/services/index.ts +0 -5
  130. package/src/util/BridgeFees.ts +0 -16
  131. package/src/util/bridgeFeesAsBigInt.ts +0 -15
  132. package/src/util/calculateBridgeFees.ts +0 -33
  133. package/src/util/calculateMaxBridgeAmount.ts +0 -22
  134. package/src/util/createBridgeTransfer.ts +0 -31
  135. package/src/util/generateBridgeEstimate.ts +0 -55
  136. package/src/util/getConfigFromEnv.ts +0 -15
  137. package/src/util/index.ts +0 -7
  138. package/src/validation/AsyncLogger.ts +0 -5
  139. package/src/validation/index.ts +0 -6
  140. package/src/validation/validateBridgeEstimate.ts +0 -60
  141. package/src/validation/validateBridgeEstimateExact.ts +0 -39
  142. package/src/validation/validateBridgeTransaction.ts +0 -53
  143. package/src/validation/validateSufficientLiquiditySourceAllowance.ts +0 -39
  144. package/src/validation/validateSufficientLiquiditySourceBalance.ts +0 -38
  145. package/src/validation/validateSufficientRunnerEthBalanceForGas.ts +0 -57
  146. package/src/validation/validateSufficientXL1SourceAddressBalance.ts +0 -39
  147. /package/dist/node/server/routes/{healthz → livez}/index.d.ts +0 -0
@@ -1,41 +0,0 @@
1
- import type { Hash } from '@xylabs/sdk-js'
2
- import { assertEx, isDefined } from '@xylabs/sdk-js'
3
- import type { BridgeConfig, BridgeConfigContext } from '@xyo-network/chain-orchestration'
4
- import { initEvmProvider } from '@xyo-network/chain-orchestration'
5
- import { HDWallet } from '@xyo-network/sdk-js'
6
- import { BridgeableToken__factory, LiquidityPoolBridge__factory } from '@xyo-network/typechain'
7
- import type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'
8
- import { getAddress, Wallet } from 'ethers'
9
-
10
- import type { EthTxState } from './EthTxState.ts'
11
- import { getIterableMap } from './getIterableMap.ts'
12
- import type { IBridgeServiceCollection } from './IBridgeServiceCollection.ts'
13
- import type { Xl1TxState } from './Xl1TxState.ts'
14
-
15
- /**
16
- * Used for retrieving a service collection
17
- * @returns A service collection
18
- */
19
- export const getServices = async (context: BridgeConfigContext, gateway: XyoGatewayRunner): Promise<IBridgeServiceCollection> => {
20
- const { config } = context
21
-
22
- const ethTxStateMap = await getIterableMap<Hash, EthTxState>(config, 'liquidity_bridge_xl1_to_eth_eth_tx_state')
23
- const xl1TxStateMap = await getIterableMap<Hash, Xl1TxState>(config, 'liquidity_bridge_xl1_to_eth_xl1_tx_state')
24
- const provider = await initEvmProvider(context)
25
- const {
26
- remoteBridgeContractAddress, remoteChainWalletPrivateKey, remoteTokenAddress, mnemonic,
27
- } = config as BridgeConfig
28
- const account = isDefined(mnemonic) ? await HDWallet.fromPhrase(mnemonic) : await HDWallet.random()
29
- const wallet = new Wallet(remoteChainWalletPrivateKey, provider)
30
- const bridgeableToken = BridgeableToken__factory.connect(getAddress(remoteTokenAddress), wallet)
31
- const bridge = LiquidityPoolBridge__factory.connect(getAddress(remoteBridgeContractAddress), wallet)
32
- // const approvalAmount = 18n * 10n ** 9n * 10n ** 18n // 18 billion tokens with 18 decimals
33
- // const contractApprovalTx = await bridgeableToken.connect(wallet).approve(bridge.getAddress(), approvalAmount)
34
- // await contractApprovalTx.wait(1)
35
- // Assert we are contract owner so we can call ownable methods
36
- const bridgeOwner = await bridge.owner()
37
- assertEx(bridgeOwner.toLowerCase() === wallet.address.toLowerCase(), () => 'Wallet is not the owner of the bridge contract')
38
- return {
39
- account, bridge, bridgeableToken, ethTxStateMap, gateway, provider, wallet, xl1TxStateMap,
40
- }
41
- }
@@ -1,5 +0,0 @@
1
- export * from './EthTxState.ts'
2
- export * from './getServices.ts'
3
- export * from './IBridgeServiceCollection.ts'
4
- export * from './TxState.ts'
5
- export * from './Xl1TxState.ts'
@@ -1,16 +0,0 @@
1
- import {
2
- type Hex, HexZod, type JsonObject,
3
- } from '@xylabs/sdk-js'
4
- import { z } from 'zod'
5
-
6
- export interface BridgeFees extends JsonObject {
7
- feeFixed: Hex
8
- feeVariable: Hex
9
- srcAmount: Hex
10
- }
11
-
12
- export const BridgeFeesZod = z.object({
13
- feeFixed: HexZod,
14
- feeVariable: HexZod,
15
- srcAmount: HexZod,
16
- })
@@ -1,15 +0,0 @@
1
- import { hexToBigInt } from '@xylabs/sdk-js'
2
-
3
- import type { BridgeFees } from './BridgeFees.ts'
4
-
5
- export const bridgeFeesAsBigInt = (fees: BridgeFees): {
6
- feeFixed: bigint
7
- feeVariable: bigint
8
- srcAmount: bigint
9
- } => {
10
- return {
11
- feeFixed: hexToBigInt(fees.feeFixed),
12
- feeVariable: hexToBigInt(fees.feeVariable),
13
- srcAmount: hexToBigInt(fees.srcAmount),
14
- }
15
- }
@@ -1,33 +0,0 @@
1
- import type { Hex } from '@xylabs/sdk-js'
2
- import { hexToBigInt, toHex } from '@xylabs/sdk-js'
3
- import type { BridgeConfig } from '@xyo-network/chain-orchestration'
4
-
5
- import type { BridgeFees } from './BridgeFees.ts'
6
-
7
- export type FeeStructure = Pick<BridgeConfig, 'feeFixed' | 'feeRateBasisPoints'>
8
-
9
- export const calculateBridgeFees = (srcAmount: Hex, feeStructure: FeeStructure): BridgeFees => {
10
- const { feeFixed, feeRateBasisPoints } = feeStructure
11
-
12
- // Format source input
13
- const srcAmountBigInt = hexToBigInt(srcAmount)
14
-
15
- // Calculate fixed fee
16
- // const feeFixedBigInt = hexToBigInt(feeFixed)
17
-
18
- // Integer-safe basis point calculation (floor division)
19
- const feeVariableBigInt
20
- = (srcAmountBigInt * BigInt(feeRateBasisPoints)) / 10_000n
21
- const feeVariable = toHex(feeVariableBigInt)
22
-
23
- // Calculate total fee
24
- // const feeTotalBigInt = feeFixedBigInt + feeVariableBigInt
25
-
26
- // Calculate destination amount
27
- // const destAmountBigInt = srcAmountBigInt > feeTotalBigInt ? srcAmountBigInt - feeTotalBigInt : 0n
28
- // const destAmount = toHex(destAmountBigInt)
29
-
30
- return {
31
- feeFixed, feeVariable, srcAmount,
32
- }
33
- }
@@ -1,22 +0,0 @@
1
- import type { Hex } from '@xylabs/sdk-js'
2
- import { hexToBigInt, toHex } from '@xylabs/sdk-js'
3
-
4
- import type { FeeStructure } from './calculateBridgeFees.ts'
5
-
6
- /**
7
- * Given a user's total available balance, calculates the maximum amount they can bridge
8
- * after accounting for the fixed and variable bridge fees.
9
- *
10
- * Solving for M where: M + feeFixed + (M * basisPoints / 10_000) = balance
11
- * => M = (balance - feeFixed) * 10_000 / (10_000 + basisPoints)
12
- */
13
- export const calculateMaxBridgeAmount = (balance: Hex, feeStructure: FeeStructure): Hex => {
14
- const { feeFixed, feeRateBasisPoints } = feeStructure
15
- const balanceBigInt = hexToBigInt(balance)
16
- const feeFixedBigInt = hexToBigInt(feeFixed)
17
-
18
- if (balanceBigInt <= feeFixedBigInt) return toHex(0n)
19
-
20
- const maxAmount = ((balanceBigInt - feeFixedBigInt) * 10_000n) / (10_000n + BigInt(feeRateBasisPoints))
21
- return toHex(maxAmount)
22
- }
@@ -1,31 +0,0 @@
1
- import type { Address, Hex } from '@xylabs/sdk-js'
2
- import { hexToBigInt } from '@xylabs/sdk-js'
3
- import type { Transfer } from '@xyo-network/xl1-sdk'
4
- import { createTransferPayload } from '@xyo-network/xl1-sdk'
5
-
6
- import type { BridgeFees } from './BridgeFees.ts'
7
-
8
- /**
9
- * Calculates the transfer representing the bridging of funds including the appropriate amounts for the bridge fees
10
- * @param sender The client attempting to bridge
11
- * @param srcAmount The amount the client is attempting to bridge
12
- * @param escrowAddress The address in which bridged funds will be held until the transfer is executed on the destination chain
13
- * @param feesAddress The address to which bridge fees will be paid
14
- * @param context An object containing the necessary fee and amount information to construct the transfer context
15
- * @returns A transfer representing the bridging of funds including the appropriate amounts for the bridge fees
16
- */
17
- export const createBridgeTransfer = (sender: Address, srcAmount: Hex, escrowAddress: Address, feesAddress: Address, context: BridgeFees): Transfer => {
18
- const { feeFixed, feeVariable } = context
19
- const escrowAmount = hexToBigInt(srcAmount)
20
- const feesAmount = hexToBigInt(feeFixed) + hexToBigInt(feeVariable)
21
- const transfers: Record<Address, bigint>
22
- // If the escrow and fee addresses are the same
23
- = escrowAddress === feesAddress
24
- // combine the amounts into a single transfer to that address
25
- ? { [feesAddress]: escrowAmount + feesAmount }
26
- // otherwise, create separate transfers to the escrow and fees addresses
27
- : { [escrowAddress]: escrowAmount, [feesAddress]: feesAmount }
28
- const transfer = createTransferPayload(sender, transfers, context)
29
-
30
- return transfer
31
- }
@@ -1,55 +0,0 @@
1
- import type { Hex } from '@xylabs/sdk-js'
2
- import { toAddress } from '@xylabs/sdk-js'
3
- import type { BridgeConfig } from '@xyo-network/chain-orchestration'
4
- import { PayloadBuilder } from '@xyo-network/sdk-js'
5
- import type {
6
- BridgeIntent, BridgeIntentFields, Transfer,
7
- } from '@xyo-network/xl1-sdk'
8
- import { BridgeIntentSchema } from '@xyo-network/xl1-sdk'
9
- import { v4 } from 'uuid'
10
-
11
- import { getBridgeSettings } from '../config/index.ts'
12
- import { calculateBridgeFees } from './calculateBridgeFees.ts'
13
- import { createBridgeTransfer } from './createBridgeTransfer.ts'
14
-
15
- export const generateBridgeEstimate = async (
16
- srcAddress: Hex,
17
- srcAmount: Hex,
18
- destAddress: Hex,
19
- config: BridgeConfig,
20
- nonceOverride?: string,
21
- ): Promise<[BridgeIntent, Transfer]> => {
22
- const {
23
- escrowAddress, feeFixed, feeRateBasisPoints, feesAddress, remoteChainId, remoteTokenAddress, xl1ChainId, xl1TokenAddress,
24
- } = await getBridgeSettings(config)
25
-
26
- const sender = toAddress(srcAddress)
27
-
28
- // Calculate fees and destination amount
29
- const fees = calculateBridgeFees(srcAmount, { feeFixed, feeRateBasisPoints })
30
-
31
- // Generate a unique nonce for the bridge intent
32
- const nonce = nonceOverride ?? v4()
33
-
34
- // Build the bridge intent
35
- const bridgeIntentFields: BridgeIntentFields = {
36
- // Source
37
- src: xl1ChainId,
38
- srcAddress: sender,
39
- srcAmount,
40
- srcToken: xl1TokenAddress,
41
-
42
- // Destination
43
- dest: remoteChainId,
44
- destAddress,
45
- destAmount: srcAmount, // This is a 1:1 bridge. Fees are handled at the transfer level, not the bridge intent level.
46
- destToken: remoteTokenAddress,
47
- nonce,
48
- }
49
- const bridgeIntent: BridgeIntent = new PayloadBuilder<BridgeIntent>({ schema: BridgeIntentSchema }).fields(bridgeIntentFields).build()
50
-
51
- // Build the transfer
52
- const transfer = createBridgeTransfer(sender, srcAmount, escrowAddress, feesAddress, fees)
53
-
54
- return [bridgeIntent, transfer]
55
- }
@@ -1,15 +0,0 @@
1
- import { type Config, ConfigZod } from '@xyo-network/xl1-sdk'
2
- import type { Configuration } from 'yargs-parser'
3
- import parser from 'yargs-parser'
4
-
5
- export const ConfigParserEnvPrefix = 'XL1_'
6
- export const ConfigParserConfiguration: Partial<Configuration> = {
7
- 'dot-notation': true, // foo.bar → { foo: { bar } }
8
- 'parse-numbers': false, // Don't auto-parse numbers to allow strings like "0x1"
9
- 'populate--': true, // Populate -- with all options so we can detected user-supplied vs defaults
10
- }
11
-
12
- export const getConfigFromEnv = (): Config => {
13
- const parsed = parser([], { configuration: ConfigParserConfiguration, envPrefix: ConfigParserEnvPrefix })
14
- return ConfigZod.parse(parsed)
15
- }
package/src/util/index.ts DELETED
@@ -1,7 +0,0 @@
1
- export * from './BridgeFees.ts'
2
- export * from './bridgeFeesAsBigInt.ts'
3
- export * from './calculateBridgeFees.ts'
4
- export * from './calculateMaxBridgeAmount.ts'
5
- export * from './createBridgeTransfer.ts'
6
- export * from './generateBridgeEstimate.ts'
7
- export * from './getConfigFromEnv.ts'
@@ -1,5 +0,0 @@
1
- import type { Promisable } from '@xylabs/sdk-js'
2
-
3
- export interface AsyncLogger {
4
- log: (message: string) => Promisable<unknown>
5
- }
@@ -1,6 +0,0 @@
1
- export * from './validateBridgeEstimateExact.ts'
2
- export * from './validateBridgeTransaction.ts'
3
- export * from './validateSufficientLiquiditySourceAllowance.ts'
4
- export * from './validateSufficientLiquiditySourceBalance.ts'
5
- export * from './validateSufficientRunnerEthBalanceForGas.ts'
6
- export * from './validateSufficientXL1SourceAddressBalance.ts'
@@ -1,60 +0,0 @@
1
- import { hexToBigInt, isUndefined } from '@xylabs/sdk-js'
2
- import type { BridgeConfig } from '@xyo-network/chain-orchestration'
3
- import type { BridgeIntent, Transfer } from '@xyo-network/xl1-sdk'
4
-
5
- import { getBridgeSettings } from '../config/index.ts'
6
- import { calculateBridgeFees } from '../util/index.ts'
7
-
8
- /**
9
- * Validates a bridge estimate by checking the intent and transfer against the provided configuration. This method
10
- * exists to allow for "at least" validation of a bridge estimates in case we want to allow for some flexibility in
11
- * the bridge estimate.
12
- * @param intent The BridgeIntent
13
- * @param transfer The Transfer
14
- * @param config The Config
15
- * @returns True if the bridge estimate satisfies bridging conditions, false otherwise.
16
- */
17
- export const validateBridgeEstimate = async (
18
- intent: BridgeIntent,
19
- transfer: Transfer,
20
- config: BridgeConfig,
21
- ): Promise<boolean> => {
22
- const {
23
- escrowAddress, feeFixed, feeRateBasisPoints, feesAddress, remoteChainId, remoteTokenAddress, xl1ChainId, xl1TokenAddress,
24
- } = await getBridgeSettings(config)
25
-
26
- // 1. Basic chain + token checks
27
- if (intent.src !== xl1ChainId) return false
28
- if (intent.dest !== remoteChainId) return false
29
- if (intent.srcToken !== xl1TokenAddress) return false
30
- if (intent.destToken !== remoteTokenAddress) return false
31
-
32
- // 2. Validate transfer outputs: escrow receives destAmount,
33
- // feesAddress receives feeFixed + variableFee.
34
- const outputs = transfer?.transfers ?? {}
35
- const escrowOut = outputs[escrowAddress]
36
- const feeOut = outputs[feesAddress]
37
- if (isUndefined(escrowOut) || isUndefined(feeOut)) return false
38
-
39
- // Convert hex amounts
40
- const destAmount = hexToBigInt(intent.destAmount)
41
- const escrowAmount = hexToBigInt(escrowOut)
42
-
43
- if (escrowAmount !== destAmount) return false
44
-
45
- // 3. Recalculate fees and compare
46
- const fees = calculateBridgeFees(intent.srcAmount, { feeFixed, feeRateBasisPoints })
47
-
48
- const expectedFeeTotal
49
- = hexToBigInt(fees.feeFixed) + hexToBigInt(fees.feeVariable)
50
-
51
- const feeAmount = hexToBigInt(feeOut)
52
- if (feeAmount < expectedFeeTotal) return false
53
-
54
- // 4. Check derived dest amount
55
- if (hexToBigInt(intent.destAmount) !== hexToBigInt(fees.srcAmount)) {
56
- return false
57
- }
58
-
59
- return true
60
- }
@@ -1,39 +0,0 @@
1
- import { hexToBigInt, isUndefined } from '@xylabs/sdk-js'
2
- import type { BridgeConfig } from '@xyo-network/chain-orchestration'
3
- import { PayloadBuilder } from '@xyo-network/sdk-js'
4
- import type { BridgeIntent, Transfer } from '@xyo-network/xl1-sdk'
5
-
6
- import { getMaxBridgeAmount } from '../config/index.ts'
7
- import { generateBridgeEstimate } from '../util/index.ts'
8
-
9
- /**
10
- * Validates a bridge estimate by checking the intent and transfer against the provided configuration. This method
11
- * only returns true if the bridge estimate matches exactly.
12
- * @param intent The BridgeIntent
13
- * @param transfer The Transfer
14
- * @param config The Config
15
- * @returns True if the bridge estimate satisfies bridging conditions, false otherwise.
16
- */
17
- export const validateBridgeEstimateExact = async (
18
- intent: BridgeIntent,
19
- transfer: Transfer,
20
- config: BridgeConfig,
21
- ): Promise<boolean> => {
22
- const {
23
- srcAddress, srcAmount, destAddress,
24
- } = intent
25
-
26
- // Reject if the requested amount exceeds the configured maximum
27
- if (hexToBigInt(srcAmount) > hexToBigInt(getMaxBridgeAmount(config))) return false
28
-
29
- const [calculatedIntent, calculatedTransfer] = await generateBridgeEstimate(srcAddress, srcAmount, destAddress, config)
30
- if (isUndefined(calculatedIntent) || isUndefined(calculatedTransfer)) return false
31
- const { nonce: expectedIntentNonce, ...expectedIntentStatic } = calculatedIntent
32
- const { nonce: actualIntentNonce, ...actualIntentStatic } = intent
33
- if (await PayloadBuilder.dataHash(expectedIntentStatic) !== await PayloadBuilder.dataHash(actualIntentStatic)) return false
34
- const { epoch: expectedTransferEpoch, ...expectedTransferStatic } = calculatedTransfer
35
- const { epoch: actualTransferEpoch, ...actualTransferStatic } = transfer
36
- if (await PayloadBuilder.dataHash(expectedTransferStatic) !== await PayloadBuilder.dataHash(actualTransferStatic)) return false
37
-
38
- return true
39
- }
@@ -1,53 +0,0 @@
1
- import { asAddress } from '@xylabs/sdk-js'
2
- import {
3
- addressesContains, BoundWitnessValidator, payloadHashesContainsAll, payloadSchemasContainsAll,
4
- } from '@xyo-network/boundwitness-validator'
5
- import type { BridgeConfig } from '@xyo-network/chain-orchestration'
6
- import { PayloadBuilder } from '@xyo-network/sdk-js'
7
- import type {
8
- BridgeIntent, TransactionBoundWitness, Transfer,
9
- } from '@xyo-network/xl1-sdk'
10
- import { BridgeIntentSchema, TransferSchema } from '@xyo-network/xl1-sdk'
11
-
12
- import { getXl1ChainId } from '../config/index.ts'
13
-
14
- /**
15
- * Validates a bridge estimate by checking the intent and transfer against the provided configuration. This method
16
- * exists to allow for "at least" validation of a bridge estimates in case we want to allow for some flexibility in
17
- * the bridge estimate.
18
- * @ param signedTransaction The signed transaction bound witness
19
- * @param signedTxBw The signed transaction bound witness
20
- * @param intent The BridgeIntent
21
- * @param transfer The Transfer
22
- * @param config The Config
23
- * @returns True if the bridge estimate satisfies bridging conditions, false otherwise.
24
- */
25
- export const validateBridgeTransaction = async (
26
- signedTxBw: TransactionBoundWitness,
27
- intent: BridgeIntent,
28
- transfer: Transfer,
29
- config: BridgeConfig,
30
- ): Promise<boolean> => {
31
- const { srcAddress } = intent
32
-
33
- // Ensure the transaction is for the correct source chain
34
- const chainId = getXl1ChainId(config)
35
- if (signedTxBw.chain !== chainId) return false
36
-
37
- // Ensure only the expected number of payloads exist (do not allow ambiguous extras)
38
- if (signedTxBw.payload_hashes.length != 2) return false
39
- // Ensure the payloads match the expected schemas
40
- if (!payloadSchemasContainsAll(signedTxBw, [BridgeIntentSchema, TransferSchema])) return false
41
- // Ensure the hashes match the intent and transfer
42
- const hashes = await PayloadBuilder.hashes([intent, transfer])
43
- if (!payloadHashesContainsAll(signedTxBw, hashes)) return false
44
- // Ensure the BoundWitness is valid and signed by the sender
45
- const errors = await new BoundWitnessValidator(signedTxBw).validate()
46
- if (errors.length > 0) return false
47
-
48
- // Ensure the sender's address is included in the addresses
49
- const sender = asAddress(srcAddress, true)
50
- if (!addressesContains(signedTxBw, sender)) return false
51
-
52
- return true
53
- }
@@ -1,39 +0,0 @@
1
- import { assertEx, hexToBigInt } from '@xylabs/sdk-js'
2
- import type { Payload } from '@xyo-network/sdk-js'
3
- import type { BridgeableToken, LiquidityPoolBridge } from '@xyo-network/typechain'
4
- import { isBridgeIntent, type SignedHydratedTransaction } from '@xyo-network/xl1-sdk'
5
-
6
- import type { AsyncLogger } from './AsyncLogger.ts'
7
-
8
- /**
9
- * Checks if the liquidity source has sufficient allowance for the bridge to execute the transaction. This doesn't
10
- * ensure that (due to race conditions) the transaction will succeed, but is a quick check to avoid
11
- * submitting transactions that are likely to fail.
12
- * @param tx The transaction containing a bridge intent
13
- * @param offChainPayloads The payloads to put off chain
14
- * @param bridgeableToken The contract for the token being bridged
15
- * @param bridge The contract for the liquidity bridge
16
- * @param logger Optional logger for asynchronous logging
17
- * @returns True if the liquidity source allowance is sufficient to execute the bridge
18
- */
19
- export const validateSufficientLiquiditySourceAllowance = async (
20
- tx: SignedHydratedTransaction,
21
- offChainPayloads: Payload[],
22
- bridgeableToken: BridgeableToken,
23
- bridge: LiquidityPoolBridge,
24
- logger?: AsyncLogger,
25
- ) => {
26
- // Get the amount being bridged from the bridge intent
27
- const allPayloads = [...tx[1], ...offChainPayloads]
28
- const bridgeIntent = assertEx(allPayloads.find(isBridgeIntent), () => 'No bridge intent found')
29
- const amount = hexToBigInt(bridgeIntent.destAmount)
30
-
31
- // Get the addresses
32
- const liquiditySourceAddress = await bridge.liquiditySource()
33
- const bridgeAddress = await bridge.getAddress()
34
-
35
- // Check the allowance of the liquidity source for the bridge
36
- const remainingAllowance = await bridgeableToken.allowance(liquiditySourceAddress, bridgeAddress)
37
- await logger?.log(`Remaining allowance: ${remainingAllowance.toString()}`)
38
- return remainingAllowance >= amount
39
- }
@@ -1,38 +0,0 @@
1
- import { assertEx, hexToBigInt } from '@xylabs/sdk-js'
2
- import type { Payload } from '@xyo-network/sdk-js'
3
- import type { BridgeableToken, LiquidityPoolBridge } from '@xyo-network/typechain'
4
- import { isBridgeIntent, type SignedHydratedTransaction } from '@xyo-network/xl1-sdk'
5
-
6
- import type { AsyncLogger } from './AsyncLogger.ts'
7
-
8
- /**
9
- * Checks if the liquidity source has sufficient balance for the bridge to execute the transaction. This doesn't
10
- * ensure that (due to race conditions) the transaction will succeed, but is a quick check to avoid
11
- * submitting transactions that are likely to fail.
12
- * @param tx The transaction containing a bridge intent
13
- * @param offChainPayloads The payloads to put off chain
14
- * @param bridgeableToken The contract for the token being bridged
15
- * @param bridge The contract for the liquidity bridge
16
- * @param logger Optional logger for asynchronous logging
17
- * @returns True if the liquidity source balance is sufficient to execute the bridge
18
- */
19
- export const validateSufficientLiquiditySourceBalance = async (
20
- tx: SignedHydratedTransaction,
21
- offChainPayloads: Payload[],
22
- bridgeableToken: BridgeableToken,
23
- bridge: LiquidityPoolBridge,
24
- logger?: AsyncLogger,
25
- ) => {
26
- // Get the amount being bridged from the bridge intent
27
- const allPayloads = [...tx[1], ...offChainPayloads]
28
- const bridgeIntent = assertEx(allPayloads.find(isBridgeIntent), () => 'No bridge intent found')
29
- const amount = hexToBigInt(bridgeIntent.destAmount)
30
-
31
- // Get the addresses
32
- const liquiditySourceAddress = await bridge.liquiditySource()
33
-
34
- // Check the balance of the liquidity source for the bridge
35
- const balance = await bridgeableToken.balanceOf(liquiditySourceAddress)
36
- await logger?.log(`Remaining balance: ${balance.toString()}`)
37
- return balance >= amount
38
- }
@@ -1,57 +0,0 @@
1
- import { assertEx } from '@xylabs/sdk-js'
2
- import type { ContractTransaction, Wallet } from 'ethers'
3
-
4
- import type { AsyncLogger } from './AsyncLogger.ts'
5
-
6
- const DEFAULT_GAS_BUFFER_BPS = 2000n // 20%
7
-
8
- /**
9
- * Validates that the wallet (the account that will submit the tx) has enough ETH
10
- * to cover the estimated gas cost (plus a buffer) for the transaction.
11
- * @param preparedTx The transaction that is being prepared for submission.
12
- * This should be a fully populated transaction (to/from/data/value) except for gas fields.
13
- * @param wallet The wallet that will be used to submit the transaction.
14
- * @param logger Optional logger for asynchronous logging.
15
- * @param bufferBps The buffer to apply to the estimated gas cost, in basis points (1/100th of a percent).
16
- * @returns A boolean indicating whether the wallet has sufficient ETH to cover the estimated gas cost with the buffer applied.
17
- */
18
- export const validateSufficientRunnerEthBalanceForGas = async (
19
- preparedTx: ContractTransaction,
20
- wallet: Wallet,
21
- logger?: AsyncLogger,
22
- bufferBps: bigint = DEFAULT_GAS_BUFFER_BPS,
23
- ) => {
24
- const provider = assertEx(wallet.provider, () => 'Wallet provider is not defined')
25
-
26
- // Fee data (EIP-1559 preferred, gasPrice fallback)
27
- const feeData = await provider.getFeeData()
28
- const perGas = feeData.maxFeePerGas ?? feeData.gasPrice
29
- if (perGas == null) {
30
- await logger?.log('[gas] unable to resolve gas price / maxFeePerGas from provider')
31
- return true // don’t hard-fail; provider may not support fee data
32
- }
33
-
34
- // Estimate gas
35
- const transactionRequest = {
36
- ...preparedTx,
37
- from: await wallet.getAddress(),
38
- }
39
- const estGas = await provider.estimateGas(transactionRequest)
40
-
41
- // Include any value sent with the tx
42
- const txValue = preparedTx?.value ?? 0n
43
-
44
- // Required = (gas * perGas + value) * (1 + buffer)
45
- const baseRequired = estGas * perGas + txValue
46
- const required = (baseRequired * (10_000n + bufferBps)) / 10_000n
47
-
48
- const balance = await provider.getBalance(await wallet.getAddress())
49
-
50
- await logger?.log(
51
- `[gas] runner=${await wallet.getAddress()} balance=${balance.toString()} `
52
- + `estGas=${estGas.toString()} perGas=${perGas.toString()} value=${txValue.toString()} `
53
- + `requiredWithBuffer=${required.toString()} bufferBps=${bufferBps.toString()}`,
54
- )
55
-
56
- return balance >= required
57
- }
@@ -1,39 +0,0 @@
1
- import {
2
- asAddress, assertEx, hexToBigInt,
3
- } from '@xylabs/sdk-js'
4
- import type { BridgeConfig } from '@xyo-network/chain-orchestration'
5
- import type { BridgeIntent, XyoGatewayRunner } from '@xyo-network/xl1-sdk'
6
-
7
- import { generateBridgeEstimate } from '../util/index.ts'
8
- import type { AsyncLogger } from './AsyncLogger.ts'
9
-
10
- /**
11
- * Checks if the liquidity source has sufficient balance for the bridge to execute the transaction. This doesn't
12
- * ensure that (due to race conditions) the transaction will succeed, but is a quick check to avoid
13
- * submitting transactions that are likely to fail.
14
- * @param bridgeIntent The bridge intent containing the details of the bridge transaction, including the source address and amount being bridged
15
- * @param gateway The XyoGatewayRunner to check the balance of the source address on XL1
16
- * @param config The bridge configuration, used to generate a bridge estimate for the transaction
17
- * @param logger Optional logger for asynchronous logging
18
- * @returns True if the liquidity source balance is sufficient to execute the bridge
19
- */
20
- export const validateSufficientXL1SourceAddressBalance = async (
21
- bridgeIntent: BridgeIntent,
22
- gateway: XyoGatewayRunner,
23
- config: BridgeConfig,
24
- logger?: AsyncLogger,
25
- ) => {
26
- // Get the amount being bridged from the bridge intent
27
- const viewer = assertEx(gateway.connection.viewer, () => 'Gateway connection does not have a viewer')
28
- const {
29
- srcAddress, srcAmount, destAddress,
30
- } = bridgeIntent
31
- const srcAddressBranded = asAddress(srcAddress, () => `Invalid source address in bridge intent: ${srcAddress}`)
32
- const [_, calculatedTransfer] = await generateBridgeEstimate(srcAddress, srcAmount, destAddress, config)
33
- const totalAmount = Object.values(calculatedTransfer.transfers).reduce((acc, transfer) => acc + hexToBigInt(transfer), 0n)
34
-
35
- // Check the srcAddress balance on XL1 for the bridge
36
- const accountBalance = await viewer.account.balance.accountBalance(srcAddressBranded)
37
- await logger?.log(`Account balance for ${srcAddressBranded}: ${accountBalance.toString()}`)
38
- return accountBalance >= totalAmount
39
- }