Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(lens): update validation method #463

Merged
merged 19 commits into from
Jul 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/large-maps-decide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@rabbitholegg/questdk-plugin-utils": minor
"@rabbitholegg/questdk-plugin-lens": minor
---

update validation method for lens
3 changes: 2 additions & 1 deletion packages/lens/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@
"author": "",
"license": "ISC",
"dependencies": {
"@lens-protocol/client": "2.3.0",
"@rabbitholegg/questdk": "workspace:*",
"@rabbitholegg/questdk-plugin-utils": "workspace:*",
"@lens-protocol/client": "2.3.0"
"alchemy-sdk": "3.3.1"
}
}
2 changes: 1 addition & 1 deletion packages/lens/src/Lens.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { validateCollect } from './Lens'
import { beforeEach, describe, expect, test, vi, MockedFunction } from 'vitest'
import { MockedFunction, beforeEach, describe, expect, test, vi } from 'vitest'

vi.mock('./Lens', () => ({
validateCollect: vi.fn(),
Expand Down
11 changes: 3 additions & 8 deletions packages/lens/src/Lens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type CollectValidationParams,
type PluginActionValidation,
type QuestCompletionPayload,
ValidationNotValid,
} from '@rabbitholegg/questdk-plugin-utils'
import { type Address } from 'viem'

Expand Down Expand Up @@ -45,14 +46,8 @@ export const validateCollect = async (
)
return hasCollected
} catch (err) {
if (err instanceof Error) {
const error = new Error(err.message)
error.name = 'ValidationNotValid'
throw error
} else {
console.error(err)
throw new Error('Unknown error')
}
console.error('[lens-plugin] Error while validating collect action')
throw new ValidationNotValid(err instanceof Error ? err : String(err))
}
}

Expand Down
9 changes: 9 additions & 0 deletions packages/lens/src/alchemy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Alchemy, Network } from 'alchemy-sdk'

const settings = {
apiKey: process.env.ALCHEMY_API_KEY,
network: Network.MATIC_MAINNET,
requestTimeout: 2000,
Copy link
Collaborator Author

@mmackz mmackz Jun 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It isn't required, but I put an arbitrary value as the requestTimeout. Thought was to let it timeout soonish and hit the reservoir backup. I couldn't find the default value and didn't want it to hang for too long.

Not sure if this is too much or too little.

}

export const alchemy = new Alchemy(settings)
11 changes: 0 additions & 11 deletions packages/lens/src/client.ts

This file was deleted.

126 changes: 85 additions & 41 deletions packages/lens/src/validate.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { alchemy } from './alchemy'
import {
LensClient,
production,
type SimpleCollectOpenActionSettingsFragment,
type MultirecipientFeeCollectOpenActionSettingsFragment,
type SimpleCollectOpenActionSettingsFragment,
production,
} from '@lens-protocol/client'
import { getClient } from './client'
import { Chains } from '@rabbitholegg/questdk-plugin-utils'
import { Address } from 'viem'
import { GetTransfersForOwnerTransferType } from 'alchemy-sdk'
import axios from 'axios'
import { Address, zeroAddress } from 'viem'

