Skip to content

Commit

Permalink
feat: auto wallet for publish and edit functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
moritzkirstein committed Apr 29, 2024
1 parent d94a363 commit cdcf9ce
Show file tree
Hide file tree
Showing 4 changed files with 107 additions and 67 deletions.
31 changes: 14 additions & 17 deletions src/@context/Asset.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,15 @@ function AssetProvider({
const newCancelToken = useCancelToken()
const isMounted = useIsMounted()

const [accountIdToCheck, setAccountIdToCheck] = useState<string>(accountId)
useEffect(() => {
if (isAutomationEnabled && autoWallet?.address) {
setAccountIdToCheck(autoWallet.address)
} else {
setAccountIdToCheck(accountId)
}
}, [accountId, autoWallet, isAutomationEnabled])

// -----------------------------------
// Helper: Get and set asset based on passed DID
// -----------------------------------
Expand Down Expand Up @@ -155,11 +164,6 @@ function AssetProvider({
const fetchAccessDetails = useCallback(async (): Promise<void> => {
if (!asset?.chainId || !asset?.services?.length) return

const accountIdToCheck =
isAutomationEnabled && autoWallet?.address
? autoWallet.address
: accountId

const accessDetails = await getAccessDetails(
asset.chainId,
asset.services[0].datatokenAddress,
Expand All @@ -171,14 +175,7 @@ function AssetProvider({
accessDetails
}))
LoggerInstance.log(`[asset] Got access details for ${did}`, accessDetails)
}, [
asset?.chainId,
asset?.services,
accountId,
did,
autoWallet?.address,
isAutomationEnabled
])
}, [asset?.chainId, asset?.services, accountIdToCheck, did])

// -----------------------------------
// Helper: Get and set asset Service Credential state
Expand Down Expand Up @@ -246,7 +243,7 @@ function AssetProvider({
if (!isMounted) return

fetchAccessDetails()
}, [accountId, fetchAccessDetails, isMounted])
}, [accountIdToCheck, fetchAccessDetails, isMounted])

// -----------------------------------
// Check user network against asset network
Expand All @@ -262,11 +259,11 @@ function AssetProvider({
// Asset owner check against wallet user
// -----------------------------------
useEffect(() => {
if (!accountId || !owner) return
if (!accountIdToCheck || !owner) return

const isOwner = accountId?.toLowerCase() === owner.toLowerCase()
const isOwner = accountIdToCheck?.toLowerCase() === owner.toLowerCase()
setIsOwner(isOwner)
}, [accountId, owner])
}, [accountIdToCheck, owner])

// -----------------------------------
// Load ocean config based on asset network
Expand Down
25 changes: 21 additions & 4 deletions src/@hooks/useNftFactory.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,37 @@
import { useEffect, useState } from 'react'
import { NftFactory } from '@oceanprotocol/lib'
import { LoggerInstance, NftFactory } from '@oceanprotocol/lib'
import { getOceanConfig } from '@utils/ocean'
import { useNetwork, useSigner } from 'wagmi'
import { useAutomation } from '../@context/Automation/AutomationProvider'
import { sign } from 'crypto'

Check warning on line 6 in src/@hooks/useNftFactory.ts

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest, 18)

'sign' is defined but never used

function useNftFactory(): NftFactory {
const { chain } = useNetwork()
const { data: signer } = useSigner()
const { autoWallet, isAutomationEnabled } = useAutomation()
const [signerToUse, setSignerToUse] = useState(signer)
const [nftFactory, setNftFactory] = useState<NftFactory>()

useEffect(() => {
if (!signer || !chain?.id) return
if (isAutomationEnabled && autoWallet?.address) {
setSignerToUse(autoWallet)
} else {
setSignerToUse(signer)
}
}, [isAutomationEnabled, autoWallet, signer])

useEffect(() => {
if (!signerToUse || !chain?.id) return

const config = getOceanConfig(chain.id)
const factory = new NftFactory(config?.nftFactoryAddress, signer)
const factory = new NftFactory(config?.nftFactoryAddress, signerToUse)
LoggerInstance.log('[NftFactory] instantiated:', {
chain: chain.id,
factory: factory.address,
signer: signerToUse
})
setNftFactory(factory)
}, [signer, chain?.id])
}, [signerToUse, chain?.id])

