Skip to content

Commit

Permalink
Merge pull request #374 from consensusnetworks/feature/populate-staki…
Browse files Browse the repository at this point in the history
…ng-address

Feature/populate staking address
  • Loading branch information
ccali11 authored Jul 17, 2023
2 parents b3b77cc + 8dc01cd commit 00ccd4e
Show file tree
Hide file tree
Showing 10 changed files with 764 additions and 577 deletions.
42 changes: 34 additions & 8 deletions apps/web/src/composables/contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,22 @@ const totalWalletBalance = ref<BreakdownAmount>({
exchange: '0 ETH'
})

const { ethereumUrl, managerAddress, viewsAddress } = useEnvironment()
const provider = new ethers.providers.JsonRpcProvider(ethereumUrl)
const manager: CasimirManager & ethers.Contract = new ethers.Contract(managerAddress, CasimirManagerJson.abi) as CasimirManager
const views: CasimirViews & ethers.Contract = new ethers.Contract(viewsAddress, CasimirViewsJson.abi) as CasimirViews

export default function useContracts() {
const { ethereumUrl, managerAddress, viewsAddress } = useEnvironment()
const { ethersProviderList, getEthersBalance, getEthersBrowserSigner } = useEthers()
const { getEthersLedgerSigner } = useLedger()
const { getCurrentPrice } = usePrice()
const { getEthersTrezorSigner } = useTrezor()
const { user } = useUsers()
const { isWalletConnectSigner, getEthersWalletConnectSigner } = useWalletConnect()

const provider = new ethers.providers.JsonRpcProvider(ethereumUrl)
const manager: CasimirManager & ethers.Contract = new ethers.Contract(managerAddress, CasimirManagerJson.abi) as CasimirManager
const views: CasimirViews & ethers.Contract = new ethers.Contract(viewsAddress, CasimirViewsJson.abi) as CasimirViews
const stakeDepositedListener = async () => await refreshBreakdown()
const stakeRebalancedListener = async () => await refreshBreakdown()
const withdrawalInitiatedListener = async () => await refreshBreakdown()

async function deposit({ amount, walletProvider }: { amount: string, walletProvider: ProviderString }) {
try {
Expand All @@ -61,7 +65,7 @@ export default function useContracts() {
await result.wait()
return true
} catch (err) {
console.error(`There was an error in despoit function: ${JSON.stringify(err)}`)
console.error(`There was an error in deposit function: ${JSON.stringify(err)}`)
return false
}
}
Expand Down Expand Up @@ -270,16 +274,31 @@ export default function useContracts() {

async function listenForContractEvents() {
try {
manager.on('StakeDeposited', async () => await refreshBreakdown())
manager.on('StakeRebalanced', async () => await refreshBreakdown())
manager.on('WithdrawalInitiated', async () => await refreshBreakdown())
manager.on('StakeDeposited', stakeDepositedListener)
manager.on('StakeRebalanced', stakeRebalancedListener)
manager.on('WithdrawalInitiated', withdrawalInitiatedListener)
} catch (err) {
console.log(`There was an error in listenForContractEvents: ${err}`)
}
}

async function refreshBreakdown() {
try {
if (!user.value?.id) {
// Reset currentStaked, totalWalletBalance, and stakingRewards
currentStaked.value = {
exchange: '0 ETH',
usd: '$ 0.00'
}
totalWalletBalance.value = {
exchange: '0 ETH',
usd: '$ 0.00'
}
stakingRewards.value = {
exchange: '0 ETH',
usd: '$ 0.00'
}
}
setBreakdownValue({ name: 'currentStaked', ...await getCurrentStaked() })
setBreakdownValue({ name: 'totalWalletBalance', ...await getTotalWalletBalance() })
setBreakdownValue({ name: 'stakingRewardsEarned', ...await getAllTimeStakingRewards() })
Expand Down Expand Up @@ -311,6 +330,12 @@ export default function useContracts() {
}
}

function stopListeningForContractEvents() {
manager.removeListener('StakeDeposited', stakeDepositedListener)
manager.removeListener('StakeRebalanced', stakeRebalancedListener)
manager.removeListener('WithdrawalInitiated', withdrawalInitiatedListener)
}

async function withdraw({ amount, walletProvider }: { amount: string, walletProvider: ProviderString }) {
const signerCreators = {
'Browser': getEthersBrowserSigner,
Expand Down Expand Up @@ -340,6 +365,7 @@ export default function useContracts() {
// getPools,
listenForContractEvents,
refreshBreakdown,
stopListeningForContractEvents,
withdraw
}
}
Expand Down
42 changes: 24 additions & 18 deletions apps/web/src/composables/ethers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ declare const window: ethereumWindow

const { createSiweMessage, signInWithEthereum } = useAuth()
const { ethereumUrl } = useEnvironment()
const provider = new ethers.providers.JsonRpcProvider(ethereumUrl)

export default function useEthers() {
const ethersProviderList = ['BraveWallet', 'CoinbaseWallet', 'MetaMask', 'OkxWallet', 'TrustWallet']
Expand All @@ -30,6 +31,23 @@ export default function useEthers() {
}
}

async function blockListener (blockNumber: number) {
const { manager, refreshBreakdown } = useContracts()
const { user } = useUsers()
console.log('blockNumber :>> ', blockNumber)
const addresses = (user.value as UserWithAccounts).accounts.map((account: Account) => account.address) as string[]
const block = await provider.getBlockWithTransactions(blockNumber)
const transactions = block.transactions
transactions.map(async (tx) => {
if (addresses.includes(tx.from.toLowerCase())) {
console.log('tx :>> ', tx)
const response = manager.interface.parseTransaction({ data: tx.data })
console.log('response :>> ', response)
await refreshBreakdown()
}
})
}

/**
* Estimate gas fee using EIP 1559 methodology
* @returns string in ETH
Expand Down Expand Up @@ -112,7 +130,6 @@ export default function useEthers() {
}

async function getEthersBalance(address: string) : Promise<GLfloat> {
const provider = new ethers.providers.JsonRpcProvider(ethereumUrl)
const balance = await provider.getBalance(address)
return parseFloat(ethers.utils.formatEther(balance))
}
Expand Down Expand Up @@ -152,23 +169,7 @@ export default function useEthers() {
}

async function listenForTransactions() {
const { manager, refreshBreakdown } = useContracts()
const { user } = useUsers()
const provider = new ethers.providers.JsonRpcProvider(ethereumUrl)
provider.on('block', async (blockNumber: number) => {
console.log('blockNumber :>> ', blockNumber)
const addresses = (user.value as UserWithAccounts).accounts.map((account: Account) => account.address) as string[]
const block = await provider.getBlockWithTransactions(blockNumber)
const transactions = block.transactions
transactions.map(async (tx) => {
if (addresses.includes(tx.from.toLowerCase())) {
console.log('tx :>> ', tx)
const response = manager.interface.parseTransaction({ data: tx.data })
console.log('response :>> ', response)
await refreshBreakdown()
}
})
})
provider.on('block', blockListener as ethers.providers.Listener)
await new Promise(() => {
// Wait indefinitely using a Promise that never resolves
})
Expand Down Expand Up @@ -232,6 +233,10 @@ export default function useEthers() {
return signature
}

function stopListeningForTransactions() {
provider.off('block', blockListener as ethers.providers.Listener)
}

async function switchEthersNetwork (providerString: ProviderString, chainId: string) {
const provider = getBrowserProvider(providerString)
const currentChainId = await provider.networkVersion
Expand Down Expand Up @@ -275,6 +280,7 @@ export default function useEthers() {
requestEthersAccount,
sendEthersTransaction,
signEthersMessage,
stopListeningForTransactions,
switchEthersNetwork
}
}
Expand Down
Loading

0 comments on commit 00ccd4e

Please sign in to comment.