const lensClient = new LensClient({
environment: production,
Expand All @@ -20,53 +21,96 @@ export async function hasAddressCollectedPost(
if (collectAddress === null) {
return false
}
const amountOwned = await checkAddressOwnsCollect(address, collectAddress)
return amountOwned > 0n
return await checkAddressMintedCollect(address, collectAddress)
}

export async function getCollectAddress(postId: string) {
const result = await lensClient.publication.fetch({
forId: postId,
})
if (!result || result?.__typename === 'Mirror') {
try {
const result = await lensClient.publication.fetch({
forId: postId,
})
if (!result || result?.__typename === 'Mirror') {
return null
}
const openActions = result.openActionModules
if (!openActions || openActions.length === 0) {
return null
}
const collectActions = openActions.filter(
(action) =>
action.__typename === 'SimpleCollectOpenActionSettings' ||
action.__typename === 'MultirecipientFeeCollectOpenActionSettings',
) as Array<
| MultirecipientFeeCollectOpenActionSettingsFragment
| SimpleCollectOpenActionSettingsFragment
>

const collectNft = collectActions.find((action) => action.collectNft)
const collectAddress = collectNft?.collectNft?.toLowerCase()
return (collectAddress as Address) ?? null
} catch (error) {
console.error('Error fetching collect contract address', error)
return null
}
const openActions = result.openActionModules
if (!openActions || openActions.length === 0) {
return null
}

export async function checkAddressMintedCollect(
actor: Address,
collectAddress: Address,
) {
try {
return await checkMintedUsingAlchemy(actor, collectAddress)
} catch (err) {
console.error('Error while using alchemy api', err)
return await checkMintedUsingReservoir(actor, collectAddress)
}
const collectActions = openActions.filter(
(action) =>
action.__typename === 'SimpleCollectOpenActionSettings' ||
action.__typename === 'MultirecipientFeeCollectOpenActionSettings',
) as Array<
| MultirecipientFeeCollectOpenActionSettingsFragment
| SimpleCollectOpenActionSettingsFragment
>
}

const collectNft = collectActions.find((action) => action.collectNft)
const collectAddress = collectNft?.collectNft?.toLowerCase()
return (collectAddress as Address) ?? null
async function checkMintedUsingAlchemy(
actor: Address,
collectAddress: Address,
) {
// alchemy will work without an api key, but we risk being rate-limited
if (!process.env.ALCHEMY_API_KEY) {
console.error('Alchemy API key not found')
}

const options = {
contractAddresses: [collectAddress],
}

const transfers = await alchemy.nft.getTransfersForOwner(
actor,
GetTransfersForOwnerTransferType.TO,
options,
)

// only count nfts that originate from zeroAddress
const mintedNfts = transfers.nfts.filter((nft) => nft.from === zeroAddress)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clever - you know we could actually handle this just with the contract Transfer events. Just ship this implementation though that's hilarious it's full circle though.


return mintedNfts.length > 0
}

export async function checkAddressOwnsCollect(
async function checkMintedUsingReservoir(
actor: Address,
collectAddress: Address,
) {
const client = getClient(Chains.POLYGON_POS)
const result = await client.readContract({
address: collectAddress as Address,
abi: [
{
inputs: [{ internalType: 'address', name: 'owner', type: 'address' }],
name: 'balanceOf',
outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],
stateMutability: 'view',
type: 'function',
},
],
functionName: 'balanceOf',
args: [actor],
const baseUrl = 'https://api-polygon.reservoir.tools/users/activity/v6'
const params = new URLSearchParams({
users: actor,
collection: collectAddress,
limit: '1',
types: 'mint',
})
return result

const options = {
method: 'GET',
url: `${baseUrl}?${params.toString()}`,
headers: {
accept: '*/*',
},
}

const response = await axios.request(options)
return response.data?.activities?.length > 0
}
2 changes: 1 addition & 1 deletion packages/lens/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
export default {
build: {
rollupOptions: {
external: [/@rabbitholegg/, /@lens-protocol/],
external: [/@rabbitholegg/, /@lens-protocol/, 'alchemy-sdk'],
},
lib: {
entry: 'src/index.ts',
Expand Down
5 changes: 4 additions & 1 deletion packages/utils/src/errors/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
export { PluginActionNotImplementedError } from './plugin'
export {
PluginActionNotImplementedError,
ValidationNotValid,
} from './plugin'
13 changes: 13 additions & 0 deletions packages/utils/src/errors/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,16 @@ export class PluginActionNotImplementedError extends Error {
this.name = 'PluginActionNotImplementedError'
}
}

export class ValidationNotValid extends Error {
constructor(input: string | Error) {
if (input instanceof Error) {
super(input.message)
Object.assign(this, input)

this.name = 'ValidationNotValid'
} else {
super(input)
}
}
}
5 changes: 4 additions & 1 deletion packages/utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,4 +141,7 @@ export {
PremintActionFormSchema,
} from './types'

export { PluginActionNotImplementedError } from './errors'
export {
PluginActionNotImplementedError,
ValidationNotValid,
} from './errors'
37 changes: 34 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading