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: integrate with divvy protocol #6492

Open
wants to merge 26 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
de4243d
chore: add redux params
kathaypacific Feb 6, 2025
0c90d29
fix: type
kathaypacific Feb 11, 2025
dcbf216
fix: knip
kathaypacific Feb 11, 2025
58c1886
fix: ensure transaction sagas can handle registration transactions
kathaypacific Feb 12, 2025
cbbc09a
feat: integrate with divvy protocol
kathaypacific Feb 12, 2025
d3984dd
chore: rename registrations variable
kathaypacific Feb 12, 2025
1b50b25
fix: type safe protocol ids
kathaypacific Feb 12, 2025
7c13a3c
Merge branch 'kathy/fl-integration-1' into kathy/fl-integration-2
kathaypacific Feb 12, 2025
883b938
fix: add try catch
kathaypacific Feb 12, 2025
bb9564e
fix: root schema
kathaypacific Feb 12, 2025
b887a35
Merge branch 'kathy/fl-integration-1' into kathy/fl-integration-2
kathaypacific Feb 12, 2025
eb22bcd
Merge branch 'kathy/fl-integration-2' into kathy/fl-integration-3
kathaypacific Feb 12, 2025
47e2a1d
fix: rename
kathaypacific Feb 12, 2025
ae376ff
fix: lint
kathaypacific Feb 12, 2025
e1627e9
chore: add first tests
kathaypacific Feb 12, 2025
87e2ff0
Merge branch 'main' into kathy/fl-integration-2
kathaypacific Feb 12, 2025
0761450
chore: add extra test
kathaypacific Feb 12, 2025
dd13d96
Merge branch 'kathy/fl-integration-2' into kathy/fl-integration-3
kathaypacific Feb 12, 2025
41707f0
chore: add more tests
kathaypacific Feb 12, 2025
e8c969e
fix: nonce
kathaypacific Feb 12, 2025
c7663f4
fix: test title
kathaypacific Feb 12, 2025
77397ce
chore: add test
kathaypacific Feb 12, 2025
80f271b
chore: test
kathaypacific Feb 12, 2025
9fa65f9
fix: comments
kathaypacific Feb 12, 2025
56ae601
Merge branch 'main' into kathy/fl-integration-3
kathaypacific Feb 12, 2025
b26e9e6
chore: spawn tx watcher
kathaypacific Feb 12, 2025
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
2 changes: 2 additions & 0 deletions src/app/selectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,5 @@ export const showNotificationSpotlightSelector = (state: RootState) =>
export const hideWalletBalancesSelector = (state: RootState) => state.app.hideBalances

export const pendingDeepLinkSelector = (state: RootState) => state.app.pendingDeepLinks[0] ?? null

export const divviRegistrationsSelector = (state: RootState) => state.app.divviRegistrations
4 changes: 4 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { LoggerLevel } from 'src/utils/LoggerLevels'
// eslint-disable-next-line import/no-relative-packages
import { TORUS_SAPPHIRE_NETWORK } from '@toruslabs/constants'
import { LaunchArguments } from 'react-native-launch-arguments'
import { SupportedProtocolId } from 'src/divviProtocol/constants'
import { HomeActionName } from 'src/home/types'
import { ToggleableOnboardingFeatures } from 'src/onboarding/types'
import { stringToBoolean } from 'src/utils/parsing'
Expand Down Expand Up @@ -226,3 +227,6 @@ export const ENABLED_QUICK_ACTIONS = (
export const FETCH_FIATCONNECT_QUOTES = true

export const WALLETCONNECT_UNIVERSAL_LINK = 'https://valoraapp.com/wc'

export const DIVVI_PROTOCOL_IDS: SupportedProtocolId[] = []
export const DIVVI_REFERRER_ID: string | undefined = undefined
6 changes: 5 additions & 1 deletion src/divviProtocol/constants.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Address } from 'viem'
import { Address, keccak256, stringToHex } from 'viem'

export const REGISTRY_CONTRACT_ADDRESS: Address = '0x5a1a1027ac1d828e7415af7d797fba2b0cdd5575'

Expand All @@ -21,3 +21,7 @@ const supportedProtocolIds = [
] as const