return nftFactory
}
Expand Down
95 changes: 53 additions & 42 deletions src/components/Asset/Edit/EditMetadata.tsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,39 @@
import { ReactElement, useState, useEffect } from 'react'
import { Formik } from 'formik'
import {
LoggerInstance,
FixedRateExchange,
generateCredentials,
transformConsumerParameters
} from '@components/Publish/_utils'
import { useAsset } from '@context/Asset'
import { useUserPreferences } from '@context/UserPreferences'
import { useAbortController } from '@hooks/useAbortController'
import {
Asset,
Datatoken,
Nft,
FixedRateExchange,
LoggerInstance,
Metadata,
Nft,
Service
} from '@oceanprotocol/lib'
import { validationSchema } from './_validation'
import { getInitialValues } from './_constants'
import { MetadataEditForm } from './_types'
import { useUserPreferences } from '@context/UserPreferences'
import Web3Feedback from '@shared/Web3Feedback'
import FormEditMetadata from './FormEditMetadata'
import { assetStateToNumber } from '@utils/assetState'
import { mapTimeoutStringToSeconds, normalizeFile } from '@utils/ddo'
import styles from './index.module.css'
import { setMinterToDispenser, setMinterToPublisher } from '@utils/dispenser'
import { decodeTokenURI, setNFTMetadataAndTokenURI } from '@utils/nft'
import { getOceanConfig, getPaymentCollector } from '@utils/ocean'
import { getEncryptedFiles } from '@utils/provider'
import { sanitizeUrl } from '@utils/url'
import { Formik } from 'formik'
import { ReactElement, useEffect, useState } from 'react'
import { useAccount, useNetwork, useProvider, useSigner } from 'wagmi'
import content from '../../../../content/pages/editMetadata.json'
import { useAbortController } from '@hooks/useAbortController'
import { useAutomation } from '../../../@context/Automation/AutomationProvider'
import DebugEditMetadata from './DebugEditMetadata'
import { getOceanConfig, getPaymentCollector } from '@utils/ocean'
import EditFeedback from './EditFeedback'
import { useAsset } from '@context/Asset'
import {
decodeTokenURI,
setNftMetadata,
setNFTMetadataAndTokenURI
} from '@utils/nft'
import { sanitizeUrl } from '@utils/url'
import { getEncryptedFiles } from '@utils/provider'
import { assetStateToNumber } from '@utils/assetState'
import { setMinterToPublisher, setMinterToDispenser } from '@utils/dispenser'
import { useAccount, useProvider, useNetwork, useSigner } from 'wagmi'
import {
transformConsumerParameters,
generateCredentials
} from '@components/Publish/_utils'
import FormEditMetadata from './FormEditMetadata'
import { getInitialValues } from './_constants'
import { MetadataEditForm } from './_types'
import { validationSchema } from './_validation'
import styles from './index.module.css'

