Skip to content

Commit

Permalink
FIL-367 Grant DataCap - increase allowance on client contract (#151)
Browse files Browse the repository at this point in the history
* FIL-364 Add modal and bussines logic related to max deviation and allowed sps

* Save progress

* Saving progress

* Make dynamic client contract address for application

* Add call to API about providers propose

* Add possibility to approve all pending SP transactions

* Add minors changes

* FIL-367 Implement increase allwance transaction

* Find pending for approve increase transactions

* Fixes after increase allowance transaction tests

* Add small fix

* Changes after test

* change z-index

* After test

* Add message_cid

* Uncomment code for test env

* Uncomment

* Remove latest

* FIL-366 Display info about allowed SPs on the application page (#150)

* FIL-366 Add additional info section with allowed SPs on the application page

* Hide additional info about SPs when not set

* Fix build

---------

Co-authored-by: Filip Lelek <[email protected]>
  • Loading branch information
lukasz-wal and filip-neti authored Oct 30, 2024
1 parent d3c55f1 commit 5c3e357
Show file tree
Hide file tree
Showing 5 changed files with 352 additions and 38 deletions.
48 changes: 48 additions & 0 deletions src/components/cards/AppInfoCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import calculateAmountToRequest, {
validateAmount,
} from '@/helpers/calculateAmountToRefill'
import useApplicationActions from '@/hooks/useApplicationActions'
import useWallet from '@/hooks/useWallet'
import { useAllocator } from '@/lib/AllocatorProvider'
import { stateColor, stateMapping } from '@/lib/constants'
import { getAllowanceForClient } from '@/lib/glifApi'
Expand Down Expand Up @@ -49,6 +50,7 @@ import {
useState,
type ReactNode,
} from 'react'
import { useQuery } from 'react-query'
import { toast } from 'react-toastify'
import AllocatorBalance from '../AllocatorBalance'
import AllowedSps from './dialogs/allowedSps'
Expand Down Expand Up @@ -150,6 +152,21 @@ const AppInfoCard: React.FC<ComponentProps> = ({
isDialogOpen: false,
})

const { getClientSPs } = useWallet()

const { data: availableAllowedSPs } = useQuery({
queryKey: ['allowedSps', application.Lifecycle['On Chain Address']],
queryFn: async () =>
await getClientSPs(
application?.Lifecycle?.['On Chain Address'],
application?.['Client Contract Address'] ?? '',
),
enabled: !!(
application.Lifecycle['On Chain Address'] &&
application['Client Contract Address']
),
})

const router = useRouter()

const allocationRequests = application?.['Allocation Requests'] ?? []
Expand Down Expand Up @@ -1020,6 +1037,37 @@ const AppInfoCard: React.FC<ComponentProps> = ({
</CardContent>
</div>
</div>
{availableAllowedSPs?.length ? (
<div>
<CardHeader className="border-b pb-2 mb-4">
<h2 className="text-xl font-bold">Additional info</h2>
</CardHeader>
<CardContent className="grid text-sm">
{[['SPs', availableAllowedSPs.join(',')]].map(
([label, value], idx) => {
const rowStyles = getRowStyles(idx)
return (
<div
key={idx}
className={`flex items-center p-2 justify-between ${rowStyles}`}
>
<p className="text-gray-600">{label}</p>
{label === 'Status' ? (
<span
className={`ml-2 px-2 py-1 rounded text-xs ${stateClass}`}
>
{value}
</span>
) : (
<p className="font-medium text-gray-800">{value}</p>
)}
</div>
)
},
)}
</CardContent>
</div>
) : null}

<CardContent>
{isProgressBarVisible && (
Expand Down
2 changes: 2 additions & 0 deletions src/components/cards/dialogs/allowedSps/AllowedSps.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,9 @@ export const AllowedSPs: React.FC<ComponentProps> = ({
if (!clientConfig) {
maxDeviationResult = maxDeviation
}

setIsDialogOpen(false)

await onSubmit(
client,
clientContractAddress,
Expand Down
138 changes: 127 additions & 11 deletions src/hooks/useApplicationActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ const useApplicationActions = (
submitClientAllowedSpsAndMaxDeviation,
getChangeSpsProposalTxs,
setMessage,
sendClientIncreaseAllowance,
} = useWallet()
const { selectedAllocator } = useAllocator()

Expand Down Expand Up @@ -443,11 +444,18 @@ const useApplicationActions = (
unknown
>(
async ({ requestId, userName, allocationAmount }) => {
const clientAddress =
setMessage(`Searching the pending transactions...`)

let clientAddress =
(process.env.NEXT_PUBLIC_MODE === 'development' ? 't' : 'f') +
initialApplication.Lifecycle['On Chain Address'].substring(1)

let proposalAllocationAmount = ''

if (initialApplication['Client Contract Address']) {
clientAddress = initialApplication['Client Contract Address']
}

if (allocationAmount) {
proposalAllocationAmount = allocationAmount
} else {
Expand All @@ -465,8 +473,10 @@ const useApplicationActions = (
clientAddress,
proposalAllocationAmount,
allocatorType,
!!initialApplication['Client Contract Address'],
)
if (proposalTx !== false) {

if (proposalTx?.pendingVerifyClientTransaction) {
throw new Error('This datacap allocation is already proposed')
}

Expand All @@ -485,7 +495,13 @@ const useApplicationActions = (
'Error sending proposal. Please try again or contact support.',
)
}

setMessage(
`Checking the 'verify client' transaction, it may take a few minutes, please wait... Do not close this window.`,
)

const response = await getStateWaitMsg(messageCID)

if (
typeof response.data === 'object' &&
response.data.ReturnDec.Applied &&
Expand All @@ -495,15 +511,50 @@ const useApplicationActions = (
`Error sending transaction. Please try again or contact support. Error code: ${response.data.ReturnDec.Code}`,
)
}
setMessage(`Transaction sent successfully. CID: ${messageCID}`)

let increaseAllowanceCID

if (initialApplication['Client Contract Address']) {
increaseAllowanceCID = await sendClientIncreaseAllowance({
contractAddress:
typeof selectedAllocator !== 'string'
? selectedAllocator?.address ?? ''
: '',
clientAddress,
proposalAllocationAmount,
})

if (increaseAllowanceCID == null) {
throw new Error(
'Error sending increase allowance transaction. Please try again or contact support.',
)
}

setMessage(
`Checking the 'increase allowance' transaction, it may take a few minutes, please wait... Do not close this window.`,
)

const increaseResponse = await getStateWaitMsg(increaseAllowanceCID)

if (
typeof increaseResponse.data === 'object' &&
increaseResponse.data.ReturnDec.Applied &&
increaseResponse.data.ReturnDec.Code !== 0
) {
throw new Error(
`Error sending transaction. Please try again or contact support. Error code: ${increaseResponse.data.ReturnDec.Code}`,
)
}
}

return await postApplicationProposal(
initialApplication.ID,
requestId,
userName,
owner,
repo,
activeAddress,
messageCID,
{ messageCID, increaseAllowanceCID },
allocationAmount,
)
},
Expand Down Expand Up @@ -533,33 +584,58 @@ const useApplicationActions = (
unknown
>(
async ({ requestId, userName }) => {
const clientAddress = getClientAddress()
const datacap = initialApplication['Allocation Requests'].find(
setMessage(`Searching the pending transactions...`)

let clientAddress = getClientAddress()

if (initialApplication['Client Contract Address']) {
clientAddress = initialApplication['Client Contract Address']
}

const activeRequest = initialApplication['Allocation Requests'].find(
(alloc) => alloc.Active,
)?.['Allocation Amount']
)

const datacap = activeRequest?.['Allocation Amount']

if (datacap == null) throw new Error('No active allocation found')

const proposalTx = await getProposalTx(
clientAddress,
datacap,
allocatorType,
!!initialApplication['Client Contract Address'],
)

if (proposalTx === false) {
if (!proposalTx?.pendingVerifyClientTransaction) {
throw new Error(
'This datacap allocation is not proposed yet. You may need to wait some time if the proposal was just sent.',
)
}

const messageCID = await sendApproval(proposalTx as string)
const signatures: {
verifyClientCid: string
increaseAllowanceCid?: string
} = {
verifyClientCid: '',
}

const messageCID = await sendApproval(
proposalTx?.pendingVerifyClientTransaction,
)

if (messageCID == null) {
throw new Error(
'Error sending proposal. Please try again or contact support.',
)
}

setMessage(
`Checking the 'verify client' transaction, it may take a few minutes, please wait... Do not close this window.`,
)

const response = await getStateWaitMsg(messageCID)

if (
typeof response.data === 'object' &&
response.data.ReturnDec.Applied &&
Expand All @@ -576,14 +652,54 @@ const useApplicationActions = (
`Datacap allocation transaction failed on chain. Application reverted to ReadyToSign. Please try again. Error code: ${response.data.ReturnDec.Code}`,
)
}

signatures.verifyClientCid = messageCID

if (
!proposalTx?.pendingIncreaseAllowanceTransaction &&
initialApplication['Client Contract Address']
) {
throw new Error(
'This increase allowance is not proposed yet. You may need to wait some time if the proposal was just sent.',
)
} else {
const increaseMessageCID = await sendApproval(
proposalTx?.pendingIncreaseAllowanceTransaction,
)

if (messageCID == null) {
throw new Error(
'Error sending proposal. Please try again or contact support.',
)
}

setMessage(
`Checking the 'verify client' transaction, it may take a few minutes, please wait... Do not close this window.`,
)

const response = await getStateWaitMsg(messageCID)

if (
typeof response.data === 'object' &&
response.data.ReturnDec.Applied &&
response.data.ReturnDec.Code !== 0
) {
throw new Error(
`Datacap increase allowance transaction failed on chain. Application reverted to ReadyToSign. Please try again. Error code: ${response.data.ReturnDec.Code}`,
)
}

signatures.increaseAllowanceCid = increaseMessageCID
}

return await postApplicationApproval(
initialApplication.ID,
requestId,
userName,
owner,
repo,
activeAddress,
messageCID,
signatures,
)
},
{
Expand Down Expand Up @@ -712,7 +828,7 @@ const useApplicationActions = (
}

setMessage(
`Checking the '${proposalTx.cidName}' transaction, It may take a few minutes, please wait... Do not close this window.`,
`Checking the '${proposalTx.cidName}' transaction, It may take several seconds, please wait...`,
)

const response = await getStateWaitMsg(messageCID)
Expand Down
Loading

0 comments on commit 5c3e357

Please sign in to comment.