Skip to content

Commit

Permalink
initial integration
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiolalombardim committed May 18, 2024
1 parent 34e66af commit 2d38549
Show file tree
Hide file tree
Showing 6 changed files with 150 additions and 61 deletions.
26 changes: 26 additions & 0 deletions src/models/Contract.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export interface ArbitraryContract {
counter: number
name: string
type: string
children: ContractChild[]
}

interface ContractChild {
counter: number
name: string
type: string
children: ParametersList[]
placeholder: string
validate: any
initValue: string
}

interface ParametersList {
counter: number
name: string
type: string
children: ParametersList[]
placeholder: string
validate: any
initValue: string
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { useMemo, useState } from "react"
import {
CircularProgress,
Grid,
InputAdornment,
Paper,
Expand All @@ -12,49 +13,21 @@ import {
} from "@material-ui/core"
import { ProposalFormInput } from "./ProposalFormInput"
import { validateContractAddress, validateAddress } from "@taquito/utils"
import { ErrorMessage, Field, FieldArray, Form, Formik, FormikErrors, getIn } from "formik"
import { Field, FieldArray, Form, Formik, FormikErrors, getIn } from "formik"
import { SmallButtonDialog } from "modules/common/SmallButton"
import { SearchLambda } from "./styled/SearchLambda"
import { ArrowBackIos } from "@material-ui/icons"
import { SearchEndpoints } from "./SearchEndpoints"
import { toShortAddress } from "services/contracts/utils"

export interface Endpoint {
key: string
parameters: Parameter[]
}
import { useArbitraryContractData } from "services/aci/useArbitratyContractData"
import { useTezos } from "services/beacon/hooks/useTezos"
import { ArbitraryContract } from "models/Contract"

interface Parameter {
key: string
type: string
value?: any
}

const endpoints: Endpoint[] = [
{
key: "add_controller",
parameters: [
{
key: "id",
type: "string"
},
{
key: "duration",
type: "number"
}
]
},
{
key: "approve",
parameters: [
{
key: "vote",
type: "boolean"
}
]
}
]

const TypeText = styled(Typography)(({ theme }) => ({
fontSize: 14,
fontWeight: 300,
Expand Down Expand Up @@ -147,12 +120,16 @@ const ContractInteractionForm = ({
touched,
setFieldTouched,
setFieldError,
isValid
isValid,
showHeader
}: any) => {
const [state, setState] = useState<Status>(Status.NEW_INTERACTION)
const [endpoint, setEndpoint] = useState<Endpoint | undefined>(undefined)
const [endpoint, setEndpoint] = useState<ArbitraryContract | undefined>(undefined)
const theme = useTheme()
const isMobileSmall = useMediaQuery(theme.breakpoints.down("sm"))
const { mutate: fetchContractData, data } = useArbitraryContractData()
const { network } = useTezos()
const [isLoading, setIsLoading] = useState(false)

const shouldContinue = useMemo(() => {
if (values.destination_contract !== "" && !errors.destination_contract) {
Expand All @@ -165,16 +142,24 @@ const ContractInteractionForm = ({
if (getIn(values, "amount") === "") {
setFieldValue("amount", 0)
}
setState(Status.CONTRACT_VALIDATED)
setIsLoading(true)
fetchContractData({
contract: getIn(values, "destination_contract"),
network: network,
handleContinue: () => setState(Status.CONTRACT_VALIDATED),
finishLoad: () => setIsLoading(false),
showHeader: () => showHeader(false)
})
}

const processParameters = (data: Endpoint) => {
const processParameters = (data: ArbitraryContract) => {
setEndpoint(data)
setFieldValue("parameters", data.parameters)
setFieldValue("target_endpoint", data.key)
setFieldValue("parameters", data.children)
setFieldValue("target_endpoint", data.name)
}

const goBack = () => {
showHeader(true)
setState(Status.NEW_INTERACTION)
setEndpoint(undefined)
}
Expand Down Expand Up @@ -245,7 +230,7 @@ const ContractInteractionForm = ({
<SubContainer item>
<Title color="textPrimary">Contract Endpoint</Title>
<ProposalFormInput>
<SearchEndpoints endpoints={endpoints} handleChange={processParameters} />
<SearchEndpoints endpoints={data ? data.children : []} handleChange={processParameters} />
</ProposalFormInput>
</SubContainer>
{endpoint && (
Expand All @@ -254,15 +239,15 @@ const ContractInteractionForm = ({
name="parameters"
render={arrayHelpers => (
<Container>
{endpoint.parameters.length > 0 &&
endpoint.parameters.map((param, index) => (
{endpoint.children.length > 0 &&
endpoint.children.map((param, index) => (
<div key={index}>
<ProposalFormInput label={`Parameter ${index + 1}`} key={`${param.key}`}>
<ProposalFormInput label={`Parameter ${index + 1}`} key={`${param.name}`}>
<Field
component={CustomFormikTextField}
name={`parameters.${index}`}
type={param.type === "number" ? "number" : "string"}
placeholder={`${param.key}`}
placeholder={`${param.name}`}
onChange={(newValue: any) => {
setFieldValue(`parameters.${index}.value`, newValue.target.value, false)
if (newValue.target.value === "") {
Expand Down Expand Up @@ -294,9 +279,13 @@ const ContractInteractionForm = ({

{state === Status.NEW_INTERACTION ? (
<Grid container direction="row" justifyContent="flex-end" style={{ marginTop: 30 }} spacing={2}>
<SmallButtonDialog variant="contained" disabled={shouldContinue} onClick={validateAddress}>
Continue
</SmallButtonDialog>
{isLoading ? (
<CircularProgress color="secondary" size={30} />
) : (
<SmallButtonDialog variant="contained" disabled={shouldContinue} onClick={validateAddress}>
Continue
</SmallButtonDialog>
)}
</Grid>
) : state === Status.CONTRACT_VALIDATED ? (
<Grid
Expand Down Expand Up @@ -324,9 +313,10 @@ const ContractInteractionForm = ({
)
}

export const ArbitraryContractInteractionForm: React.FC = () => {
const isInvalidKtOrTzAddress = (address: string) =>
validateContractAddress(address) !== 3 && validateAddress(address) !== 3
export const ArbitraryContractInteractionForm: React.FC<{ showHeader: (state: boolean) => void }> = ({
showHeader
}) => {
const isInvalidKtOrTzAddress = (address: string) => validateContractAddress(address) !== 3

const initialValue: ACIValues = {
destination_contract: "",
Expand Down Expand Up @@ -358,7 +348,7 @@ export const ArbitraryContractInteractionForm: React.FC = () => {
return errors
}

const saveInfo = () => {
const interact = () => {
console.log("saveInfo")
}

Expand All @@ -367,7 +357,7 @@ export const ArbitraryContractInteractionForm: React.FC = () => {
validateOnChange={true}
validateOnBlur={true}
validate={validateForm}
onSubmit={saveInfo}
onSubmit={interact}
initialValues={initialValue}
>
{({
Expand All @@ -393,6 +383,7 @@ export const ArbitraryContractInteractionForm: React.FC = () => {
setFieldTouched={setFieldTouched}
setFieldError={setFieldError}
isValid={isValid}
showHeader={showHeader}
/>
</Form>
)
Expand Down
15 changes: 10 additions & 5 deletions src/modules/explorer/components/ConfigProposalFormLambda.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Grid, Typography, styled, CircularProgress } from "@material-ui/core"
import React, { useCallback, useEffect } from "react"
import React, { useCallback, useEffect, useState } from "react"
import { useDAO } from "services/services/dao/hooks/useDAO"
import { FormProvider, useForm } from "react-hook-form"
import { useDAOID } from "../pages/DAO/router"
Expand Down Expand Up @@ -155,6 +155,8 @@ export const ProposalFormLambda: React.FC<Props> = ({ open, handleClose, action
const { mutate: lambdaRemove } = useLambdaRemovePropose()
const { mutate: lambdaExecute } = useLambdaExecutePropose()

const [showHeader, setShowHeader] = useState(true)

const lambdaForm = useForm<Values>()
const ACIForm = useForm<ACIValues>()

Expand Down Expand Up @@ -332,9 +334,12 @@ export const ProposalFormLambda: React.FC<Props> = ({ open, handleClose, action
const renderExecuteProposal = () => {
return (
<>
<ProposalFormInput label="Function Name">
<SearchLambda lambdas={daoLambdas} handleChange={handleSearchChange} />
</ProposalFormInput>
{showHeader ? (
<ProposalFormInput label="Function Name">
<SearchLambda lambdas={daoLambdas} handleChange={handleSearchChange} />
</ProposalFormInput>
) : null}

{lambda?.key !== ARBITRARY_CONTRACT_INTERACTION ? (
<>
<ProposalCodeEditorInput
Expand Down Expand Up @@ -378,7 +383,7 @@ export const ProposalFormLambda: React.FC<Props> = ({ open, handleClose, action
/>
</>
) : (
<ArbitraryContractInteractionForm />
<ArbitraryContractInteractionForm showHeader={setShowHeader} />
)}
</>
)
Expand Down
2 changes: 1 addition & 1 deletion src/modules/explorer/components/ProposalActionsDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ export const ProposalActionsDialog: React.FC<Props> = ({ open, handleClose }) =>
onClick={() =>
elem.id === "off-chain"
? handleLiteProposal()
: !shouldDisable
: true
? elem.isLambda
? handleOpenCustomProposalModal(elem.id)
: handleOpenSupportedExecuteProposalModal(elem.id)
Expand Down
8 changes: 4 additions & 4 deletions src/modules/explorer/components/SearchEndpoints.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from "react"
import { Grid, InputAdornment, makeStyles, styled, TextField, Theme, withStyles } from "@material-ui/core"
import { SearchOutlined } from "@material-ui/icons"
import { Autocomplete } from "@material-ui/lab"
import { Endpoint } from "./ArbitraryContractInteractionForm"
import { ArbitraryContract } from "models/Contract"

const StyledType = styled(Grid)({
opacity: 0.65
Expand Down Expand Up @@ -75,7 +75,7 @@ const useStyles = makeStyles({
})

export const SearchEndpoints: React.FC<{
endpoints: Array<Endpoint> | undefined
endpoints: Array<ArbitraryContract> | undefined
handleChange?: any
}> = ({ endpoints, handleChange }) => {
useStyles()
Expand All @@ -87,10 +87,10 @@ export const SearchEndpoints: React.FC<{
disablePortal
id="combo-box-demo"
options={endpoints}
getOptionLabel={(option: any) => option.key}
getOptionLabel={(option: any) => option.name}
renderOption={(option: any, state: any) => (
<Grid container direction="row" justifyContent="space-between" {...state}>
<Grid>{option.key}</Grid>
<Grid>{option.name}</Grid>
<StyledType>{option.type}</StyledType>
</Grid>
)}
Expand Down
67 changes: 67 additions & 0 deletions src/services/aci/useArbitratyContractData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { useMutation, useQueryClient } from "react-query"
import { useNotification } from "modules/common/hooks/useNotification"
import { useTezos } from "services/beacon/hooks/useTezos"
import mixpanel from "mixpanel-browser"
import { Network } from "services/beacon"
import { EnvKey, getEnv } from "services/config"

export const useArbitraryContractData = () => {
const queryClient = useQueryClient()
const openNotification = useNotification()
const { network, tezos, account, connect } = useTezos()

return useMutation<
any | Error,
Error,
{
contract: string
network: Network
handleContinue: () => void
finishLoad: (status: boolean) => void
showHeader: (status: boolean) => void
}
>(
async ({ contract, network, handleContinue, finishLoad, showHeader }) => {
try {
let tezosToolkit = tezos

if (!account) {
tezosToolkit = await connect()
}

const resp = await fetch(`${getEnv(EnvKey.REACT_APP_API_URL)}/aci/${contract}`, {
method: "POST",
body: JSON.stringify({ network: network }),
headers: { "Content-Type": "application/json" }
})

const data = await resp.json()
finishLoad(false)
if (data.success === false) {
openNotification({
message: "Invalid contract address with unsupported prefix.",
variant: "error",
autoHideDuration: 10000
})
} else {
handleContinue()
showHeader(false)
}
return data
} catch (e) {
console.log(e)
openNotification({
message: "Contract's data could not be fetch!",
variant: "error",
autoHideDuration: 10000
})
return new Error((e as Error).message)
}
},
{
onSuccess: () => {
queryClient.resetQueries()
}
}
)
}

0 comments on commit 2d38549

Please sign in to comment.