Skip to content

Commit

Permalink
Bump Vocdoni SDK (#202)
Browse files Browse the repository at this point in the history
* Bump Vocdoni SDK to v0.9.0
* Set strict to false
* Fix breaking sdk changes
* Fixing tests (mocks need review too)
* Fix mocks

---------

Co-authored-by: Òscar Casajuana <elboletaire@gmail.com>
  • Loading branch information
selankon and elboletaire authored Sep 5, 2024
1 parent 44ea2b9 commit 6f8ec1a
Show file tree
Hide file tree
Showing 13 changed files with 46 additions and 96 deletions.
13 changes: 13 additions & 0 deletions .swcrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true,
"dynamicImport": true
},
"target": "es2021"
},
"module": {
"type": "commonjs"
}
}
2 changes: 1 addition & 1 deletion jest.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const config = {
transform: {
'^.+\\.(ts|tsx|js|jsx)?$': '@swc-node/jest',
},
transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$'],
transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\](?!ffjavascript).+\\.(js|jsx)$'],
testPathIgnorePatterns: ['[/\\\\]dist[/\\\\].+\\.(js|jsx)$'],
setupFilesAfterEnv: ['@testing-library/jest-dom', './setup-tests.ts'],
globals: {
Expand Down
2 changes: 1 addition & 1 deletion mocks/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export const handlers = [
rest.post('https://api*.vocdoni.*/v2/accounts', (req, res, ctx) => {
return res(ctx.status(200), ctx.body('0xmocked'))
}),
rest.get('https://api*.vocdoni.*/v2/chain/transactions/reference/*', (req, res, ctx) => {
rest.get('https://api*.vocdoni.*/v2/chain/transactions/*', (req, res, ctx) => {
return res(ctx.status(200), ctx.body('ok'))
}),
rest.post('https://api*.vocdoni.*/v2/accounts', (req, res, ctx) => {
Expand Down
4 changes: 2 additions & 2 deletions packages/chakra-components/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
"@chakra-ui/toast": "^7.0.2",
"@ethersproject/abstract-signer": "^5.7.0",
"@ethersproject/wallet": "^5.7.0",
"@vocdoni/sdk": "~0.8.2",
"@vocdoni/sdk": "~0.9.0",
"react": ">= 16.8.0",
"react-dom": ">= 16.8.0",
"react-markdown": ">= 8.0.0",
Expand Down Expand Up @@ -81,7 +81,7 @@
"@ethersproject/wallet": "^5.7.0",
"@types/react": "^18.0.30",
"@types/react-dom": "^18.0.11",
"@vocdoni/sdk": "~0.8.2",
"@vocdoni/sdk": "~0.9.0",
"date-fns": "^2.29.3",
"eslint": "^8.42.0",
"eslint-config-prettier": "^8.8.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Text } from '@chakra-ui/layout'
import { chakra, useMultiStyleConfig } from '@chakra-ui/system'
import { Signer } from '@ethersproject/abstract-signer'
import { useClient, useElection } from '@vocdoni/react-providers'
import { ArchivedElection, ElectionStatus, InvalidElection, PublishedElection } from '@vocdoni/sdk'
import { ElectionStatus, InvalidElection, PublishedElection } from '@vocdoni/sdk'
import { useEffect, useState } from 'react'
import { Button } from '../layout/Button'
import { results } from './Results'
Expand All @@ -24,7 +24,7 @@ export const VoteButton = (props: ButtonProps) => {
} = useElection()
const [loading, setLoading] = useState<boolean>(false)

if (!election || election instanceof InvalidElection || election instanceof ArchivedElection) {
if (!election || election instanceof InvalidElection) {
return null
}

Expand Down
7 changes: 2 additions & 5 deletions packages/extended-sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,10 @@
},
"main": "src/index.ts",
"devDependencies": {
"@vocdoni/sdk": "https://github.com/vocdoni/vocdoni-sdk.git#main"
"@vocdoni/sdk": "~0.9.0"
},
"peerDependencies": {
"@vocdoni/sdk": "~0.8.1"
},
"resolutions": {
"@vocdoni/sdk": "https://github.com/vocdoni/vocdoni-sdk.git#main"
"@vocdoni/sdk": "~0.9.0"
},
"clean-package": "../../clean-package.config.json"
}
76 changes: 7 additions & 69 deletions packages/extended-sdk/src/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,66 +8,19 @@ import {
FetchTransactionsParametersWithPagination,
FetchTransfersParametersWithPagination,
FetchVotesParametersWithPagination,
IChainBlockInfoResponse,
PaginationRequest,
PaginationResponse,
VocdoniSDKClient,
VoteAPI,
} from '@vocdoni/sdk'

export class ExtendedSDKClient extends VocdoniSDKClient {
blockByHeight = (height: number) => ChainAPI.blockByHeight(this.url, height)
blockByHeight = (height: number) => ChainAPI.blockInfoHeight(this.url, height)

blockByHash = (hash: string) => ChainAPI.blockByHash(this.url, hash)
blockByHash = (hash: string) => ChainAPI.blockInfoHash(this.url, hash)

blockToDate = (height: number): ReturnType<typeof ChainAPI.blockToDate> => ChainAPI.blockToDate(this.url, height)

blockList = ({
totalItems, // Needed to construct the pagination response and first block of the page
page,
limit = 10,
}: BlockListParametersWithPagination): Promise<BlockListResponseWithPagination> => {
const promises: Promise<IChainBlockInfoResponse | BlockError>[] = []

// Calculate the first block index for the reuqested page
const firstPageBlock = totalItems - page * limit + 1 - limit

for (let i = 0; i < limit; i++) {
if (firstPageBlock + i <= 0) continue
promises.push(
(async () => {
try {
return await this.blockByHeight(firstPageBlock + i)
} catch (error) {
if (error instanceof ErrBlockNotFound) {
return new BlockNotFoundError(firstPageBlock + i, error)
}
if (error instanceof ErrAPI) {
return new BlockError(firstPageBlock + i, error)
}
throw error // re-throw other errors
}
})()
)
}

const lastPage = Math.ceil(totalItems / limit) - 1

return Promise.all(promises).then((blockInfo) => {
// flatten the array[][] into array[]
return {
// @ts-ignore
blocks: blockInfo.reverse(),
pagination: {
totalItems,
previousPage: page > 0 ? page - 1 : 0,
currentPage: page,
nextPage: page < lastPage ? page + 1 : lastPage,
lastPage: lastPage,
},
}
})
}
blockList = (params: BlockListQueryParamsWithPagination) => ChainAPI.blocksList(this.url, params)

chainInfo = () => ChainAPI.info(this.url)

Expand All @@ -84,29 +37,14 @@ export class ExtendedSDKClient extends VocdoniSDKClient {

txCosts = () => ChainAPI.txCosts(this.url)
txInfo = (txHash: string) => ChainAPI.txInfo(this.url, txHash)
txInfoByBlock = (blockHeight: number, txIndex: number) => ChainAPI.txInfoByBlock(this.url, blockHeight, txIndex)
txByIndex = (index: number) => ChainAPI.txByIndex(this.url, index)
txList = (params?: Partial<FetchTransactionsParametersWithPagination>) => ChainAPI.txList(this.url, params)

validatorsList = () => ChainAPI.validatorsList(this.url)
voteInfo = (voteId: string) => VoteAPI.info(this.url, voteId)
}

export class BlockError extends Error {
public height: number

constructor(height: number, error: ErrAPI | ErrBlockNotFound) {
super(error.message, error)
this.height = height
}
}

export class BlockNotFoundError extends BlockError {}

export type BlockListResponseWithPagination = {
blocks: Array<IChainBlockInfoResponse | BlockError>
} & PaginationResponse

export type BlockListParametersWithPagination = {
totalItems: number
// Not exported properly by the sdk, awaiting new version
export type BlockListQueryParamsWithPagination = {
hash?: string // Filter by partial hash
chainId?: string // Filter by exact chainId
} & PaginationRequest
4 changes: 2 additions & 2 deletions packages/react-providers/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@
"peerDependencies": {
"@ethersproject/abstract-signer": "^5.7.0",
"@ethersproject/wallet": "^5.7.0",
"@vocdoni/sdk": "~0.8.2",
"@vocdoni/sdk": "~0.9.0",
"react": ">= 16.8.0"
},
"devDependencies": {
"@ethersproject/abstract-signer": "^5.7.0",
"@ethersproject/wallet": "^5.7.0",
"@types/latinize": "^0.2.15",
"@types/react": "^18.0.30",
"@vocdoni/sdk": "~0.8.2",
"@vocdoni/sdk": "~0.9.0",
"eslint": "^8.42.0",
"eslint-config-prettier": "^8.8.0",
"eslint-config-react-app": "^7.0.1",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import {
AnonymousService,
AnonymousVote,
ArchivedElection,
areEqualHexStrings,
CensusType,
ChainAPI,
Expand All @@ -21,7 +20,7 @@ import { BlindCspServiceKey, useElectionReducer } from './use-election-reducer'

export type ElectionProviderProps = {
id?: string
election?: PublishedElection | InvalidElection | ArchivedElection
election?: PublishedElection | InvalidElection
ConnectButton?: ComponentType
fetchCensus?: boolean
beforeSubmit?: (vote: Vote) => boolean
Expand Down
17 changes: 6 additions & 11 deletions packages/react-providers/src/election/use-election-reducer.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {
ArchivedElection,
areEqualHexStrings,
CensusType,
InvalidElection,
Expand Down Expand Up @@ -94,7 +93,7 @@ export interface ElectionReducerState {
id: string | undefined
isAbleToVote: boolean | undefined
isInCensus: boolean
election: PublishedElection | InvalidElection | ArchivedElection | undefined
election: PublishedElection | InvalidElection | undefined
vote: Vote | undefined
voter: string | undefined
votesLeft: number
Expand Down Expand Up @@ -126,7 +125,7 @@ export interface ElectionReducerState {
turnout: number
}

const participation = (election?: PublishedElection | InvalidElection | ArchivedElection) => {
const participation = (election?: PublishedElection | InvalidElection) => {
if (!election || election instanceof InvalidElection || (!election.census && !election.maxCensusSize)) {
return 0
}
Expand All @@ -136,7 +135,7 @@ const participation = (election?: PublishedElection | InvalidElection | Archived
return Math.round((election.voteCount / size) * 10000) / 100
}

const turnout = (election?: PublishedElection | InvalidElection | ArchivedElection) => {
const turnout = (election?: PublishedElection | InvalidElection) => {
if (!election || election instanceof InvalidElection || (!election.census && !election.maxCensusSize)) {
return 0
}
Expand All @@ -151,7 +150,7 @@ export const electionStateEmpty = ({
election,
}: {
client: VocdoniSDKClient
election?: PublishedElection | InvalidElection | ArchivedElection
election?: PublishedElection | InvalidElection
}): ElectionReducerState => ({
client,
connected: false,
Expand Down Expand Up @@ -447,10 +446,7 @@ const electionReducer: Reducer<ElectionReducerState, ElectionAction> = (
}
}

export const useElectionReducer = (
client: VocdoniSDKClient,
election?: PublishedElection | ArchivedElection | InvalidElection
) => {
export const useElectionReducer = (client: VocdoniSDKClient, election?: PublishedElection | InvalidElection) => {
const initial = electionStateEmpty({ client, election })
const { connected } = useClient()
const [state, dispatch] = useReducer(electionReducer, {
Expand All @@ -460,8 +456,7 @@ export const useElectionReducer = (

const clear = () => dispatch({ type: CensusClear })
const setClient = (client: VocdoniSDKClient) => dispatch({ type: ElectionClientSet, payload: client })
const set = (election: PublishedElection | ArchivedElection | InvalidElection) =>
dispatch({ type: ElectionSet, payload: election })
const set = (election: PublishedElection | InvalidElection) => dispatch({ type: ElectionSet, payload: election })
const sikPassword = (password: SikPayload) => dispatch({ type: SikPasswordSet, payload: password })
const sikSignature = (signature: SikPayload) => dispatch({ type: SikSignatureSet, payload: signature })
// Some census types require to have a local client instance. This var stores if the current election is one of those
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ describe('<OrganizationProvider />', () => {
balance: 0,
electionIndex: 0,
nonce: 0,
feesCount: 0,
sik: '',
transfersCount: 0,
}

const { result, rerender } = renderHook(() => useOrganization(), { wrapper, initialProps: { organization } })
Expand All @@ -49,6 +52,9 @@ describe('<OrganizationProvider />', () => {
balance: 0,
electionIndex: 0,
nonce: 0,
feesCount: 0,
sik: '',
transfersCount: 0,
}

rerender({ organization: neworg })
Expand Down
2 changes: 2 additions & 0 deletions setup-tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,5 @@ Object.defineProperty(window, 'MockedWindowURL', {

// required by any react component (almost all of them)
global.React = React

global.URL.createObjectURL = jest.fn()
2 changes: 1 addition & 1 deletion templates/chakra/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"@emotion/styled": "^11.10.6",
"@rainbow-me/rainbowkit": "^1.2.0",
"@vocdoni/chakra-components": "*",
"@vocdoni/sdk": "~0.8.0",
"@vocdoni/sdk": "~0.9.0",
"date-fns": "^2.29.3",
"ethers": "^5.7.2",
"formik": "^2.2.9",
Expand Down

0 comments on commit 6f8ec1a

Please sign in to comment.