export default function Edit({
asset
Expand All @@ -57,6 +54,20 @@ export default function Edit({
const isComputeType = asset?.services[0]?.type === 'compute'
const hasFeedback = error || success

const { autoWallet, isAutomationEnabled } = useAutomation()
const [signerToUse, setSignerToUse] = useState(signer)
const [accountIdToUse, setAccountIdToUse] = useState<string>(accountId)

useEffect(() => {
if (isAutomationEnabled && autoWallet?.address) {
setAccountIdToUse(autoWallet.address)
setSignerToUse(autoWallet)
} else {
setAccountIdToUse(accountId)
setSignerToUse(signer)
}
}, [isAutomationEnabled, autoWallet, signer, accountId])

useEffect(() => {
if (!asset || !provider) return

Expand All @@ -82,7 +93,7 @@ export default function Edit({

const fixedRateInstance = new FixedRateExchange(
config.fixedRateExchangeAddress,
signer
signerToUse
)

const setPriceResp = await fixedRateInstance.setRate(
Expand Down Expand Up @@ -130,10 +141,10 @@ export default function Edit({
(await updateFixedPrice(values.price))

if (values.paymentCollector !== paymentCollector) {
const datatoken = new Datatoken(signer)
const datatoken = new Datatoken(signerToUse)
await datatoken.setPaymentCollector(
asset?.datatokens[0].address,
accountId,
accountIdToUse,
values.paymentCollector
)
}
Expand Down Expand Up @@ -185,9 +196,9 @@ export default function Edit({
asset?.accessDetails?.isPurchasable
) {
const tx = await setMinterToPublisher(
signer,
signerToUse,
asset?.accessDetails?.datatoken?.address,
accountId,
accountIdToUse,
setError
)
if (!tx) return
Expand All @@ -200,15 +211,15 @@ export default function Edit({
// TODO: revert to setMetadata function
const setMetadataTx = await setNFTMetadataAndTokenURI(
updatedAsset,
accountId,
signer,
accountIdToUse,
signerToUse,
decodeTokenURI(asset.nft.tokenURI),
newAbortController()
)
// const setMetadataTx = await setNftMetadata(
// updatedAsset,
// accountId,
// signer,
// accountIdToUse,
// signerToUse,
// newAbortController()
// )

Expand All @@ -224,11 +235,11 @@ export default function Edit({
assetState
})
if (values.assetState !== assetState) {
const nft = new Nft(signer)
const nft = new Nft(signerToUse)

const setMetadataStateTx = await nft.setMetadataState(
asset?.nftAddress,
accountId,
accountIdToUse,
assetStateToNumber(values.assetState)
)
if (!setMetadataStateTx) {
Expand All @@ -243,9 +254,9 @@ export default function Edit({

if (asset.accessDetails.type === 'free') {
const tx = await setMinterToDispenser(
signer,
signerToUse,
asset?.accessDetails?.datatoken?.address,
accountId,
accountIdToUse,
setError
)
if (!tx) return
Expand Down Expand Up @@ -304,7 +315,7 @@ export default function Edit({

<Web3Feedback
networkId={asset?.chainId}
accountId={accountId}
accountId={accountIdToUse}
isAssetNetwork={isAssetNetwork}
/>

Expand Down
23 changes: 19 additions & 4 deletions src/components/Publish/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ReactElement, useState, useRef } from 'react'
import { ReactElement, useState, useRef, useEffect } from 'react'
import { Form, Formik } from 'formik'
import { initialPublishFeedback, initialValues } from './_constants'
import { useAccountPurgatory } from '@hooks/useAccountPurgatory'
Expand All @@ -25,6 +25,7 @@ import { useAbortController } from '@hooks/useAbortController'
import { setNFTMetadataAndTokenURI } from '@utils/nft'
import { customProviderUrl } from '../../../app.config'
import { useAccount, useNetwork, useSigner } from 'wagmi'
import { useAutomation } from '../../@context/Automation/AutomationProvider'

export default function PublishPage({
content
Expand All @@ -51,6 +52,20 @@ export default function PublishPage({
const [ddoEncrypted, setDdoEncrypted] = useState<string>()
const [did, setDid] = useState<string>()

const { autoWallet, isAutomationEnabled } = useAutomation()
const [accountIdToUse, setAccountIdToUse] = useState<string>(accountId)
const [signerToUse, setSignerToUse] = useState(signer)

useEffect(() => {
if (isAutomationEnabled && autoWallet?.address) {
setAccountIdToUse(autoWallet.address)
setSignerToUse(autoWallet)
} else {
setAccountIdToUse(accountId)
setSignerToUse(signer)
}
}, [isAutomationEnabled, autoWallet, accountId, signer])

// --------------------------------------------------
// 1. Create NFT & datatokens & create pricing schema
// --------------------------------------------------
Expand All @@ -72,7 +87,7 @@ export default function PublishPage({
LoggerInstance.log('[publish] using config: ', config)

const { erc721Address, datatokenAddress, txHash } =
await createTokensAndPricing(values, accountId, config, nftFactory)
await createTokensAndPricing(values, accountIdToUse, config, nftFactory)

const isSuccess = Boolean(erc721Address && datatokenAddress && txHash)
if (!isSuccess) throw new Error('No Token created. Please try again.')
Expand Down Expand Up @@ -203,8 +218,8 @@ export default function PublishPage({

const res = await setNFTMetadataAndTokenURI(
ddo,
accountId,
signer,
accountIdToUse,
signerToUse,
values.metadata.nft,
newAbortController()
)
Expand Down

0 comments on commit cdcf9ce

Please sign in to comment.