export type SupportedProtocolId = (typeof supportedProtocolIds)[number]

export const supportedProtocolIdHashes = Object.fromEntries(
supportedProtocolIds.map((protocol) => [keccak256(stringToHex(protocol)), protocol])
)
234 changes: 234 additions & 0 deletions src/divviProtocol/registerReferral.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
import { expectSaga } from 'redux-saga-test-plan'
import * as matchers from 'redux-saga-test-plan/matchers'
import { throwError } from 'redux-saga-test-plan/providers'
import { divviRegistrationCompleted } from 'src/app/actions'
import * as config from 'src/config'
import { registryContractAbi } from 'src/divviProtocol/abi/Registry'
import { REGISTRY_CONTRACT_ADDRESS } from 'src/divviProtocol/constants'
import {
createRegistrationTransactionsIfNeeded,
monitorRegistrationTransaction,
sendPreparedRegistrationTransactions,
} from 'src/divviProtocol/registerReferral'
import { store } from 'src/redux/store'
import { NetworkId } from 'src/transactions/types'
import { publicClient } from 'src/viem'
import { ViemWallet } from 'src/viem/getLockableWallet'
import { getMockStoreData } from 'test/utils'
import { mockAccount } from 'test/values'
import { encodeFunctionData, Hash, parseEventLogs } from 'viem'

// Note: Statsig is not directly used by this module, but mocking it prevents
// require cycles from impacting the tests.
jest.mock('src/statsig')

jest.mock('viem', () => ({
...jest.requireActual('viem'),
readContract: jest.fn(),
parseEventLogs: jest.fn(),
}))

jest.mock('src/redux/store', () => ({ store: { getState: jest.fn() } }))
const mockStore = jest.mocked(store)
mockStore.getState.mockImplementation(getMockStoreData)
mockStore.dispatch = jest.fn()

jest.mock('src/config')

const mockBeefyRegistrationTx = {
data: encodeFunctionData({
abi: registryContractAbi,
functionName: 'registerReferral',
args: ['referrer-id', 'beefy'],
}),
to: REGISTRY_CONTRACT_ADDRESS,
}

describe('createRegistrationTransactionsIfNeeded', () => {
beforeEach(() => {
jest.clearAllMocks()
jest.mocked(config).DIVVI_PROTOCOL_IDS = ['beefy', 'somm']
jest.mocked(config).DIVVI_REFERRER_ID = 'referrer-id'
})

it('returns no transactions if referrer id is not set', async () => {
jest.mocked(config).DIVVI_REFERRER_ID = undefined

const result = await createRegistrationTransactionsIfNeeded({
networkId: NetworkId['op-mainnet'],
})
expect(result).toEqual([])
})

it('returns no transactions if referrer is not registered', async () => {
jest
.spyOn(publicClient.optimism, 'readContract')
.mockImplementation(async ({ functionName, args }) => {
if (functionName === 'getReferrers') {
return ['unrelated-referrer-id'] // Referrer is not registered
}
if (functionName === 'getUsers' && args) {
return [[], []] // User is not registered
}
throw new Error('Unexpected read contract call.')
})

const result = await createRegistrationTransactionsIfNeeded({
networkId: NetworkId['op-mainnet'],
})
expect(result).toEqual([])
})

it('returns no transactions if all registrations are completed', async () => {
mockStore.getState.mockImplementationOnce(() =>
getMockStoreData({
app: {
divviRegistrations: {
[NetworkId['op-mainnet']]: ['beefy', 'somm'],
},
},
})
)
const result = await createRegistrationTransactionsIfNeeded({
networkId: NetworkId['op-mainnet'],
})
expect(result).toEqual([])
})

it('returns transactions for pending registrations only', async () => {
jest
.spyOn(publicClient.optimism, 'readContract')
.mockImplementation(async ({ functionName, args }) => {
if (functionName === 'getReferrers') {
return ['unrelated-referrer-id', 'referrer-id'] // Referrer is registered
}
if (functionName === 'getUsers' && args) {
if (args[0] === 'beefy') {
return [[], []] // User is not registered
}
return [[mockAccount], []] // User is registered
}
throw new Error('Unexpected read contract call.')
})

const result = await createRegistrationTransactionsIfNeeded({
networkId: NetworkId['op-mainnet'],
})
expect(result).toEqual([
{
data: encodeFunctionData({
abi: registryContractAbi,
functionName: 'registerReferral',
args: ['referrer-id', 'beefy'],
}),
to: REGISTRY_CONTRACT_ADDRESS,
},
])
})

it('handles errors in contract reads gracefully and returns no corresponding transactions', async () => {
jest
.spyOn(publicClient.optimism, 'readContract')
.mockImplementation(async ({ functionName, args }) => {
if (functionName === 'getReferrers') {
return ['unrelated-referrer-id', 'referrer-id'] // Referrer is registered
}
if (functionName === 'getUsers' && args) {
if (args[0] === 'beefy') {
return [[], []] // User is not registered
}
throw new Error('Read error for protocol') // simulate error for other protocols
}
throw new Error('Unexpected read contract call.')
})

const result = await createRegistrationTransactionsIfNeeded({
networkId: NetworkId['op-mainnet'],
})
expect(result).toEqual([
{
data: encodeFunctionData({
abi: registryContractAbi,
functionName: 'registerReferral',
args: ['referrer-id', 'beefy'],
}),
to: REGISTRY_CONTRACT_ADDRESS,
},
])
})
})

