Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
motechFR committed Nov 4, 2024
1 parent 41818a9 commit df49b21
Show file tree
Hide file tree
Showing 4 changed files with 167 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Box, Divider, Grid2, IconButton, Typography } from '@mui/material';
import { Box, Button, Divider, Grid2, IconButton, Typography } from '@mui/material';
import Link from 'next/link';
import { MdLaunch } from 'react-icons/md';

Expand Down Expand Up @@ -77,10 +77,24 @@ export function ProtocolContractDashboard(data: ProtocolData) {
{data.merkleRoots.map((root) => (
<Grid2 size={itemSizeThreeColumnMd} key={root.week}>
<Typography variant='h6'>Merkle Root for week {root.week}</Typography>
<Typography variant='body1'>{root.root}</Typography>
{!root.root && <Typography>Week not processed</Typography>}
{root.root &&
(root.publishedOnchain ? (
<Typography>Published onchain</Typography>
) : (
<Typography>Awaiting publication</Typography>
))}
</Grid2>
))}
<GridDivider />
<Grid2 size={12}>
<SectionTitle title='Governance' />
</Grid2>
<Grid2 size={itemSizeTwoColumnMd}>
<Typography variant='h6'>Upgrade contract</Typography>
<Button>Upgrade contract</Button>
</Grid2>
<GridDivider />
<Grid2 size={12}>
<SectionTitle title='Roles & Permissions' />
</Grid2>
Expand Down
131 changes: 131 additions & 0 deletions apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// useProposeSetImplementation.ts
import type {} from '@safe-global/api-kit';
import { ProposeTransactionProps } from '@safe-global/api-kit';
import { useNetwork } from '@wagmi/core';
import { ethers } from 'ethers';
import { useState, useCallback } from 'react';
import { encodeFunctionData } from 'viem';

/**
* Hook to propose a transaction to call setImplementation on a contract using Gnosis Safe SDK.
*
* @param safeAddress - The address of the Gnosis Safe.
* @param contractAddress - The address of the contract with the setImplementation method.
* @returns An object containing the proposeTransaction function, loading state, and any error.
*/
const useProposeSetImplementation = (safeAddress: string, contractAddress: string) => {
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<string | null>(null);
const { data: signer } = useSigner();
const { chain } = useNetwork();

const proposeTransaction = useCallback(
async (newImplementationAddress: string) => {
setLoading(true);
setError(null);

try {
if (!signer) {
throw new Error('No signer available');
}

if (!chain) {
throw new Error('No network information available');
}

// Initialize ethers provider and signer
const provider = new ethers.providers.Web3Provider((window as any).ethereum);
const signerAddress = await signer.getAddress();

// Initialize Safe API Kit
const apiKit = new SafeApiKit({
txServiceUrl: getTxServiceUrl(chain.id),

Check failure on line 42 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Test apps

'getTxServiceUrl' was used before it was defined

Check failure on line 42 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Test apps

'getTxServiceUrl' was used before it was defined

Check failure on line 42 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Test app

'getTxServiceUrl' was used before it was defined

Check failure on line 42 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Test

'getTxServiceUrl' was used before it was defined

Check failure on line 42 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Test apps

'getTxServiceUrl' was used before it was defined

Check failure on line 42 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Validate code

'getTxServiceUrl' was used before it was defined
ethAdapter: new ethers.providers.Web3Provider((window as any).ethereum),
safeAddress
});

// Encode the setImplementation call using viem
const data = encodeFunctionData({
abi: [
{
name: 'setImplementation',
type: 'function',
inputs: [
{
type: 'address',
name: 'newImplementation'
}
]
}
],
functionName: 'setImplementation',
args: [newImplementationAddress]
});

// Prepare transaction data
const safeTx: SafeTransactionData = {
to: contractAddress,
value: '0',
data,
operation: 0 // 0 for CALL, 1 for DELEGATECALL
};

// Create the Safe transaction
const safeTransaction = await apiKit.createTransaction({
safeTransactionData: safeTx
});

// Get the transaction hash for signing
const txHash = await apiKit.getTransactionHash(safeTransaction);

// Sign the transaction hash using the signer
const signature = await signer.signMessage(ethers.utils.arrayify(txHash));

// Add the signature to the transaction
safeTransaction.signatures[safeAddress] = {
signer: signerAddress,
data: signature
};

// Propose the transaction via Safe API Kit
const response = await apiKit.proposeTransaction(safeTransaction);

if (!response.success) {
throw new Error(response.message || 'Failed to propose transaction');
}

console.log('Transaction proposed successfully:', response);

Check failure on line 97 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Test apps

Unexpected console statement

Check failure on line 97 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Test apps

Unexpected console statement

Check failure on line 97 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Test app

Unexpected console statement

Check failure on line 97 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Test

Unexpected console statement

Check failure on line 97 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Test apps

Unexpected console statement

Check failure on line 97 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Validate code

Unexpected console statement
} catch (err: any) {
console.error('Error proposing transaction:', err);

Check failure on line 99 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Test apps

Unexpected console statement

Check failure on line 99 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Test apps

Unexpected console statement

Check failure on line 99 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Test app

Unexpected console statement

Check failure on line 99 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Test

Unexpected console statement

Check failure on line 99 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Test apps

Unexpected console statement

Check failure on line 99 in apps/scoutgameadmin/hooks/useProposeContractUpgrade.tsx

View workflow job for this annotation

GitHub Actions / Validate code

Unexpected console statement
setError(err.message || 'An unknown error occurred');
} finally {
setLoading(false);
}
},
[signer, chain, safeAddress, contractAddress]
);

return { proposeTransaction, loading, error };
};

/**
* Helper function to get the Safe Transaction Service URL based on chain ID.
*
* @param chainId - The ID of the Ethereum chain.
* @returns The URL of the Safe Transaction Service.
*/
const getTxServiceUrl = (chainId: number): string => {
switch (chainId) {
case 1:
return 'https://safe-transaction.gnosis.io/';
case 5:
return 'https://safe-transaction-goerli.safe.global/';
case 137:
return 'https://safe-transaction-mainnet.safe.global/';
// Add other chains as needed
default:
throw new Error(`Unsupported chain ID: ${chainId}`);
}
};

export default useProposeSetImplementation;
22 changes: 18 additions & 4 deletions apps/scoutgameadmin/lib/contract/aggregateProtocolData.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { prisma } from '@charmverse/core/prisma-client';
import { getAllISOWeeksFromSeasonStart } from '@packages/scoutgame/dates';
import {
protocolImplementationReadonlyApiClient,
Expand All @@ -8,7 +9,8 @@ import type { Address } from 'viem';

type MerkleRoot = {
week: string;
root: string;
publishedOnchain: boolean;
root: string | null;
};

export type ProtocolData = {
Expand All @@ -28,13 +30,25 @@ export async function aggregateProtocolData(): Promise<ProtocolData> {

const weeks = getAllISOWeeksFromSeasonStart();

const merkleRoots = await Promise.all(
const weeklyClaims = await prisma.weeklyClaims.findMany({
where: {
week: {
in: weeks
}
}
});

const merkleRoots = await Promise.all<MerkleRoot>(
weeks.map((week) =>
protocolImplementationReadonlyApiClient
.getMerkleRoot({ args: { week } })
.then((root) => ({ week, root }))
.then((root) => ({ week, root, publishedOnchain: true }) as MerkleRoot)
.catch(() => {
return { week, root: 'No root found' };
return {
week,
root: weeklyClaims.find((claim) => claim.week === week)?.merkleTreeRoot || null,
publishedOnchain: false
} as MerkleRoot;
})
)
);
Expand Down
2 changes: 2 additions & 0 deletions packages/scoutgame/src/protocol/generateWeeklyClaims.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,5 @@ export async function generateWeeklyClaims({ week }: { week: string }): Promise<

return weeklyClaim as WeeklyClaimsTyped;
}

// generateWeeklyClaims({ week: '2024-W44' }).then(console.log);

0 comments on commit df49b21

Please sign in to comment.