-
Notifications
You must be signed in to change notification settings - Fork 99
Sparrow dom/cctp defender action #2770
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
sparrowDom
merged 19 commits into
shah/cross-chain-strategy-cctpv2
from
sparrowDom/cctpDefenderAction
Jan 28, 2026
Merged
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
8815ab5
Add unit tests (#2751)
sparrowDom 7e59c4d
add comment
sparrowDom 09ad576
create a defender task and cleanup
sparrowDom b83ca3d
small change
sparrowDom 16cf9c3
add the ability for the defender relay action to store already proces…
sparrowDom d41bde1
update gitignore
sparrowDom 4682387
prettier
sparrowDom a2cbea3
Merge remote-tracking branch 'origin/shah/cross-chain-strategy-cctpv2…
sparrowDom b07b4de
put into a better place
sparrowDom be5d261
...
sparrowDom 9493fb9
add dry run option, also fix issues with cross chain providers
sparrowDom 3719866
read cctp domain ids from config
sparrowDom 4d5f5a7
make api a constant
sparrowDom 7cc57f2
remove finality checks
sparrowDom 57b2942
add custom per chain block lookback
sparrowDom a8368c0
readme change
sparrowDom ef2b043
move all configuration out of cross-chain source file, to more easily…
sparrowDom 167d3ad
clear the testing addresses
sparrowDom 19f4931
prettier
sparrowDom File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| const { ethers } = require("ethers"); | ||
| const { Defender } = require("@openzeppelin/defender-sdk"); | ||
| const { processCctpBridgeTransactions } = require("../../tasks/crossChain"); | ||
| const { getNetworkName } = require("../../utils/hardhat-helpers"); | ||
| const { configuration } = require("../../utils/cctp"); | ||
|
|
||
| // Entrypoint for the Defender Action | ||
| const handler = async (event) => { | ||
| console.log( | ||
| `DEBUG env var in handler before being set: "${process.env.DEBUG}"` | ||
| ); | ||
|
|
||
| // Initialize defender relayer provider and signer | ||
| const client = new Defender(event); | ||
| // Chain ID of the target contract relayer signer | ||
| const provider = client.relaySigner.getProvider({ ethersVersion: "v5" }); | ||
| const { chainId } = await provider.getNetwork(); | ||
| let sourceProvider; | ||
| const signer = await client.relaySigner.getSigner(provider, { | ||
| speed: "fastest", | ||
| ethersVersion: "v5", | ||
| }); | ||
|
|
||
| // destinatino chain is mainnet, source chain is base | ||
| if (chainId === 1) { | ||
| if (!event.secrets.BASE_PROVIDER_URL) { | ||
| throw new Error("BASE_PROVIDER_URL env var required"); | ||
| } | ||
| sourceProvider = new ethers.providers.JsonRpcProvider( | ||
| event.secrets.BASE_PROVIDER_URL | ||
| ); | ||
| } | ||
| // destination chain is base, source chain is mainnet | ||
| else if (chainId === 8453) { | ||
| if (!event.secrets.PROVIDER_URL) { | ||
| throw new Error("PROVIDER_URL env var required"); | ||
| } | ||
| sourceProvider = new ethers.providers.JsonRpcProvider( | ||
| event.secrets.PROVIDER_URL | ||
| ); | ||
| } else { | ||
| throw new Error(`Unsupported chain id: ${chainId}`); | ||
| } | ||
|
|
||
| const networkName = await getNetworkName(sourceProvider); | ||
| const isMainnet = networkName === "mainnet"; | ||
| const isBase = networkName === "base"; | ||
|
|
||
| let config; | ||
| if (isMainnet) { | ||
| config = configuration.mainnetBaseMorpho.mainnet; | ||
| } else if (isBase) { | ||
| config = configuration.mainnetBaseMorpho.base; | ||
| } else { | ||
| throw new Error(`Unsupported network name: ${networkName}`); | ||
| } | ||
|
|
||
| await processCctpBridgeTransactions({ | ||
| destinationChainSigner: signer, | ||
| sourceChainProvider: sourceProvider, | ||
| store: client.keyValueStore, | ||
| networkName, | ||
| blockLookback: config.blockLookback, | ||
| cctpDestinationDomainId: config.cctpDestinationDomainId, | ||
| cctpSourceDomainId: config.cctpSourceDomainId, | ||
| cctpIntegrationContractAddress: config.cctpIntegrationContractAddress, | ||
| cctpIntegrationContractAddressDestination: | ||
| config.cctpIntegrationContractAddressDestination, | ||
| }); | ||
| }; | ||
|
|
||
| module.exports = { handler }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,213 @@ | ||
| //const { KeyValueStoreClient } = require("@openzeppelin/defender-sdk"); | ||
| const ethers = require("ethers"); | ||
| const { logTxDetails } = require("../utils/txLogger"); | ||
| const { api: cctpApi } = require("../utils/cctp"); | ||
|
|
||
| const cctpOperationsConfig = async ({ | ||
| destinationChainSigner, | ||
| sourceChainProvider, | ||
| networkName, | ||
| cctpIntegrationContractAddress, | ||
| cctpIntegrationContractAddressDestination, | ||
| }) => { | ||
| const cctpIntegratorAbi = [ | ||
| "event TokensBridged(uint32 peerDomainID,address peerStrategy,address usdcToken,uint256 tokenAmount,uint256 maxFee,uint32 minFinalityThreshold,bytes hookData)", | ||
| "event MessageTransmitted(uint32 peerDomainID,address peerStrategy,uint32 minFinalityThreshold,bytes message)", | ||
| "function relay(bytes message, bytes attestation) external", | ||
| ]; | ||
|
|
||
| const cctpIntegrationContractSource = new ethers.Contract( | ||
| cctpIntegrationContractAddress, | ||
| cctpIntegratorAbi, | ||
| sourceChainProvider | ||
| ); | ||
| const cctpIntegrationContractDestination = new ethers.Contract( | ||
| cctpIntegrationContractAddressDestination, | ||
| cctpIntegratorAbi, | ||
| destinationChainSigner | ||
| ); | ||
|
|
||
| return { | ||
| networkName, | ||
| cctpIntegrationContractSource, | ||
| cctpIntegrationContractDestination, | ||
| }; | ||
| }; | ||
|
|
||
| const fetchAttestation = async ({ transactionHash, cctpChainId }) => { | ||
| console.log( | ||
| `Fetching attestation for transaction hash: ${transactionHash} on cctp chain id: ${cctpChainId}` | ||
| ); | ||
| const response = await fetch( | ||
| `${cctpApi}/v2/messages/${cctpChainId}?transactionHash=${transactionHash}` | ||
| ); | ||
| if (!response.ok) { | ||
| throw new Error( | ||
| `Error fetching attestation code: ${ | ||
| response.status | ||
| } error: ${await response.text()}` | ||
| ); | ||
| } | ||
| const resultJson = await response.json(); | ||
|
|
||
| if (resultJson.messages.length !== 1) { | ||
| throw new Error( | ||
| `Expected 1 attestation, got ${resultJson.messages.length}` | ||
| ); | ||
| } | ||
|
|
||
| const message = resultJson.messages[0]; | ||
| const status = message.status; | ||
| if (status !== "complete") { | ||
| throw new Error(`Attestation is not complete, status: ${status}`); | ||
| } | ||
|
|
||
| return { | ||
| attestation: message.attestation, | ||
| message: message.message, | ||
| status: "ok", | ||
| }; | ||
| }; | ||
|
|
||
| // TokensBridged & MessageTransmitted are the 2 events that are emitted when a transaction is published to the CCTP contract | ||
| // One transaction containing such message can at most only contain one of these events | ||
| const fetchTxHashesFromCctpTransactions = async ({ | ||
| config, | ||
| blockLookback, | ||
| overrideBlock, | ||
| sourceChainProvider, | ||
| } = {}) => { | ||
| let resolvedFromBlock, resolvedToBlock; | ||
| if (overrideBlock) { | ||
| resolvedFromBlock = overrideBlock; | ||
| resolvedToBlock = overrideBlock; | ||
| } else { | ||
| const latestBlock = await sourceChainProvider.getBlockNumber(); | ||
| resolvedFromBlock = Math.max(latestBlock - blockLookback, 0); | ||
| resolvedToBlock = latestBlock; | ||
| } | ||
|
|
||
| const cctpIntegrationContractSource = config.cctpIntegrationContractSource; | ||
|
|
||
| const tokensBridgedTopic = | ||
| cctpIntegrationContractSource.interface.getEventTopic("TokensBridged"); | ||
| const messageTransmittedTopic = | ||
| cctpIntegrationContractSource.interface.getEventTopic("MessageTransmitted"); | ||
|
|
||
| console.log( | ||
| `Fetching event logs from block ${resolvedFromBlock} to block ${resolvedToBlock}` | ||
| ); | ||
| const [eventLogsTokenBridged, eventLogsMessageTransmitted] = | ||
| await Promise.all([ | ||
| sourceChainProvider.getLogs({ | ||
| address: cctpIntegrationContractSource.address, | ||
| fromBlock: resolvedFromBlock, | ||
| toBlock: resolvedToBlock, | ||
| topics: [tokensBridgedTopic], | ||
| }), | ||
| sourceChainProvider.getLogs({ | ||
| address: cctpIntegrationContractSource.address, | ||
| fromBlock: resolvedFromBlock, | ||
| toBlock: resolvedToBlock, | ||
| topics: [messageTransmittedTopic], | ||
| }), | ||
| ]); | ||
|
|
||
| // There should be no duplicates in the event logs, but still deduplicate to be safe | ||
| const possiblyDuplicatedTxHashes = [ | ||
| ...eventLogsTokenBridged, | ||
| ...eventLogsMessageTransmitted, | ||
| ].map((log) => log.transactionHash); | ||
| const allTxHashes = Array.from(new Set([...possiblyDuplicatedTxHashes])); | ||
|
|
||
| console.log(`Found ${allTxHashes.length} transactions that emitted messages`); | ||
| return { allTxHashes }; | ||
| }; | ||
|
|
||
| const processCctpBridgeTransactions = async ({ | ||
| block = undefined, | ||
| dryrun = false, | ||
| destinationChainSigner, | ||
| sourceChainProvider, | ||
| store, | ||
| networkName, | ||
| blockLookback, | ||
| cctpDestinationDomainId, | ||
| cctpSourceDomainId, | ||
| cctpIntegrationContractAddress, | ||
| cctpIntegrationContractAddressDestination, | ||
| }) => { | ||
| const config = await cctpOperationsConfig({ | ||
| destinationChainSigner, | ||
| sourceChainProvider, | ||
| networkName, | ||
| cctpIntegrationContractAddress, | ||
| cctpIntegrationContractAddressDestination, | ||
| }); | ||
| console.log( | ||
| `Fetching cctp messages posted on ${config.networkName} network.${ | ||
| block ? ` Only for block: ${block}` : " Looking at most recent blocks" | ||
| }` | ||
| ); | ||
|
|
||
| const { allTxHashes } = await fetchTxHashesFromCctpTransactions({ | ||
| config, | ||
| overrideBlock: block, | ||
| sourceChainProvider, | ||
| blockLookback, | ||
| }); | ||
| for (const txHash of allTxHashes) { | ||
| const storeKey = `cctp_message_${txHash}`; | ||
| const storedValue = await store.get(storeKey); | ||
sparrowDom marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| if (storedValue === "processed") { | ||
| console.log( | ||
| `Transaction with hash: ${txHash} has already been processed. Skipping...` | ||
| ); | ||
| continue; | ||
| } | ||
|
|
||
| const { attestation, message, status } = await fetchAttestation({ | ||
| transactionHash: txHash, | ||
| cctpChainId: cctpSourceDomainId, | ||
| }); | ||
| if (status !== "ok") { | ||
| console.log( | ||
| `Attestation from tx hash: ${txHash} on cctp chain id: ${config.cctpSourceDomainId} is not attested yet, status: ${status}. Skipping...` | ||
| ); | ||
| } | ||
|
|
||
| console.log( | ||
| `Attempting to relay attestation with tx hash: ${txHash} and message: ${message} to cctp chain id: ${cctpDestinationDomainId}` | ||
| ); | ||
|
|
||
| if (dryrun) { | ||
| console.log( | ||
| `Dryrun: Would have relayed attestation with tx hash: ${txHash} to cctp chain id: ${cctpDestinationDomainId}` | ||
| ); | ||
| continue; | ||
| } | ||
|
|
||
| const relayTx = await config.cctpIntegrationContractDestination.relay( | ||
| message, | ||
| attestation | ||
| ); | ||
| console.log( | ||
| `Relay transaction with hash ${relayTx.hash} sent to cctp chain id: ${cctpDestinationDomainId}` | ||
| ); | ||
| const receipt = await logTxDetails(relayTx, "CCTP relay"); | ||
|
|
||
| // Final verification | ||
| if (receipt.status === 1) { | ||
| console.log("SUCCESS: Transaction executed successfully!"); | ||
| await store.put(storeKey, "processed"); | ||
| } else { | ||
| console.log("FAILURE: Transaction reverted!"); | ||
| throw new Error(`Transaction reverted - status: ${receipt.status}`); | ||
| } | ||
| } | ||
| }; | ||
|
|
||
| module.exports = { | ||
| processCctpBridgeTransactions, | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -70,4 +70,5 @@ const updateAction = async ({ id, file }) => { | |
| module.exports = { | ||
| setActionVars, | ||
| updateAction, | ||
| getClient, | ||
| }; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.