Skip to content
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

Develop #18

Open
wants to merge 22 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions contracts/BaseRouter.sol
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ abstract contract BaseRouter is Ownable, ReentrancyGuard {

event InitiateCross(
address sourceFoundryToken,
uint256 amountIn,
address remoteFoundryToken,
uint256 settledAmount,
address recipient,
uint256 targetChainId,
uint256 gasFee
Expand All @@ -31,8 +30,7 @@ abstract contract BaseRouter is Ownable, ReentrancyGuard {
address fromToken,
uint256 amountIn,
address sourceFoundryToken,
uint256 amountOut,
address remoteFoundryToken,
uint256 settledAmount,
address recipient,
uint256 targetChainId,
uint256 gasFee
Expand Down
11 changes: 6 additions & 5 deletions contracts/FiberRouter.sol
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { IWETH } from "./common/IWETH.sol";
import { StargateComposer } from "./StargateComposer.sol";
import { QuantumPortalApp } from "./QuantumPortalApp.sol";


contract FiberRouter is FeeDistributor, StargateComposer, QuantumPortalApp, CCIPApp {
constructor(
address pool,
Expand All @@ -22,7 +21,6 @@ contract FiberRouter is FeeDistributor, StargateComposer, QuantumPortalApp, CCIP
//###################### USER FUNCTIONS #######################
//#############################################################


function swapOnSameNetwork(
uint256 amountIn,
uint256 minAmountOut,
Expand Down Expand Up @@ -245,6 +243,7 @@ contract FiberRouter is FeeDistributor, StargateComposer, QuantumPortalApp, CCIP
//#############################################################
//################# INTERNAL LOGIC FUNCTIONS ##################
//#############################################################

function _cross(
address sourceFoundryToken,
uint256 amountIn,
Expand Down Expand Up @@ -272,6 +271,8 @@ contract FiberRouter is FeeDistributor, StargateComposer, QuantumPortalApp, CCIP
} else {
revert("FR: Invalid swap type");
}

emit InitiateCross(sourceFoundryToken, amountIn, recipient, dstChainId, feeAmount);
}

function _swapAndCross(
Expand Down Expand Up @@ -300,8 +301,6 @@ contract FiberRouter is FeeDistributor, StargateComposer, QuantumPortalApp, CCIP
amountIn = _moveTokens(fromToken, msg.sender, address(this), amountIn);
}

// amountIn = _moveTokens(fromToken, msg.sender, address(this), amountIn);

uint256 amountOut = _swap(
address(this),
fromToken,
Expand All @@ -323,5 +322,7 @@ contract FiberRouter is FeeDistributor, StargateComposer, QuantumPortalApp, CCIP
} else {
revert("FR: Invalid swap type");
}

emit SwapAndInitiateCross(fromToken, amountIn, sourceFoundryToken, amountOut, recipient, dstChainId, feeAmount);
}
}
}
103 changes: 103 additions & 0 deletions scripts/fetchToken.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
const Web3 = require('web3');
const fs = require('fs');
const aggregatorAbi = require("./abi/1inch.json");

const ARBITRUM_RPC_URL = "https://arb1.arbitrum.io/rpc";
const CONTRACT_ADDRESS = "0x111111125421ca6dc452d289314280a0f8842a65";
const TOKEN_X_ADDRESS = "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9".toLowerCase(); // USDT address
const SECONDS_PER_BLOCK = 12;
const PAST_FIVE_DAYS_IN_BLOCKS = Math.floor((30 * 24 * 60 * 60) / SECONDS_PER_BLOCK);
const BLOCK_CHUNK_SIZE = 20000;

const web3 = new Web3(new Web3.providers.HttpProvider(ARBITRUM_RPC_URL));
const aggregatorContract = new web3.eth.Contract(aggregatorAbi, CONTRACT_ADDRESS);

const swapFunctionSelectors = [
"0xd2d374e5", "0xc4d652af", "0xa76dfc3b", "0x89af926a", "0x188ac35d", "0x175accdc", "0x0f449d71",
"0x493189f0", "0xcc713a04", "0x56a75868", "0x9fda64bd", "0xf497df75", "0x07ed2379", "0x83800a8e",
"0x8770ba91", "0x19367472", "0xe2c95c82", "0xea76dddf", "0xf7a70056"
];

// Fetch events in chunks
async function getEventsInChunks(contract, eventName, fromBlock, toBlock) {
let events = [];
while (fromBlock <= toBlock) {
const endBlock = Math.min(fromBlock + BLOCK_CHUNK_SIZE, toBlock);
try {
const contractEvents = await contract.getPastEvents(eventName, {
fromBlock: fromBlock,
toBlock: endBlock,
});
events = events.concat(contractEvents);
} catch (error) {
console.error(`Error fetching ${eventName} events from block ${fromBlock} to ${endBlock}:`, error);
}
fromBlock = endBlock + 1;
}
return events;
}

// Fetch swap transactions and filter based on TokenX (USDT)
async function getSwapTransactionsForTokenX(fromBlock, toBlock) {
const latestBlock = await web3.eth.getBlockNumber();
const matchingTransactions = [];

for (let block = fromBlock; block <= toBlock; block += BLOCK_CHUNK_SIZE) {
const endBlock = Math.min(block + BLOCK_CHUNK_SIZE, latestBlock);
const blockData = await web3.eth.getPastLogs({
fromBlock: block,
toBlock: endBlock,
address: CONTRACT_ADDRESS,
});

for (const log of blockData) {
const transaction = await web3.eth.getTransaction(log.transactionHash);
const inputData = transaction.input.substring(0, 10);

if (swapFunctionSelectors.includes(inputData)) {
const receipt = await web3.eth.getTransactionReceipt(log.transactionHash);

// Filter transactions that involve TokenX (USDT)
const tokenXInvolved = receipt.logs.some(log =>
log.address.toLowerCase() === TOKEN_X_ADDRESS ||
(log.topics.includes(web3.utils.keccak256('Transfer(address,address,uint256)')) &&
(log.topics[2] && web3.utils.toChecksumAddress('0x' + log.topics[2].slice(26)).toLowerCase() === TOKEN_X_ADDRESS))
);

if (tokenXInvolved) {
matchingTransactions.push({
transactionHash: log.transactionHash,
blockNumber: log.blockNumber,
inputData,
});
}
}
}
}

return matchingTransactions;
}

// Main function to fetch and filter swap-related transactions
async function getEventsForToken() {
const latestBlock = await web3.eth.getBlockNumber();
const fromBlock = Math.floor(latestBlock - PAST_FIVE_DAYS_IN_BLOCKS);

console.log(`Fetching swap-related transactions from block ${fromBlock} to ${latestBlock}`);

// Fetch all swap-related transactions involving TokenX (USDT)
const swapEvents = await getSwapTransactionsForTokenX(fromBlock, latestBlock);
console.log(`Total swap-related transactions found involving token ${TOKEN_X_ADDRESS}: ${swapEvents.length}`);

const eventsWithDetails = swapEvents.map(event => ({
eventType: "Swap",
blockNumber: event.blockNumber,
transactionHash: event.transactionHash,
functionSelector: event.inputData,
}));

fs.writeFileSync("token_swap_transactions.txt", JSON.stringify(eventsWithDetails, null, 2));
console.log("Filtered swap transactions with token involvement saved to token_x_swap_transactions.txt");
}

getEventsForToken().catch(console.error);
9 changes: 7 additions & 2 deletions scripts/live-tests/crossAndSwap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,13 @@ async function main() {

const srcFoundry = currentNetworkInfo.foundry
const dstFoundry = dstNetworkInfo.foundry
const toToken = "0x4200000000000000000000000000000000000006"
const amountIn = 20000n
const toToken = "0x7f5373AE26c3E8FfC4c77b7255DF7eC1A9aF52a6"
const amountIn = 10000n
const srcFoundryContract = await hre.ethers.getContractAt("Token", srcFoundry);
const approveFoundryTx = await srcFoundryContract.approve(fiberRouterAddress, amountIn)
approveFoundryTx.wait()
console.log("Approved Foundry")

const oneInchRouterAddress = "0x111111125421ca6dc452d289314280a0f8842a65"

const res = await get1InchData(currentNetworkInfo.chainId, dstFoundry, toToken, amountIn, dstFiberRouterAddress, walletAddress)
Expand Down
92 changes: 92 additions & 0 deletions scripts/stargateWithdrawConfirmation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
const Web3 = require('web3');
import addresses from "../constants/addresses_test.json";

// Set up the RPC URLs for the source and target networks
const sourceNetworkProviderUrl = process.env.ARBITRUM_RPC; // Source network RPC URL
const targetNetworkProviderUrl = process.env.BASE_RPC; // Target network RPC URL

const targetNetwork = "base";
const thisNetwork = hre.network.name;
const targetNetworkInfo = addresses.networks[targetNetwork];
const currentNetworkInfo = addresses.networks[thisNetwork];
const sourceWeb3 = new Web3(new Web3.providers.HttpProvider(sourceNetworkProviderUrl));
const targetWeb3 = new Web3(new Web3.providers.HttpProvider(targetNetworkProviderUrl));

// Enter the swapHash for which we need to confirm if the withdrawal is successful
const swapHash = '0xaf1634f8d7ae2072e00928ac8820e4cf0439487ff3d85a2d13a6ea3f675f8565';

async function fetchOFTSentEvent() {
const receipt = await sourceWeb3.eth.getTransactionReceipt(swapHash);

if (!receipt || !receipt.logs) {
console.error('Transaction receipt or logs not found');
return null;
}

const oftsentEventSignature = '0x85496b760a4b7f8d66384b9df21b381f5d1b1e79f229a47aaf4c232edc2fe59a';

// Find the OFTSent event from the logs
const oftsentLog = receipt.logs.find(log => log.topics[0] === oftsentEventSignature);

if (!oftsentLog) {
console.error('OFTSent event not found in the transaction');
return null;
}

// Decode the event data
const decodedLog = sourceWeb3.eth.abi.decodeLog(
[
{ type: 'bytes32', name: 'guid', indexed: true },
{ type: 'uint32', name: 'dstEid', indexed: false },
{ type: 'address', name: 'fromAddress', indexed: true },
{ type: 'uint256', name: 'amountSentLD', indexed: false },
{ type: 'uint256', name: 'amountReceivedLD', indexed: false }
],
oftsentLog.data,
oftsentLog.topics.slice(1) // Remove the event topic
);

console.log("For the Stargate Swap hash", swapHash);
return decodedLog[0];
}

// Function to fetch the OFTReceived event from the target network using guid
async function fetchOFTReceivedEvent(guid) {

const oftReceivedEventSignature = '0xefed6d3500546b29533b128a29e3a94d70788727f0507505ac12eaf2e578fd9c';

// Create a filter for the OFTReceived event based on the guid
const filter = {
fromBlock: 0, // Adjust this based on when the transaction is expected
toBlock: 'latest',
topics: [
oftReceivedEventSignature, // Event signature
guid, // guid (indexed parameter)
null // toAddress (indexed parameter)
]
};

const logs = await targetWeb3.eth.getPastLogs(filter);
return logs[0].transactionHash;
}

// Main function to track the swap and find both events
async function trackStargateSwapTransaction() {
try {
// Fetch OFTSent event from the source network
const oftsentEventDetails = await fetchOFTSentEvent();

if (oftsentEventDetails) {
// Fetch OFTReceived event from the target network using the guid
const oftReceivedEventDetails = await fetchOFTReceivedEvent(oftsentEventDetails);

if (oftReceivedEventDetails) {
console.log("Stargate withdrawal is successful, Withdrawal hash:", oftReceivedEventDetails);
}
}
} catch (error) {
console.error("Error tracking swap transaction:", error);
}
}

trackStargateSwapTransaction();
5 changes: 3 additions & 2 deletions scripts/temp/addLiquidity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ async function main() {

const currentNetworkInfo = addresses.networks[thisNetwork];
const pool = await hre.ethers.getContractAt("Pool", currentNetworkInfo.deployments.pool);
const usdc = await hre.ethers.getContractAt("MockUSDC", "0x6FCF42A7EFFC92410CE6dc8fC13bD4600abe7bB6");
const liquidityAmount = 1000000n * (10n ** 18n)
const usdc = await hre.ethers.getContractAt("MockUSDC", currentNetworkInfo.foundry);
const liquidityAmount = 5n * (10n ** 18n)
console.log(liquidityAmount)
const tx = await usdc.approve(pool, liquidityAmount)
tx.wait()
console.log("Adding liquidity")
Expand Down