describe('sendPreparedRegistrationTransactions', () => {
const mockViemWallet = {
account: { address: mockAccount },
signTransaction: jest.fn(async () => '0xsignedTx'),
sendRawTransaction: jest.fn(async () => '0xhash'),
} as any as ViemWallet

it('sends transactions and spawns the monitor transaction saga', async () => {
const mockNonce = 157

await expectSaga(
sendPreparedRegistrationTransactions,
[mockBeefyRegistrationTx],
NetworkId['op-mainnet'],
mockViemWallet,
mockNonce
)
.provide([
[matchers.call.fn(mockViemWallet.signTransaction), '0xsomeSerialisedTransaction'],
[matchers.call.fn(mockViemWallet.sendRawTransaction), '0xhash'],
[matchers.spawn.fn(monitorRegistrationTransaction), null],
])
.spawn(monitorRegistrationTransaction, '0xhash', NetworkId['op-mainnet'])
.returns(mockNonce + 1)
.run()
})

it('does not throw on failure during sending to network, and returns the original nonce', async () => {
const mockNonce = 157

await expectSaga(
sendPreparedRegistrationTransactions,
[mockBeefyRegistrationTx],
NetworkId['op-mainnet'],
mockViemWallet,
mockNonce
)
.provide([
[matchers.call.fn(mockViemWallet.signTransaction), '0xsomeSerialisedTransaction'],
[matchers.call.fn(mockViemWallet.sendRawTransaction), throwError(new Error('failure'))],
])
.not.put(divviRegistrationCompleted(NetworkId['op-mainnet'], 'beefy'))
.returns(mockNonce)
.run()
})
})

describe('monitorRegistrationTransaction', () => {
it('updates the store on successful transaction', async () => {
jest.mocked(parseEventLogs).mockReturnValue([
{
args: {
protocolId: '0x62bd0dd2bb37b275249fe0ec6a61b0fb5adafd50d05a41adb9e1cbfd41ab0607', // keccak256(stringToHex('beefy'))
},
},
] as unknown as ReturnType<typeof parseEventLogs>)

await expectSaga(monitorRegistrationTransaction, '0xhash' as Hash, NetworkId['op-mainnet'])
.provide([
[matchers.call.fn(publicClient.optimism.waitForTransactionReceipt), { status: 'success' }],
])
.put(divviRegistrationCompleted(NetworkId['op-mainnet'], 'beefy'))
.run()
})

it('does not update the store on reverted transaction', async () => {
await expectSaga(monitorRegistrationTransaction, '0xhash' as Hash, NetworkId['op-mainnet'])
.provide([
[matchers.call.fn(publicClient.optimism.waitForTransactionReceipt), { status: 'reverted' }],
])
.not.put(divviRegistrationCompleted(NetworkId['op-mainnet'], 'beefy'))
.run()
})
})
Loading
Loading