From d5c077a352ee3ab75da70fb56666ba6c519237b1 Mon Sep 17 00:00:00 2001 From: Bassgeta Date: Mon, 2 Dec 2024 12:03:28 +0100 Subject: [PATCH] Feat: Create proxy chain app Feat: Create proxy chain app, add Docker config and refactoring --- .eslintrc.js | 14 +- .gitignore | 3 +- Dockerfile | 7 + apps/main-chain/.env.example | 1 + apps/main-chain/Dockerfile | 22 -- apps/main-chain/package.json | 30 +- apps/main-chain/src/amplifyClient.ts | 65 +--- apps/main-chain/src/blockListener.ts | 59 --- apps/main-chain/src/blockManager.ts | 8 + apps/main-chain/src/blockProcessor.ts | 218 ----------- apps/main-chain/src/eventListeners/colony.ts | 18 +- .../src/eventListeners/eventListeners.ts | 45 --- .../src/eventListeners/extension/index.ts | 31 +- .../src/eventListeners/extension/multiSig.ts | 12 +- .../eventListeners/extension/oneTxPayment.ts | 4 +- .../extension/stagedExpenditure.ts | 4 +- .../extension/stakedExpenditure.ts | 4 +- .../extension/streamingPayments.ts | 4 +- .../extension/votingReputation.ts | 4 +- apps/main-chain/src/eventListeners/index.ts | 2 - apps/main-chain/src/eventListeners/network.ts | 6 +- .../src/eventListeners/proxyColonies.ts | 6 +- apps/main-chain/src/eventListeners/token.ts | 13 +- apps/main-chain/src/eventListeners/types.ts | 61 ---- apps/main-chain/src/eventManager.ts | 6 + .../handlers/actions/annotateTransaction.ts | 14 +- .../src/handlers/actions/colonyUpgrade.ts | 23 +- .../src/handlers/actions/createDomain.ts | 28 +- .../src/handlers/actions/editColony.ts | 2 +- .../src/handlers/actions/editDomain.ts | 4 +- .../handlers/actions/emitDomainReputation.ts | 23 +- .../actions/makeArbitraryTransaction.ts | 18 +- .../src/handlers/actions/managePermissions.ts | 39 +- .../src/handlers/actions/mintTokens.ts | 4 +- .../src/handlers/actions/moveFunds.ts | 22 +- .../src/handlers/actions/oneTxPayment.ts | 22 +- .../src/handlers/actions/unlockToken.ts | 2 +- .../src/handlers/colonies/colonyAdded.ts | 13 +- .../handlers/colonies/colonyFundsClaimed.ts | 11 +- .../handlers/colonies/colonyVersionAdded.ts | 5 +- .../colonies/helpers/createUniqueColony.ts | 87 ++--- .../src/handlers/colonies/transfer.ts | 15 +- .../handlers/expenditures/expenditureAdded.ts | 41 +-- .../expenditures/expenditureCancelled.ts | 23 +- .../expenditures/expenditureClaimDelaySet.ts | 23 +- .../expenditures/expenditureFinalized.ts | 24 +- .../expenditureGlobalClaimDelaySet.ts | 20 +- .../expenditures/expenditureLocked.ts | 22 +- .../expenditures/expenditureMadeStaged.ts | 26 +- .../expenditures/expenditureMadeViaStake.ts | 72 ++-- .../expenditures/expenditurePayoutClaimed.ts | 25 +- .../expenditurePayoutModifierSet.ts | 23 +- .../expenditures/expenditurePayoutSet.ts | 9 +- .../expenditures/expenditureRecipientSet.ts | 23 +- .../expenditures/expenditureStakerPunished.ts | 6 +- .../expenditures/expenditureStateChanged.ts | 9 +- .../expenditures/expenditureTransferred.ts | 23 +- .../helpers/createEditExpenditureAction.ts | 26 +- .../helpers/decodeSetExpenditureState.ts | 2 +- .../expenditures/helpers/getExpenditure.ts | 6 +- .../helpers/updateExpenditureStake.ts | 20 +- .../expenditures/paymentTokenUpdated.ts | 10 +- .../expenditures/stagedPaymentReleased.ts | 15 +- .../handlers/expenditures/stakeFractionSet.ts | 2 +- .../handlers/expenditures/stakeReclaimed.ts | 6 +- .../expenditures/streamingPaymentCreated.ts | 9 +- .../extensions/extensionAddedToNetwork.ts | 2 +- .../extensions/extensionDeprecated.ts | 8 +- .../extensions/extensionInitialised.ts | 5 +- .../handlers/extensions/extensionInstalled.ts | 2 +- .../extensions/extensionUninstalled.ts | 2 +- .../handlers/extensions/extensionUpgraded.ts | 9 +- .../handlers/addVerifiedMembers.ts | 8 +- .../metadataDelta/handlers/manageTokens.ts | 2 +- .../handlers/removeVerifiedMembers.ts | 8 +- .../handlers/metadataDelta/metadataDelta.ts | 4 +- .../src/handlers/motions/helpers.ts | 22 +- .../motionCreated/handlers/addDomain.ts | 3 +- .../motionCreated/handlers/editColony.ts | 3 +- .../motionCreated/handlers/editDomain.ts | 3 +- .../cancelExpenditureViaArbitration.ts | 3 +- .../expenditures/cancelStakedExpenditures.ts | 3 +- .../finalizeExpenditureViaArbitration.ts | 3 +- .../releaseStagedPaymentViaArbitration.ts | 3 +- .../handlers/makeArbitraryTransactions.ts | 3 +- .../motionCreated/handlers/metadataDelta.ts | 4 +- .../metadataDeltaHandlers/manageTokens.ts | 2 +- .../motionCreated/handlers/mintTokens.ts | 3 +- .../motionCreated/handlers/moveFunds.ts | 3 +- .../handlers/multicall/multicall.ts | 5 +- .../fundExpenditureMotion.ts | 4 +- .../multicall/multicallHandlers/types.ts | 2 +- .../motionCreated/handlers/networkUpgrade.ts | 3 +- .../motions/motionCreated/handlers/payment.ts | 3 +- .../motionCreated/handlers/reputation.ts | 3 +- .../motionCreated/handlers/setUserRoles.ts | 3 +- .../motionCreated/handlers/simpleDecision.ts | 3 +- .../motionCreated/handlers/unlockToken.ts | 3 +- .../handlers/motions/motionCreated/helpers.ts | 22 +- .../motions/motionCreated/motionCreated.ts | 7 +- .../handlers/motions/motionEventSet/index.ts | 6 +- .../motions/motionFinalized/helpers.ts | 10 +- .../motionFinalized/motionFinalized.ts | 4 +- .../motions/motionRewardClaimed/helpers.ts | 53 +-- .../motionRewardClaimed.ts | 4 +- .../handlers/motions/motionStaked/helpers.ts | 48 +-- .../motions/motionStaked/motionStaked.ts | 7 +- .../motions/motionVoteRevealed/helpers.ts | 26 +- .../motions/motionVoteRevealed/index.ts | 7 +- .../motions/motionVoteSubmitted/index.ts | 6 +- .../approvalChanged/approvalChanged.ts | 7 +- .../multiSig/domainSkillThresholdSet.ts | 8 +- .../handlers/multiSig/globalThresholdSet.ts | 6 +- .../src/handlers/multiSig/helpers.ts | 52 +-- .../handlers/multiSig/multiSigCancelled.ts | 13 +- .../handlers/addOrEditDomain.ts | 3 +- .../handlers/colonyVersionUpgrade.ts | 3 +- .../multiSigCreated/handlers/editColony.ts | 3 +- .../handlers/manageReputation.ts | 3 +- .../multiSigCreated/handlers/metadataDelta.ts | 4 +- .../metadataDeltaHandlers/manageTokens.ts | 2 +- .../multiSigCreated/handlers/mintTokens.ts | 3 +- .../multiSigCreated/handlers/moveFunds.ts | 3 +- .../multiSigCreated/handlers/payment.ts | 3 +- .../multiSigCreated/handlers/setUserRoles.ts | 3 +- .../multiSigCreated/handlers/unlockToken.ts | 3 +- .../multiSig/multiSigCreated/helpers.ts | 15 +- .../multiSigCreated/multiSigCreated.ts | 6 +- .../multiSigExecuted/multiSigExecuted.ts | 11 +- .../rejectionChanged/rejectionChanged.ts | 7 +- .../handlers/network/networkFeeInverseSet.ts | 8 +- .../proxyColonies/proxyColonyRequested.ts | 2 +- .../reputationMiningCycleComplete.ts | 10 +- .../src/handlers/tokens/setTokenAuthority.ts | 2 +- apps/main-chain/src/index.ts | 15 +- apps/main-chain/src/interfaces.ts | 98 ----- apps/main-chain/src/networkClient.ts | 17 +- apps/main-chain/src/provider.ts | 23 +- apps/main-chain/src/stats.ts | 19 +- apps/main-chain/src/statsManager.ts | 7 + apps/main-chain/src/types/actions.ts | 2 +- apps/main-chain/src/types/index.ts | 1 - apps/main-chain/src/utils/actionExists.ts | 4 +- .../main-chain/src/utils/actions/getAction.ts | 6 +- .../src/utils/actions/writeAction.ts | 53 +-- apps/main-chain/src/utils/clients/index.ts | 15 +- apps/main-chain/src/utils/colony.ts | 4 +- apps/main-chain/src/utils/colonyClient.ts | 13 +- apps/main-chain/src/utils/colonyMetadata.ts | 34 +- apps/main-chain/src/utils/contributors.ts | 27 +- apps/main-chain/src/utils/currentVersion.ts | 8 +- apps/main-chain/src/utils/decisions.ts | 6 +- apps/main-chain/src/utils/events.ts | 31 +- apps/main-chain/src/utils/expenditures.ts | 6 +- .../utils/extensions/getColonyExtensions.ts | 4 +- .../src/utils/extensions/installationCount.ts | 14 +- .../utils/extensions/isAddressExtension.ts | 4 +- .../src/utils/extensions/multiSig.ts | 4 +- .../src/utils/extensions/updateExtension.ts | 4 +- .../src/utils/extensions/writeExtension.ts | 23 +- apps/main-chain/src/utils/fundsClaims.ts | 10 +- apps/main-chain/src/utils/graphql.ts | 10 +- apps/main-chain/src/utils/index.ts | 2 - .../src/utils/metadataDelta/utils.ts | 2 +- apps/main-chain/src/utils/networkFee.ts | 4 +- apps/main-chain/src/utils/notifications.ts | 6 +- apps/main-chain/src/utils/permissions.ts | 168 ++++----- apps/main-chain/src/utils/seedDB.ts | 4 +- apps/main-chain/src/utils/stats.ts | 103 ------ apps/main-chain/src/utils/tokens.ts | 36 +- .../src/utils/transactionHasEvent.ts | 9 +- apps/proxy-chain/.env.example | 4 + apps/proxy-chain/package.json | 18 + apps/proxy-chain/src/amplifyClient.ts | 8 + apps/proxy-chain/src/blockManager.ts | 8 + apps/proxy-chain/src/env.ts | 6 + apps/proxy-chain/src/eventListeners/colony.ts | 12 + apps/proxy-chain/src/eventListeners/index.ts | 3 + .../proxy-chain/src/eventListeners/network.ts | 16 + .../src/eventListeners/proxyColonies.ts | 16 + apps/proxy-chain/src/eventManager.ts | 6 + .../src/handlers/proxyColonies/index.ts | 1 + .../proxyColonies/proxyColonyDeployed.ts | 35 ++ apps/proxy-chain/src/index.ts | 34 ++ apps/proxy-chain/src/networkClient.ts | 11 + apps/proxy-chain/src/provider.ts | 4 + apps/proxy-chain/src/stats.ts | 55 +++ apps/proxy-chain/src/statsManager.ts | 7 + apps/proxy-chain/tsconfig.json | 11 + package.json | 6 +- packages/blocks/package.json | 10 + packages/blocks/src/blocks/blockManager.ts | 344 ++++++++++++++++++ packages/blocks/src/blocks/index.ts | 2 + packages/blocks/src/blocks/types.ts | 6 + packages/blocks/src/events/eventManager.ts | 158 ++++++++ packages/blocks/src/events/index.ts | 2 + .../blocks/src/events/types.ts | 83 +++-- packages/blocks/src/index.ts | 3 + packages/blocks/src/stats/index.ts | 2 + packages/blocks/src/stats/statsManager.ts | 123 +++++++ packages/blocks/src/stats/types.ts | 3 + packages/blocks/tsconfig.json | 5 + packages/clients/package.json | 8 + packages/clients/src/amplifyClient.ts | 59 +++ packages/clients/src/index.ts | 4 + packages/clients/src/networkClient.ts | 23 ++ packages/clients/src/rpcProvider.ts | 38 ++ packages/clients/src/types.ts | 1 + packages/clients/tsconfig.json | 5 + packages/graphql/src/generated.ts | 50 ++- packages/graphql/src/mutations/stats.graphql | 8 +- packages/graphql/src/queries/stats.graphql | 9 +- packages/utils/package.json | 6 + packages/utils/src/index.ts | 1 + .../utils => packages/utils/src}/logger.ts | 0 packages/utils/tsconfig.json | 5 + pnpm-lock.yaml | 44 +++ 217 files changed, 2319 insertions(+), 1701 deletions(-) delete mode 100644 apps/main-chain/Dockerfile delete mode 100644 apps/main-chain/src/blockListener.ts create mode 100644 apps/main-chain/src/blockManager.ts delete mode 100644 apps/main-chain/src/blockProcessor.ts delete mode 100644 apps/main-chain/src/eventListeners/eventListeners.ts delete mode 100644 apps/main-chain/src/eventListeners/types.ts create mode 100644 apps/main-chain/src/eventManager.ts delete mode 100644 apps/main-chain/src/interfaces.ts create mode 100644 apps/main-chain/src/statsManager.ts delete mode 100644 apps/main-chain/src/utils/stats.ts create mode 100644 apps/proxy-chain/.env.example create mode 100644 apps/proxy-chain/package.json create mode 100644 apps/proxy-chain/src/amplifyClient.ts create mode 100644 apps/proxy-chain/src/blockManager.ts create mode 100644 apps/proxy-chain/src/env.ts create mode 100644 apps/proxy-chain/src/eventListeners/colony.ts create mode 100644 apps/proxy-chain/src/eventListeners/index.ts create mode 100644 apps/proxy-chain/src/eventListeners/network.ts create mode 100644 apps/proxy-chain/src/eventListeners/proxyColonies.ts create mode 100644 apps/proxy-chain/src/eventManager.ts create mode 100644 apps/proxy-chain/src/handlers/proxyColonies/index.ts create mode 100644 apps/proxy-chain/src/handlers/proxyColonies/proxyColonyDeployed.ts create mode 100644 apps/proxy-chain/src/index.ts create mode 100644 apps/proxy-chain/src/networkClient.ts create mode 100644 apps/proxy-chain/src/provider.ts create mode 100644 apps/proxy-chain/src/stats.ts create mode 100644 apps/proxy-chain/src/statsManager.ts create mode 100644 apps/proxy-chain/tsconfig.json create mode 100644 packages/blocks/package.json create mode 100644 packages/blocks/src/blocks/blockManager.ts create mode 100644 packages/blocks/src/blocks/index.ts create mode 100644 packages/blocks/src/blocks/types.ts create mode 100644 packages/blocks/src/events/eventManager.ts create mode 100644 packages/blocks/src/events/index.ts rename apps/main-chain/src/types/events.ts => packages/blocks/src/events/types.ts (77%) create mode 100644 packages/blocks/src/index.ts create mode 100644 packages/blocks/src/stats/index.ts create mode 100644 packages/blocks/src/stats/statsManager.ts create mode 100644 packages/blocks/src/stats/types.ts create mode 100644 packages/blocks/tsconfig.json create mode 100644 packages/clients/package.json create mode 100644 packages/clients/src/amplifyClient.ts create mode 100644 packages/clients/src/index.ts create mode 100644 packages/clients/src/networkClient.ts create mode 100644 packages/clients/src/rpcProvider.ts create mode 100644 packages/clients/src/types.ts create mode 100644 packages/clients/tsconfig.json create mode 100644 packages/utils/package.json create mode 100644 packages/utils/src/index.ts rename {apps/main-chain/src/utils => packages/utils/src}/logger.ts (100%) create mode 100644 packages/utils/tsconfig.json diff --git a/.eslintrc.js b/.eslintrc.js index f34eb3ee9..bc3217360 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -8,13 +8,19 @@ module.exports = { parserOptions: { ecmaVersion: 'latest', sourceType: 'module', - project: ['./tsconfig.json'], + project: [ + './tsconfig.base.json', + './packages/*/tsconfig.json', + './apps/*/tsconfig.json' + ], + tsconfigRootDir: __dirname, }, rules: { semi: 'off', '@typescript-eslint/semi': ['error', 'always'], '@typescript-eslint/strict-boolean-expressions': 'off', '@typescript-eslint/restrict-template-expressions': 'off', + '@typescript-eslint/consistent-type-definitions': 'off', 'comma-dangle': 'off', '@typescript-eslint/comma-dangle': ['error', 'always-multiline'], '@typescript-eslint/no-misused-promises': 'off', @@ -25,6 +31,10 @@ module.exports = { 'no-useless-return': 'off', '@typescript-eslint/member-delimiter-style': 'off', '@typescript-eslint/indent': 'off', + '@typescript-eslint/array-type': 'off', + '@typescript-eslint/prefer-nullish-coalescing': 'off', + '@typescript-eslint/prefer-optional-chain': 'off', + '@typescript-eslint/return-await': 'off', '@typescript-eslint/space-before-function-paren': [ 'error', { @@ -34,5 +44,5 @@ module.exports = { }, ], }, - ignorePatterns: ['codegen.ts', 'src/graphql/generated.ts'], + ignorePatterns: ['packages/graphql/codegen.ts', 'packages/graphql/src/generated.ts'], }; diff --git a/.gitignore b/.gitignore index be62f4f73..675713ff1 100644 --- a/.gitignore +++ b/.gitignore @@ -70,6 +70,7 @@ typings/ # dotenv environment variables file .env +.env.proxy-2 .env.test # parcel-bundler cache (https://parceljs.org/) @@ -102,5 +103,3 @@ dist # TernJS port file .tern-port - -stats diff --git a/Dockerfile b/Dockerfile index 145780faa..e418b30ad 100644 --- a/Dockerfile +++ b/Dockerfile @@ -18,3 +18,10 @@ COPY --from=build /workspace /workspace WORKDIR /workspace/apps/main-chain CMD ["pnpm", "--filter", "@joincolony/main-chain", "prod"] +# Proxy Chain Stage +FROM base AS proxy-chain +WORKDIR /workspace +COPY --from=build /workspace /workspace +WORKDIR /workspace/apps/proxy-chain +CMD ["pnpm", "--filter", "@joincolony/proxy-chain", "prod"] + diff --git a/apps/main-chain/.env.example b/apps/main-chain/.env.example index fb3a3a641..1fa25f817 100644 --- a/apps/main-chain/.env.example +++ b/apps/main-chain/.env.example @@ -1,2 +1,3 @@ CHAIN_RPC_ENDPOINT=http://localhost:8545 CHAIN_NETWORK_CONTRACT=0x777760996135F0791E2e1a74aFAa060711197777 +STATS_PORT=10001 diff --git a/apps/main-chain/Dockerfile b/apps/main-chain/Dockerfile deleted file mode 100644 index 02707856c..000000000 --- a/apps/main-chain/Dockerfile +++ /dev/null @@ -1,22 +0,0 @@ -FROM node:20-slim -ENV PNPM_HOME="/pnpm" -ENV PATH="$PNPM_HOME:$PATH" -RUN corepack enable - -# Set the working directory to the monorepo root -WORKDIR /workspace - -# Copy necessary files -COPY pnpm-lock.yaml pnpm-workspace.yaml package.json tsconfig.base.json .npmrc ./ -COPY scripts ./scripts -COPY .env.example ./.env.example -COPY .env ./.env -COPY apps/main-chain ./apps/main-chain -COPY apps/main-chain/.env ./apps/main-chain/.env -COPY packages/graphql ./packages/graphql - -# Install dependencies and filter for scoped package -RUN pnpm install --frozen-lockfile - -# the command that starts our app -CMD ["pnpm", "--filter", "@joincolony/main-chain", "dev"] diff --git a/apps/main-chain/package.json b/apps/main-chain/package.json index 9fba3a862..bc1d9b94e 100644 --- a/apps/main-chain/package.json +++ b/apps/main-chain/package.json @@ -1,16 +1,18 @@ { - "name": "@joincolony/main-chain", - "version": "1.0.0", - "main": "src/index.ts", - "scripts": { - "build": "rm -rf dist/* && npx tsc", - "start": "node -r ts-node/register/transpile-only -r tsconfig-paths/register -r ./src/env.ts dist/index.js", - "dev": "NODE_ENV=development ts-node-dev -r tsconfig-paths/register -r ./src/env.ts src/index.ts", - "prod": "pnpm run build && NODE_ENV=production pnpm run start", - "typecheck": "tsc --noEmit" - }, - "dependencies": { - "@joincolony/graphql": "workspace:*" - } + "name": "@joincolony/main-chain", + "version": "1.0.0", + "main": "src/index.ts", + "scripts": { + "build": "rm -rf dist/* && npx tsc", + "start": "node -r ts-node/register/transpile-only -r tsconfig-paths/register -r ./dist/env.js dist/index.js", + "dev": "NODE_ENV=development ts-node-dev -r tsconfig-paths/register -r ./src/env.ts src/index.ts", + "prod": "pnpm run build && NODE_ENV=production pnpm run start", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@joincolony/graphql": "workspace:*", + "@joincolony/clients": "workspace:*", + "@joincolony/blocks": "workspace:*", + "@joincolony/utils": "workspace:*" } - \ No newline at end of file +} \ No newline at end of file diff --git a/apps/main-chain/src/amplifyClient.ts b/apps/main-chain/src/amplifyClient.ts index c65a551e3..381535806 100644 --- a/apps/main-chain/src/amplifyClient.ts +++ b/apps/main-chain/src/amplifyClient.ts @@ -1,61 +1,8 @@ -import { Amplify, API, graphqlOperation } from 'aws-amplify'; -import { GraphQLQuery } from '@aws-amplify/api'; -import { DocumentNode, isExecutableDefinitionNode } from 'graphql'; -import { verbose } from '~utils'; +import { AmplifyClient } from '@joincolony/clients'; -export default (): void => { - Amplify.configure({ - aws_appsync_graphqlEndpoint: `${process.env.AWS_APPSYNC_ENDPOINT}`, - aws_appsync_authenticationType: 'API_KEY', - aws_appsync_apiKey: process.env.AWS_APPSYNC_KEY, - }); -}; +const amplifyClient = new AmplifyClient( + process.env.AWS_APPSYNC_ENDPOINT || '', + process.env.AWS_APPSYNC_KEY || '', +); -export type GraphQLFnReturn = Promise< - ReturnType>> | undefined ->; - -export const query = async >( - queryDocument: DocumentNode, - variables?: TVariables, -): GraphQLFnReturn => { - try { - const result = await API.graphql>( - graphqlOperation(queryDocument, variables), - ); - - return result; - } catch (error) { - const definitionNode = queryDocument.definitions[0]; - const queryName = isExecutableDefinitionNode(definitionNode) - ? definitionNode.name?.value - : 'Unknown'; - console.error(`Could not fetch query ${queryName}`, error); - return undefined; - } -}; - -export const mutate = async < - T, - TVariables extends Record = {}, ->( - mutationDocument: DocumentNode, - variables?: TVariables, -): GraphQLFnReturn => { - try { - const result = await API.graphql>( - graphqlOperation(mutationDocument, variables), - ); - - return result; - } catch (error: any) { - const definitionNode = mutationDocument.definitions[0]; - const mutationName = isExecutableDefinitionNode(definitionNode) - ? definitionNode.name?.value - : 'Unknown'; - - const errMsg = 'errors' in error ? error.errors : error; - verbose(`Could not execute mutation ${mutationName}. Error: `, errMsg); - return undefined; - } -}; +export default amplifyClient; diff --git a/apps/main-chain/src/blockListener.ts b/apps/main-chain/src/blockListener.ts deleted file mode 100644 index a3a2cd8ad..000000000 --- a/apps/main-chain/src/blockListener.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { output, getLastBlockNumber } from '~utils'; -import { Block, BlockWithTransactions, EthersObserverEvents } from '~types'; -import provider from '~provider'; -import { processNextBlock } from '~blockProcessor'; - -/** - * Map storing blocks that have been either picked up by the block listener - * or missed blocks tracking - * Blocks are removed once processed by a call to .delete in the blockProcessor - */ -export const blocksMap = new Map(); -let latestSeenBlockNumber = 0; - -export const getLatestSeenBlockNumber = (): number => latestSeenBlockNumber; -// export const blocksMap = new Map(); - -export const startBlockListener = (): void => { - provider.on(EthersObserverEvents.Block, async (blockNumber: number) => { - try { - // For now, we just track that this block exists. - latestSeenBlockNumber = Math.max(latestSeenBlockNumber, blockNumber); - - output(`Block ${blockNumber} added to the queue`); - - processNextBlock(); - } catch (error) { - throw new Error( - `Observed block ${blockNumber} but failed to get its data: ${error}`, - ); - } - }); - - output('Block listener started'); - - trackMissedBlocks(); -}; - -/** - * Function fetching all the blocks between the last processed block and the current block - * that happened when ingestor was not actively listening - */ -const trackMissedBlocks = async (): Promise => { - const lastBlockNumber = getLastBlockNumber(); - const currentBlockNumber = await provider.getBlockNumber(); - - if (lastBlockNumber >= currentBlockNumber) { - return; - } - - output( - `Will need to process blocks from block ${ - lastBlockNumber + 1 - } to ${currentBlockNumber}`, - ); - - latestSeenBlockNumber = Math.max(latestSeenBlockNumber, currentBlockNumber); - - processNextBlock(); -}; diff --git a/apps/main-chain/src/blockManager.ts b/apps/main-chain/src/blockManager.ts new file mode 100644 index 000000000..bbaac0e00 --- /dev/null +++ b/apps/main-chain/src/blockManager.ts @@ -0,0 +1,8 @@ +import { BlockManager } from '@joincolony/blocks'; +import eventManager from '~eventManager'; +import rpcProvider from '~provider'; +import statsManager from '~statsManager'; + +const blockManager = new BlockManager(eventManager, rpcProvider, statsManager); + +export default blockManager; diff --git a/apps/main-chain/src/blockProcessor.ts b/apps/main-chain/src/blockProcessor.ts deleted file mode 100644 index 13fe6d73b..000000000 --- a/apps/main-chain/src/blockProcessor.ts +++ /dev/null @@ -1,218 +0,0 @@ -import { Log } from '@ethersproject/abstract-provider'; -import { blocksMap, getLatestSeenBlockNumber } from '~blockListener'; -import { getMatchingListeners } from '~eventListeners'; -import { getInterfaceByListener } from '~interfaces'; -import provider from '~provider'; -import { - getLastBlockNumber, - mapLogToContractEvent, - output, - verbose, - setLastBlockNumber, -} from '~utils'; -import { BLOCK_PAGING_SIZE } from '~constants'; - -let isProcessing = false; -const blockLogs = new Map(); -let timeNow = Date.now(); -let timePrev = 0; - -export const processNextBlock = async (): Promise => { - if (isProcessing) { - return; - } - - // Only allow one instance of the function to run at any given time - isProcessing = true; - - let lastBlockNumber = getLastBlockNumber(); - - // Process as many blocks as are available sequentially - while (lastBlockNumber < getLatestSeenBlockNumber()) { - const currentBlockNumber = lastBlockNumber + 1; - if (currentBlockNumber % BLOCK_PAGING_SIZE === 0) { - if (timePrev > 0) { - timePrev = timeNow; - timeNow = Date.now(); - output( - `Time taken for last ${BLOCK_PAGING_SIZE} blocks: ${ - timeNow - timePrev - }ms`, - ); - output( - `Estimated time to sync: ${ - ((timeNow - timePrev) * - (getLatestSeenBlockNumber() - getLastBlockNumber())) / - 1000 - }ms`, - ); - output( - `Overall progress: ${currentBlockNumber} / ${getLatestSeenBlockNumber()}`, - ); - } else { - timePrev = timeNow; - } - } - - if (!blockLogs.get(currentBlockNumber)) { - // BLOCK_PAGING_SIZE - 1 thanks to fenceposts - const nMoreBlocks = Math.min( - getLatestSeenBlockNumber() - currentBlockNumber, - BLOCK_PAGING_SIZE - 1, - ); - - verbose( - 'Querying for logs', - currentBlockNumber, - 'to', - currentBlockNumber + nMoreBlocks, - ); - - const logs = await provider.getLogs({ - fromBlock: currentBlockNumber, - toBlock: currentBlockNumber + nMoreBlocks, - }); - - verbose( - `Fetched ${logs.length} logs`, - currentBlockNumber, - 'to', - currentBlockNumber + nMoreBlocks, - ); - - // initialize blockLogs - for ( - let i = currentBlockNumber; - i <= currentBlockNumber + nMoreBlocks; - i += 1 - ) { - blockLogs.set(i, []); - } - - let logIndex = 0; - let pushingBlock = 0; - let pushingLogs: Log[] = []; - - logs.forEach((log) => { - // As we push logs in to blockLogs, check they're in order - // (They should be...) - if (log.blockNumber !== pushingBlock) { - if (pushingBlock > log.blockNumber) { - output( - `Blocks (that logs from query are in) are not monotonically increasing`, - ); - process.exit(1); - } - blockLogs.set(pushingBlock, [...pushingLogs]); - pushingBlock = log.blockNumber; - pushingLogs = []; - logIndex = 0; - } - if (log.logIndex !== logIndex) { - output(`Logs are out of order for block ${log.blockNumber}`); - process.exit(1); - } - pushingLogs.push(log); - logIndex += 1; - }); - // Push the logs in the last block - blockLogs.set(pushingBlock, [...pushingLogs]); - } - - // Get logs contained in the current block - const logs = blockLogs.get(currentBlockNumber); - if (!logs) { - throw new Error( - `Could not find logs for block ${currentBlockNumber}, but should have been fetched`, - ); - } - - /* - * Logic needed to account for blocks that get emmited, but which don't have the logs indexed yet - * This happens in networks with very fast block times, like arbitrum (<=250ms block times) - * See: https://github.com/ethers-io/ethers.js/issues/3486 - * - * Basically, the change that @area implemented here is to try and detect if a block actually has - * logs, but which don't get retrived using the `getLogs` call. - * If that happens, it means the block was emitted, but the logs weren't indexed yet, at which point - * we just short-circuit and re-process the block. - * We do this enough times, until the logs are actually indexed. - */ - if (logs.length === 0) { - verbose('No logs seen in block', currentBlockNumber); - // Check whether block actually has no logs - let block = blocksMap.get(currentBlockNumber); - if ( - !block || - (block.transactions as string[]).every((tx) => typeof tx === 'string') - ) { - block = await provider.getBlockWithTransactions(currentBlockNumber); - // May as well save this block in the blocksMap in case it turns out we need it in mapLogToContractEvent - blocksMap.set(currentBlockNumber, block); - } - - let mustReindex = false; - for (const tx of block.transactions) { - if (typeof tx === 'string') { - throw Error('tx was a string, but should have been a TxResponse'); - } - const txReceipt = await provider.getTransactionReceipt(tx.hash); - if (txReceipt.logs.length > 0) { - verbose( - `Proved ${currentBlockNumber} has logs, but weren't given any, will reindex`, - ); - mustReindex = true; - // Then the block has events, and they've not been indexed yet. - // We exit out of this handler, and wait until they've been indexed. - // We remove the empty array from blockLogs to cause the getLogs call to be made again - blockLogs.delete(currentBlockNumber); - // Now we've proved we're missing events, don't need to look at any other transactions in - // this block. - break; - } - } - if (mustReindex) { - continue; - } - } - - for (const log of logs) { - // Find listeners that match the log - const listeners = getMatchingListeners(log.topics, log.address); - if (!listeners.length) { - continue; - } - - for (const listener of listeners) { - // In order to parse the log, we need an ethers interface - const iface = getInterfaceByListener(listener); - if (!iface) { - output( - `Failed to get an interface for a log with listener type ${listener.type}`, - ); - continue; - } - - const event = await mapLogToContractEvent(log, iface); - if (!event) { - output( - `Failed to map log describing event ${listener.eventSignature} in transaction ${log.transactionHash} `, - ); - continue; - } - - // Call the handler in a blocking way to ensure events get processed sequentially - await listener.handler(event, listener); - } - } - - verbose('processed block', currentBlockNumber); - - lastBlockNumber = currentBlockNumber; - setLastBlockNumber(currentBlockNumber); - blockLogs.delete(currentBlockNumber); - blocksMap.delete(currentBlockNumber); - } - - isProcessing = false; -}; diff --git a/apps/main-chain/src/eventListeners/colony.ts b/apps/main-chain/src/eventListeners/colony.ts index 06b3813d4..d44a59b7e 100644 --- a/apps/main-chain/src/eventListeners/colony.ts +++ b/apps/main-chain/src/eventListeners/colony.ts @@ -1,20 +1,22 @@ import { utils } from 'ethers'; -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ListColoniesDocument, ListColoniesQuery, ListColoniesQueryVariables, } from '@joincolony/graphql'; -import { ContractEventsSignatures, EventHandler } from '~types'; -import { notNull, output } from '~utils'; import { - addEventListener, + ContractEventsSignatures, + EventHandler, + EventListenerType, +} from '@joincolony/blocks'; +import { notNull } from '~utils'; +import { addNetworkEventListener, addTokenEventListener, } from '~eventListeners'; -import { EventListenerType } from './types'; import { handleAnnotateTransaction, handleColonyAdded, @@ -50,13 +52,15 @@ import { import { handleProxyColonyRequested } from '~handlers/proxyColonies'; import setTokenAuthority from '~handlers/tokens/setTokenAuthority'; import { addProxyColoniesEventListener } from './proxyColonies'; +import { output } from '@joincolony/utils'; +import eventManager from '~eventManager'; const addColonyEventListener = ( eventSignature: ContractEventsSignatures, address: string, handler: EventHandler, ): void => { - addEventListener({ + eventManager.addEventListener({ type: EventListenerType.Colony, address, eventSignature, @@ -76,7 +80,7 @@ const fetchColoniesAddresses = async (): Promise< do { const { data } = - (await query( + (await amplifyClient.query( ListColoniesDocument, { nextToken }, )) ?? {}; diff --git a/apps/main-chain/src/eventListeners/eventListeners.ts b/apps/main-chain/src/eventListeners/eventListeners.ts deleted file mode 100644 index 807b9cbc5..000000000 --- a/apps/main-chain/src/eventListeners/eventListeners.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { verbose } from '~utils'; - -import { EventListener } from './types'; - -let listeners: EventListener[] = []; - -export const getEventListeners = (): EventListener[] => listeners; - -export const setEventListeners = (newListeners: EventListener[]): void => { - listeners = newListeners; -}; - -export const addEventListener = (listener: EventListener): void => { - verbose( - `Added listener for event ${listener.eventSignature}`, - listener.address ? `filtering address ${listener.address}` : '', - ); - listeners.push(listener); -}; - -export const getMatchingListeners = ( - logTopics: string[], - logAddress: string, -): EventListener[] => { - return listeners.filter((listener) => { - if (listener.address && logAddress !== listener.address) { - return false; - } - - if (listener.topics.length > logTopics.length) { - return false; - } - - return listener.topics.every((topic, index) => { - if (topic === null) { - // if listener topic is null, skip the check - return true; - } - - return topic.toLowerCase() === logTopics[index].toLowerCase(); - }); - }); -}; - -export const getListenersStats = (): string => JSON.stringify(listeners); diff --git a/apps/main-chain/src/eventListeners/extension/index.ts b/apps/main-chain/src/eventListeners/extension/index.ts index 866e92ecd..69d02ee2f 100644 --- a/apps/main-chain/src/eventListeners/extension/index.ts +++ b/apps/main-chain/src/eventListeners/extension/index.ts @@ -1,22 +1,23 @@ import { utils } from 'ethers'; import { Extension, getExtensionHash } from '@colony/colony-js'; -import { ContractEventsSignatures, EventHandler } from '~types'; import { + ContractEventsSignatures, + EventHandler, EventListenerType, - addEventListener, - getEventListeners, - setEventListeners, +} from '@joincolony/blocks'; +import { setupListenerForOneTxPaymentExtensions, setupListenersForStagedExpenditureExtensions, } from '~eventListeners'; +import eventManager from '~eventManager'; import { ExtensionFragment, ListExtensionsDocument, ListExtensionsQuery, ListExtensionsQueryVariables, } from '@joincolony/graphql'; -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { notNull } from '~utils'; import { addNetworkEventListener } from '../network'; @@ -44,7 +45,7 @@ export const addExtensionEventListener = ( colonyAddress: string, handler: EventHandler, ): void => { - addEventListener({ + eventManager.addEventListener({ type: EventListenerType.Extension, eventSignature, address: extensionAddress, @@ -58,8 +59,8 @@ export const addExtensionEventListener = ( export const removeExtensionEventListeners = ( extensionAddress: string, ): void => { - const existingListeners = getEventListeners(); - setEventListeners( + const existingListeners = eventManager.getEventListeners(); + eventManager.setEventListeners( existingListeners.filter((listener) => { if (listener.type !== EventListenerType.Extension) { return true; @@ -103,13 +104,13 @@ export const fetchExistingExtensions = async ( do { const { data } = - (await query( - ListExtensionsDocument, - { - nextToken, - hash: extensionHash, - }, - )) ?? {}; + (await amplifyClient.query< + ListExtensionsQuery, + ListExtensionsQueryVariables + >(ListExtensionsDocument, { + nextToken, + hash: extensionHash, + })) ?? {}; const { items } = data?.getExtensionsByHash ?? {}; extensions.push(...(items ?? [])); diff --git a/apps/main-chain/src/eventListeners/extension/multiSig.ts b/apps/main-chain/src/eventListeners/extension/multiSig.ts index 649262955..859dd14e6 100644 --- a/apps/main-chain/src/eventListeners/extension/multiSig.ts +++ b/apps/main-chain/src/eventListeners/extension/multiSig.ts @@ -9,7 +9,7 @@ import { handleMultiSigMotionCreated, handleMultiSigMotionExecuted, } from '~handlers/multiSig'; -import { mutate, query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { GetActiveColonyMultisigsDocument, GetActiveColonyMultisigsQuery, @@ -22,10 +22,10 @@ import { RemoveMultiSigRoleMutationVariables, } from '@joincolony/graphql'; -import { ContractEventsSignatures } from '~types'; +import { ContractEventsSignatures } from '@joincolony/blocks'; import { notNull } from '~utils'; import { addMultiSigParamsToDB } from '~utils/extensions/multiSig'; -import { output } from '~utils/logger'; +import { output } from '@joincolony/utils'; import { addExtensionEventListener, fetchExistingExtensions } from './index'; import { updateMultiSigInDB } from '~handlers/multiSig/helpers'; @@ -51,7 +51,7 @@ export const handleMultiSigInstalled = async ( export const handleMultiSigUninstalled = async ( colonyAddress: string, ): Promise => { - const multiSigRolesQuery = await query< + const multiSigRolesQuery = await amplifyClient.query< GetAllMultiSigRolesQuery, GetAllMultiSigRolesQueryVariables >(GetAllMultiSigRolesDocument, { @@ -62,7 +62,7 @@ export const handleMultiSigUninstalled = async ( await Promise.all( roleEntries.filter(notNull).map(async (entry) => { - await mutate< + await amplifyClient.mutate< RemoveMultiSigRoleMutation, RemoveMultiSigRoleMutationVariables >(RemoveMultiSigRoleDocument, { @@ -71,7 +71,7 @@ export const handleMultiSigUninstalled = async ( }), ); - const activeMultiSigsQuery = await query< + const activeMultiSigsQuery = await amplifyClient.query< GetActiveColonyMultisigsQuery, GetActiveColonyMultisigsQueryVariables >(GetActiveColonyMultisigsDocument, { diff --git a/apps/main-chain/src/eventListeners/extension/oneTxPayment.ts b/apps/main-chain/src/eventListeners/extension/oneTxPayment.ts index edc93cb32..c1404904a 100644 --- a/apps/main-chain/src/eventListeners/extension/oneTxPayment.ts +++ b/apps/main-chain/src/eventListeners/extension/oneTxPayment.ts @@ -1,6 +1,6 @@ import { Extension, getExtensionHash } from '@colony/colony-js'; -import { output } from '~utils'; -import { ContractEventsSignatures } from '~types'; +import { output } from '@joincolony/utils'; +import { ContractEventsSignatures } from '@joincolony/blocks'; import { addExtensionEventListener, fetchExistingExtensions } from '.'; import { handleOneTxPaymentAction } from '~handlers'; diff --git a/apps/main-chain/src/eventListeners/extension/stagedExpenditure.ts b/apps/main-chain/src/eventListeners/extension/stagedExpenditure.ts index 36b5662ed..aac9edcf4 100644 --- a/apps/main-chain/src/eventListeners/extension/stagedExpenditure.ts +++ b/apps/main-chain/src/eventListeners/extension/stagedExpenditure.ts @@ -4,8 +4,8 @@ import { handleStagedPaymentReleased, } from '~handlers'; -import { ContractEventsSignatures } from '~types'; -import { output } from '~utils'; +import { ContractEventsSignatures } from '@joincolony/blocks'; +import { output } from '@joincolony/utils'; import { addExtensionEventListener, fetchExistingExtensions } from './index'; diff --git a/apps/main-chain/src/eventListeners/extension/stakedExpenditure.ts b/apps/main-chain/src/eventListeners/extension/stakedExpenditure.ts index d41cf7cd5..b6e940ddc 100644 --- a/apps/main-chain/src/eventListeners/extension/stakedExpenditure.ts +++ b/apps/main-chain/src/eventListeners/extension/stakedExpenditure.ts @@ -8,8 +8,8 @@ import { handleStakeReclaimed, } from '~handlers'; -import { ContractEventsSignatures } from '~types'; -import { output } from '~utils'; +import { ContractEventsSignatures } from '@joincolony/blocks'; +import { output } from '@joincolony/utils'; import { addExtensionEventListener, fetchExistingExtensions } from './index'; diff --git a/apps/main-chain/src/eventListeners/extension/streamingPayments.ts b/apps/main-chain/src/eventListeners/extension/streamingPayments.ts index 4edf0d01d..b444f5136 100644 --- a/apps/main-chain/src/eventListeners/extension/streamingPayments.ts +++ b/apps/main-chain/src/eventListeners/extension/streamingPayments.ts @@ -4,8 +4,8 @@ import { handleStreamingPaymentCreated, } from '~handlers'; -import { ContractEventsSignatures } from '~types'; -import { output } from '~utils'; +import { ContractEventsSignatures } from '@joincolony/blocks'; +import { output } from '@joincolony/utils'; import { addExtensionEventListener, fetchExistingExtensions } from './index'; diff --git a/apps/main-chain/src/eventListeners/extension/votingReputation.ts b/apps/main-chain/src/eventListeners/extension/votingReputation.ts index b8da73034..9be131571 100644 --- a/apps/main-chain/src/eventListeners/extension/votingReputation.ts +++ b/apps/main-chain/src/eventListeners/extension/votingReputation.ts @@ -10,8 +10,8 @@ import { handleMotionVoteSubmitted, } from '~handlers'; -import { ContractEventsSignatures } from '~types'; -import { output } from '~utils'; +import { ContractEventsSignatures } from '@joincolony/blocks'; +import { output } from '@joincolony/utils'; import { addExtensionEventListener, fetchExistingExtensions } from './index'; diff --git a/apps/main-chain/src/eventListeners/index.ts b/apps/main-chain/src/eventListeners/index.ts index a4d169dec..57148d63e 100644 --- a/apps/main-chain/src/eventListeners/index.ts +++ b/apps/main-chain/src/eventListeners/index.ts @@ -1,5 +1,3 @@ -export * from './eventListeners'; -export * from './types'; export * from './colony'; export * from './network'; export * from './extension'; diff --git a/apps/main-chain/src/eventListeners/network.ts b/apps/main-chain/src/eventListeners/network.ts index a515f04f9..7ec858f07 100644 --- a/apps/main-chain/src/eventListeners/network.ts +++ b/apps/main-chain/src/eventListeners/network.ts @@ -1,13 +1,13 @@ +import { EventListenerType , ContractEventsSignatures, EventHandler } from '@joincolony/blocks'; import { utils } from 'ethers'; -import { EventListenerType, addEventListener } from '~eventListeners'; -import { ContractEventsSignatures, EventHandler } from '~types'; +import eventManager from '~eventManager'; export const addNetworkEventListener = ( eventSignature: ContractEventsSignatures, handler: EventHandler, ): void => - addEventListener({ + eventManager.addEventListener({ type: EventListenerType.Network, eventSignature, topics: [utils.id(eventSignature)], diff --git a/apps/main-chain/src/eventListeners/proxyColonies.ts b/apps/main-chain/src/eventListeners/proxyColonies.ts index 29158c665..73ea92e5c 100644 --- a/apps/main-chain/src/eventListeners/proxyColonies.ts +++ b/apps/main-chain/src/eventListeners/proxyColonies.ts @@ -1,13 +1,13 @@ import { utils } from 'ethers'; -import { EventListenerType, addEventListener } from '~eventListeners'; -import { ContractEventsSignatures, EventHandler } from '~types'; +import { ContractEventsSignatures, EventHandler , EventListenerType } from '@joincolony/blocks'; +import eventManager from '~eventManager'; export const addProxyColoniesEventListener = ( eventSignature: ContractEventsSignatures, handler: EventHandler, ): void => - addEventListener({ + eventManager.addEventListener({ type: EventListenerType.ProxyColonies, eventSignature, topics: [utils.id(eventSignature)], diff --git a/apps/main-chain/src/eventListeners/token.ts b/apps/main-chain/src/eventListeners/token.ts index 119ad5367..de3964d01 100644 --- a/apps/main-chain/src/eventListeners/token.ts +++ b/apps/main-chain/src/eventListeners/token.ts @@ -1,6 +1,5 @@ -import { ContractEventsSignatures, EventHandler } from '~types'; -import { addEventListener, getEventListeners } from '~eventListeners'; -import { EventListenerType, EventListener } from './types'; +import { ContractEventsSignatures, EventHandler , EventListenerType, EventListener } from '@joincolony/blocks'; +import eventManager from '~eventManager'; import { utils } from 'ethers'; import isEqual from 'lodash/isEqual'; @@ -32,12 +31,12 @@ export const addTokenEventListener = ( * As a general rule, this will only *NOT* apply to the token Transfer event * as that's the only one treated differently. */ - const listenerExists = getEventListeners().some((existingListener) => - isEqual(existingListener, tokenListener), - ); + const listenerExists = eventManager + .getEventListeners() + .some((existingListener) => isEqual(existingListener, tokenListener)); if (listenerExists) { return; } - return addEventListener(tokenListener); + return eventManager.addEventListener(tokenListener); }; diff --git a/apps/main-chain/src/eventListeners/types.ts b/apps/main-chain/src/eventListeners/types.ts deleted file mode 100644 index 0ea3633fc..000000000 --- a/apps/main-chain/src/eventListeners/types.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { ContractEventsSignatures, EventHandler } from '~types'; - -export interface BaseEventListener { - type: EventListenerType; - eventSignature: ContractEventsSignatures; - topics: Array; - handler: EventHandler; - address?: string; -} - -export enum EventListenerType { - Colony = 'Colony', - Network = 'Network', - Extension = 'Extension', - Token = 'Token', - MultisigPermissions = 'MultisigPermissions', - ProxyColonies = 'ProxyColonies', -} - -export interface ColonyEventListener extends BaseEventListener { - type: EventListenerType.Colony; - address: string; -} - -export interface NetworkEventListener extends BaseEventListener { - type: EventListenerType.Network; - address: string; -} - -// Special listener just for Token transfers -// Due to the volume of these events, we can't process them in the same way -// as the normal events -export interface TokenTransferEventListener extends BaseEventListener { - type: EventListenerType.Token; -} - -export interface TokenEventListener extends BaseEventListener { - type: EventListenerType.Token; - address: string; -} - -export interface ProxyColoniesListener extends BaseEventListener { - type: EventListenerType.ProxyColonies; - address: string; -} - -export interface ExtensionEventListener extends BaseEventListener { - type: EventListenerType.Extension; - address: string; - colonyAddress: string; - extensionHash: string; - handler: EventHandler; -} - -export type EventListener = - | ColonyEventListener - | NetworkEventListener - | TokenEventListener - | TokenTransferEventListener - | ProxyColoniesListener - | ExtensionEventListener; diff --git a/apps/main-chain/src/eventManager.ts b/apps/main-chain/src/eventManager.ts new file mode 100644 index 000000000..b57b8481f --- /dev/null +++ b/apps/main-chain/src/eventManager.ts @@ -0,0 +1,6 @@ +import { EventManager } from '@joincolony/blocks'; +import rpcProvider from '~provider'; + +const eventManager = new EventManager(rpcProvider); + +export default eventManager; diff --git a/apps/main-chain/src/handlers/actions/annotateTransaction.ts b/apps/main-chain/src/handlers/actions/annotateTransaction.ts index 2cb130465..838f85cb4 100644 --- a/apps/main-chain/src/handlers/actions/annotateTransaction.ts +++ b/apps/main-chain/src/handlers/actions/annotateTransaction.ts @@ -1,4 +1,4 @@ -import { mutate, query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { GetActionIdFromAnnotationDocument, GetActionIdFromAnnotationQuery, @@ -13,14 +13,14 @@ import { UpdateColonyMotionMutation, UpdateColonyMotionMutationVariables, } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; -import { verbose } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; +import { verbose } from '@joincolony/utils'; export default async ({ args }: ContractEvent): Promise => { const [, txHash] = args; const { data } = - (await query< + (await amplifyClient.query< GetActionIdFromAnnotationQuery, GetActionIdFromAnnotationQueryVariables >(GetActionIdFromAnnotationDocument, { id: txHash })) ?? {}; @@ -45,7 +45,7 @@ export default async ({ args }: ContractEvent): Promise => { if (isMotionObjection) { const { data } = - (await query< + (await amplifyClient.query< GetMotionIdFromActionQuery, GetMotionIdFromActionQueryVariables >(GetMotionIdFromActionDocument, { id: actionId })) ?? {}; @@ -60,7 +60,7 @@ export default async ({ args }: ContractEvent): Promise => { return; } - await mutate< + await amplifyClient.mutate< UpdateColonyMotionMutation, UpdateColonyMotionMutationVariables >(UpdateColonyMotionDocument, { @@ -70,7 +70,7 @@ export default async ({ args }: ContractEvent): Promise => { }, }); } else { - await mutate< + await amplifyClient.mutate< UpdateColonyActionMutation, UpdateColonyActionMutationVariables >(UpdateColonyActionDocument, { diff --git a/apps/main-chain/src/handlers/actions/colonyUpgrade.ts b/apps/main-chain/src/handlers/actions/colonyUpgrade.ts index e23efc094..b819965e8 100644 --- a/apps/main-chain/src/handlers/actions/colonyUpgrade.ts +++ b/apps/main-chain/src/handlers/actions/colonyUpgrade.ts @@ -1,14 +1,15 @@ -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyActionType, UpdateColonyDocument, UpdateColonyMutation, UpdateColonyMutationVariables, } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; import { NotificationCategory } from '~types/notifications'; -import { toNumber, verbose, writeActionFromEvent } from '~utils'; +import { toNumber, writeActionFromEvent } from '~utils'; import { sendPermissionsActionNotifications } from '~utils/notifications'; +import { verbose } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { contractAddress: colonyAddress, transactionHash } = event; @@ -18,15 +19,15 @@ export default async (event: ContractEvent): Promise => { verbose('Colony:', colonyAddress, `upgraded to version ${convertedVersion}`); // Update colony version in the db - await mutate( - UpdateColonyDocument, - { - input: { - id: event.contractAddress, - version: convertedVersion, - }, + await amplifyClient.mutate< + UpdateColonyMutation, + UpdateColonyMutationVariables + >(UpdateColonyDocument, { + input: { + id: event.contractAddress, + version: convertedVersion, }, - ); + }); await writeActionFromEvent(event, colonyAddress, { type: ColonyActionType.VersionUpgrade, diff --git a/apps/main-chain/src/handlers/actions/createDomain.ts b/apps/main-chain/src/handlers/actions/createDomain.ts index 9665852a0..452ff3171 100644 --- a/apps/main-chain/src/handlers/actions/createDomain.ts +++ b/apps/main-chain/src/handlers/actions/createDomain.ts @@ -1,11 +1,11 @@ -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyActionType, CreateDomainDocument, CreateDomainMutation, CreateDomainMutationVariables, } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; import { NotificationCategory } from '~types/notifications'; import { toNumber, @@ -35,19 +35,19 @@ export default async (event: ContractEvent): Promise => { blockTag: blockNumber, }); - await mutate( - CreateDomainDocument, - { - input: { - id: databaseDomainId, - colonyId: colonyAddress, - nativeId: nativeDomainId, - isRoot: false, - nativeFundingPotId: toNumber(fundingPotId), - nativeSkillId: skillId.toString(), - }, + await amplifyClient.mutate< + CreateDomainMutation, + CreateDomainMutationVariables + >(CreateDomainDocument, { + input: { + id: databaseDomainId, + colonyId: colonyAddress, + nativeId: nativeDomainId, + isRoot: false, + nativeFundingPotId: toNumber(fundingPotId), + nativeSkillId: skillId.toString(), }, - ); + }); await writeActionFromEvent(event, colonyAddress, { type: ColonyActionType.CreateDomain, diff --git a/apps/main-chain/src/handlers/actions/editColony.ts b/apps/main-chain/src/handlers/actions/editColony.ts index 3cd868d0a..8af448e52 100644 --- a/apps/main-chain/src/handlers/actions/editColony.ts +++ b/apps/main-chain/src/handlers/actions/editColony.ts @@ -1,7 +1,7 @@ import { Id } from '@colony/colony-js'; import { ColonyActionType } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; import { NotificationCategory } from '~types/notifications'; import { getDomainDatabaseId, writeActionFromEvent } from '~utils'; import { sendPermissionsActionNotifications } from '~utils/notifications'; diff --git a/apps/main-chain/src/handlers/actions/editDomain.ts b/apps/main-chain/src/handlers/actions/editDomain.ts index d0065a662..92fea325d 100644 --- a/apps/main-chain/src/handlers/actions/editDomain.ts +++ b/apps/main-chain/src/handlers/actions/editDomain.ts @@ -1,9 +1,9 @@ import { ColonyActionType } from '@joincolony/graphql'; -import { ContractEvent, ContractEventsSignatures } from '~types'; +import { verbose } from '@joincolony/utils'; +import { ContractEvent, ContractEventsSignatures } from '@joincolony/blocks'; import { NotificationCategory } from '~types/notifications'; import { toNumber, - verbose, writeActionFromEvent, getDomainDatabaseId, transactionHasEvent, diff --git a/apps/main-chain/src/handlers/actions/emitDomainReputation.ts b/apps/main-chain/src/handlers/actions/emitDomainReputation.ts index 0d3ef0eb1..e151e7caf 100644 --- a/apps/main-chain/src/handlers/actions/emitDomainReputation.ts +++ b/apps/main-chain/src/handlers/actions/emitDomainReputation.ts @@ -1,21 +1,17 @@ import { BigNumber } from 'ethers'; -import { ContractEvent, ContractEventsSignatures } from '~types'; -import { - writeActionFromEvent, - verbose, - notNull, - transactionHasEvent, -} from '~utils'; +import { ContractEvent, ContractEventsSignatures } from '@joincolony/blocks'; +import { writeActionFromEvent, notNull, transactionHasEvent } from '~utils'; import { ColonyActionType, GetColonyDocument, GetColonyQuery, GetColonyQueryVariables, } from '@joincolony/graphql'; -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { sendPermissionsActionNotifications } from '~utils/notifications'; import { NotificationCategory } from '~types/notifications'; +import { verbose } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { contractAddress: colonyAddress, transactionHash } = event; @@ -56,10 +52,13 @@ export default async (event: ContractEvent): Promise => { */ do { const { data } = - (await query(GetColonyDocument, { - id: colonyAddress, - nextToken, - })) ?? {}; + (await amplifyClient.query( + GetColonyDocument, + { + id: colonyAddress, + nextToken, + }, + )) ?? {}; domain = data?.getColony?.domains?.items .filter(notNull) .find( diff --git a/apps/main-chain/src/handlers/actions/makeArbitraryTransaction.ts b/apps/main-chain/src/handlers/actions/makeArbitraryTransaction.ts index 63168d3a3..179744f80 100644 --- a/apps/main-chain/src/handlers/actions/makeArbitraryTransaction.ts +++ b/apps/main-chain/src/handlers/actions/makeArbitraryTransaction.ts @@ -6,20 +6,22 @@ import { GetColonyActionQuery, GetColonyActionQueryVariables, } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; -import provider from '~provider'; +import { ContractEvent } from '@joincolony/blocks'; +import rpcProvider from '~provider'; import { getDomainDatabaseId, writeActionFromEvent } from '~utils'; -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; export default async (event: ContractEvent): Promise => { const { contractAddress: colonyAddress, transactionHash } = event; - const receipt = await provider.getTransactionReceipt(event.transactionHash); + const receipt = await rpcProvider + .getProviderInstance() + .getTransactionReceipt(event.transactionHash); const { data } = - (await query( - GetColonyActionDocument, - { transactionHash }, - )) ?? {}; + (await amplifyClient.query< + GetColonyActionQuery, + GetColonyActionQueryVariables + >(GetColonyActionDocument, { transactionHash })) ?? {}; // @NOTE: Filter out the event if it's already been processed (It can happen with multi-transactions) if (data?.getColonyAction?.id) { diff --git a/apps/main-chain/src/handlers/actions/managePermissions.ts b/apps/main-chain/src/handlers/actions/managePermissions.ts index 40783f8e9..193315e96 100644 --- a/apps/main-chain/src/handlers/actions/managePermissions.ts +++ b/apps/main-chain/src/handlers/actions/managePermissions.ts @@ -1,7 +1,11 @@ import { BigNumber } from 'ethers'; import { Id } from '@colony/colony-js'; -import { mutate, query } from '~amplifyClient'; -import { ContractEventsSignatures, EventHandler } from '~types'; +import amplifyClient from '~amplifyClient'; +import { + ContractEventsSignatures, + EventHandler, + ExtensionEventListener, +} from '@joincolony/blocks'; import { getColonyRolesDatabaseId, getDomainDatabaseId, @@ -9,7 +13,6 @@ import { createColonyHistoricRoleDatabaseEntry, getAllRoleEventsFromTransaction, getRolesMapFromEvents, - verbose, writeActionFromEvent, isAddressExtension, getAllMultiSigRoleEventsFromTransaction, @@ -26,11 +29,11 @@ import { UpdateColonyRoleDocument, ColonyActionType, } from '@joincolony/graphql'; -import provider from '~provider'; +import rpcProvider from '~provider'; import { updateColonyContributor } from '~utils/contributors'; -import { ExtensionEventListener } from '~eventListeners'; import { sendPermissionsActionNotifications } from '~utils/notifications'; import { NotificationCategory } from '~types/notifications'; +import { verbose } from '@joincolony/utils'; export const handleManagePermissionsAction: EventHandler = async ( event, @@ -83,7 +86,7 @@ export const handleManagePermissionsAction: EventHandler = async ( __typename, ...existingRoles } = ( - await query( + await amplifyClient.query( GetColonyRoleDocument, { id }, ) @@ -110,9 +113,9 @@ export const handleManagePermissionsAction: EventHandler = async ( // We can get the msg.sender from the transaction receipt. if (!agent) { - const { from = '' } = await provider.getTransactionReceipt( - transactionHash, - ); + const { from = '' } = await rpcProvider + .getProviderInstance() + .getTransactionReceipt(transactionHash); agent = from; } const allRoleEventsUpdates = isMultiSig @@ -130,16 +133,16 @@ export const handleManagePermissionsAction: EventHandler = async ( ? getMultiSigRolesMapFromEvents(allRoleEventsUpdates, false) : getRolesMapFromEvents(allRoleEventsUpdates, false); - await mutate( - UpdateColonyRoleDocument, - { - input: { - id, - latestBlock: blockNumber, - ...rolesFromAllUpdateEvents, - }, + await amplifyClient.mutate< + UpdateColonyRoleMutation, + UpdateColonyRoleMutationVariables + >(UpdateColonyRoleDocument, { + input: { + id, + latestBlock: blockNumber, + ...rolesFromAllUpdateEvents, }, - ); + }); verbose( `Update the${ diff --git a/apps/main-chain/src/handlers/actions/mintTokens.ts b/apps/main-chain/src/handlers/actions/mintTokens.ts index 235efb326..33b206106 100644 --- a/apps/main-chain/src/handlers/actions/mintTokens.ts +++ b/apps/main-chain/src/handlers/actions/mintTokens.ts @@ -1,13 +1,13 @@ import { Id } from '@colony/colony-js'; import { ColonyActionType } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; +import { verbose } from '@joincolony/utils'; +import { ContractEvent } from '@joincolony/blocks'; import { NotificationCategory } from '~types/notifications'; import { writeActionFromEvent, getColonyTokenAddress, getDomainDatabaseId, - verbose, } from '~utils'; import { sendPermissionsActionNotifications } from '~utils/notifications'; diff --git a/apps/main-chain/src/handlers/actions/moveFunds.ts b/apps/main-chain/src/handlers/actions/moveFunds.ts index 2f19d1d05..45de520d1 100644 --- a/apps/main-chain/src/handlers/actions/moveFunds.ts +++ b/apps/main-chain/src/handlers/actions/moveFunds.ts @@ -1,6 +1,6 @@ import { BigNumber } from 'ethers'; -import { ContractEvent, ContractEventsSignatures } from '~types'; +import { ContractEvent, ContractEventsSignatures } from '@joincolony/blocks'; import { toNumber, writeActionFromEvent, @@ -10,7 +10,6 @@ import { getUpdatedExpenditureBalances, transactionHasEvent, getExpenditureByFundingPot, - verbose, } from '~utils'; import { ColonyActionType, @@ -21,12 +20,13 @@ import { UpdateExpenditureMutation, UpdateExpenditureMutationVariables, } from '@joincolony/graphql'; -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { sendExpenditureUpdateNotifications, sendPermissionsActionNotifications, } from '~utils/notifications'; import { NotificationCategory } from '~types/notifications'; +import { verbose } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { @@ -140,15 +140,15 @@ const updateExpenditureBalances = async ({ amount, ); - await mutate( - UpdateExpenditureDocument, - { - input: { - id: expenditure.id, - balances: updatedBalances, - }, + await amplifyClient.mutate< + UpdateExpenditureMutation, + UpdateExpenditureMutationVariables + >(UpdateExpenditureDocument, { + input: { + id: expenditure.id, + balances: updatedBalances, }, - ); + }); if ( !isPartOfOneTxPayment && diff --git a/apps/main-chain/src/handlers/actions/oneTxPayment.ts b/apps/main-chain/src/handlers/actions/oneTxPayment.ts index c6d179ddc..17bdbc2ba 100644 --- a/apps/main-chain/src/handlers/actions/oneTxPayment.ts +++ b/apps/main-chain/src/handlers/actions/oneTxPayment.ts @@ -1,14 +1,14 @@ import { AnyColonyClient } from '@colony/colony-js'; import { BigNumber, utils } from 'ethers'; -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyActionType, GetColonyExtensionDocument, GetColonyExtensionQuery, GetColonyExtensionQueryVariables, } from '@joincolony/graphql'; -import provider from '~provider'; -import { ContractEvent, ContractEventsSignatures } from '~types'; +import rpcProvider from '~provider'; +import { ContractEvent, ContractEventsSignatures } from '@joincolony/blocks'; import { NotificationCategory } from '~types/notifications'; import { getCachedColonyClient, @@ -66,10 +66,10 @@ export default async (oneTxPaymentEvent: ContractEvent): Promise => { const { contractAddress: extensionAddress } = oneTxPaymentEvent; const { data } = - (await query( - GetColonyExtensionDocument, - { id: extensionAddress }, - )) ?? {}; + (await amplifyClient.query< + GetColonyExtensionQuery, + GetColonyExtensionQueryVariables + >(GetColonyExtensionDocument, { id: extensionAddress })) ?? {}; const { colonyId: colonyAddress = '', version } = data?.getColonyExtension ?? {}; @@ -123,7 +123,9 @@ const handlerV1ToV5 = async ( ): Promise => { const { blockNumber } = event; const [initiatorAddress, paymentOrExpenditureId, nPayments] = event.args; - const receipt = await provider.getTransactionReceipt(event.transactionHash); + const receipt = await rpcProvider + .getProviderInstance() + .getTransactionReceipt(event.transactionHash); if ((nPayments as BigNumber).eq(1)) { const [payoutClaimedLog] = receipt.logs.filter( @@ -228,7 +230,9 @@ const handlerV6 = async ( ): Promise => { const { blockNumber, transactionHash } = event; const [initiatorAddress, expenditureId] = event.args; - const receipt = await provider.getTransactionReceipt(event.transactionHash); + const receipt = await rpcProvider + .getProviderInstance() + .getTransactionReceipt(event.transactionHash); // multiple OneTxPayments use expenditures at the contract level const expenditure: Expenditure = await colonyClient.getExpenditure( diff --git a/apps/main-chain/src/handlers/actions/unlockToken.ts b/apps/main-chain/src/handlers/actions/unlockToken.ts index 9c353e2bf..21a864b43 100644 --- a/apps/main-chain/src/handlers/actions/unlockToken.ts +++ b/apps/main-chain/src/handlers/actions/unlockToken.ts @@ -1,7 +1,7 @@ import { Id } from '@colony/colony-js'; import { ColonyActionType } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; import { NotificationCategory } from '~types/notifications'; import { writeActionFromEvent, diff --git a/apps/main-chain/src/handlers/colonies/colonyAdded.ts b/apps/main-chain/src/handlers/colonies/colonyAdded.ts index 54eda29af..ce673e559 100644 --- a/apps/main-chain/src/handlers/colonies/colonyAdded.ts +++ b/apps/main-chain/src/handlers/colonies/colonyAdded.ts @@ -1,6 +1,6 @@ import { utils } from 'ethers'; -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { setupListenersForColony } from '~eventListeners'; import { UpdateColonyContributorDocument, @@ -9,16 +9,16 @@ import { GetColonyMetadataDocument, } from '@joincolony/graphql'; import { coloniesSet } from '~stats'; -import { ContractEvent, ContractEventsSignatures } from '~types'; +import { ContractEvent, ContractEventsSignatures } from '@joincolony/blocks'; import { - output, - updateStats, createColonyFounderInitialRoleEntry, getAllRoleEventsFromTransaction, } from '~utils'; +import statsManager from '~statsManager'; import { getColonyContributorId } from '~utils/contributors'; import { tryFetchGraphqlQuery } from '~utils/graphql'; import { createUniqueColony } from './helpers/createUniqueColony'; +import { output } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { transactionHash, args, blockNumber } = event; @@ -50,8 +50,9 @@ export default async (event: ContractEvent): Promise => { /* * Add it to the Set */ + // @NOTE seems to not be working, is it borken on master too? coloniesSet.add(JSON.stringify({ colonyAddress, tokenAddress })); - await updateStats({ trackedColonies: coloniesSet.size }); + await statsManager.updateStats({ trackedColonies: coloniesSet.size }); output( 'Found new Colony:', @@ -120,7 +121,7 @@ export default async (event: ContractEvent): Promise => { * check whether the contributor has already been created in the front end, and perform an update or a create mutation * accordingly. */ - await mutate< + await amplifyClient.mutate< UpdateColonyContributorMutation, UpdateColonyContributorMutationVariables >(UpdateColonyContributorDocument, { diff --git a/apps/main-chain/src/handlers/colonies/colonyFundsClaimed.ts b/apps/main-chain/src/handlers/colonies/colonyFundsClaimed.ts index 077883c34..fc7809ae6 100644 --- a/apps/main-chain/src/handlers/colonies/colonyFundsClaimed.ts +++ b/apps/main-chain/src/handlers/colonies/colonyFundsClaimed.ts @@ -1,8 +1,8 @@ import { constants } from 'ethers'; -import { mutate, query } from '~amplifyClient'; -import { ContractEvent } from '~types'; -import { output, saveEvent, notNull } from '~utils'; +import amplifyClient from '~amplifyClient'; +import { ContractEvent } from '@joincolony/blocks'; +import { saveEvent, notNull } from '~utils'; import { UpdateColonyFundsClaimDocument, UpdateColonyFundsClaimMutation, @@ -12,6 +12,7 @@ import { GetColonyUnclaimedFundsQueryVariables, } from '@joincolony/graphql'; import { sendFundsClaimedNotifications } from '~utils/notifications'; +import { output } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { contractAddress: colonyAddress, blockNumber } = event; @@ -24,7 +25,7 @@ export default async (event: ContractEvent): Promise => { if (tokenAddress !== constants.AddressZero) { const { items: unclaimedFunds } = ( - await query< + await amplifyClient.query< GetColonyUnclaimedFundsQuery, GetColonyUnclaimedFundsQueryVariables >(GetColonyUnclaimedFundsDocument, { @@ -55,7 +56,7 @@ export default async (event: ContractEvent): Promise => { if (colonyHasUnclaimedFunds) { await Promise.all( unclaimedFunds.filter(notNull).map(async ({ id, token, amount }) => { - await mutate< + await amplifyClient.mutate< UpdateColonyFundsClaimMutation, UpdateColonyFundsClaimMutationVariables >(UpdateColonyFundsClaimDocument, { diff --git a/apps/main-chain/src/handlers/colonies/colonyVersionAdded.ts b/apps/main-chain/src/handlers/colonies/colonyVersionAdded.ts index 4e6398403..4c8146386 100644 --- a/apps/main-chain/src/handlers/colonies/colonyVersionAdded.ts +++ b/apps/main-chain/src/handlers/colonies/colonyVersionAdded.ts @@ -1,6 +1,7 @@ +import { verbose } from '@joincolony/utils'; import { COLONY_CURRENT_VERSION_KEY } from '~constants'; -import { ContractEvent } from '~types'; -import { toNumber, verbose } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; +import { toNumber } from '~utils'; import { updateCurrentVersion } from '~utils/currentVersion'; import { sendColonyVersionAddedNotifications } from '~utils/notifications'; diff --git a/apps/main-chain/src/handlers/colonies/helpers/createUniqueColony.ts b/apps/main-chain/src/handlers/colonies/helpers/createUniqueColony.ts index 5ecbeef7f..ccd38b396 100644 --- a/apps/main-chain/src/handlers/colonies/helpers/createUniqueColony.ts +++ b/apps/main-chain/src/handlers/colonies/helpers/createUniqueColony.ts @@ -1,7 +1,7 @@ import { Id } from '@colony/colony-js'; import { utils } from 'ethers'; import { randomUUID } from 'crypto'; -import { mutate, query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyType, CreateColonyDocument, @@ -39,7 +39,7 @@ import { GetTokenFromEverywhereQuery, GetTokenFromEverywhereQueryVariables, } from '@joincolony/graphql'; -import { getChainId } from '~provider'; +import rpcProvider from '~provider'; import { getCachedColonyClient } from '~utils/clients/colony'; export const createUniqueColony = async ({ @@ -86,9 +86,12 @@ export const createUniqueColony = async ({ * Via it's address */ const colonyQuery = - (await query(GetColonyDocument, { - id: checksummedAddress, - })) ?? {}; + (await amplifyClient.query( + GetColonyDocument, + { + id: checksummedAddress, + }, + )) ?? {}; if (!colonyQuery.data) { throw new Error('Could not fetch colony data'); @@ -107,12 +110,12 @@ export const createUniqueColony = async ({ * Get metadata, determine if it's the correct one, and if we should proceed */ const metadataQuery = - (await query( - GetColonyMetadataDocument, - { - id: `etherealcolonymetadata-${transactionHash}`, - }, - )) ?? {}; + (await amplifyClient.query< + GetColonyMetadataQuery, + GetColonyMetadataQueryVariables + >(GetColonyMetadataDocument, { + id: `etherealcolonymetadata-${transactionHash}`, + })) ?? {}; if (!metadataQuery.data) { throw new Error('Could not fetch metadata data'); @@ -139,10 +142,10 @@ export const createUniqueColony = async ({ * Ensure the colony name doesn't already exist in the database */ const colonyNameQuery = - (await query( - GetColonyByNameDocument, - { name: colonyName }, - )) ?? {}; + (await amplifyClient.query< + GetColonyByNameQuery, + GetColonyByNameQueryVariables + >(GetColonyByNameDocument, { name: colonyName })) ?? {}; if (!colonyNameQuery) { throw new Error(); @@ -169,7 +172,7 @@ export const createUniqueColony = async ({ /* * Create token in the database */ - const tokenQuery = await query< + const tokenQuery = await amplifyClient.query< GetTokenFromEverywhereQuery, GetTokenFromEverywhereQueryVariables >(GetTokenFromEverywhereDocument, { @@ -194,7 +197,7 @@ export const createUniqueColony = async ({ const memberInviteCode = randomUUID(); - const chainId = getChainId(); + const chainId = rpcProvider.getChainId(); const version = await colonyClient.version(); let isTokenLocked; @@ -202,7 +205,7 @@ export const createUniqueColony = async ({ isTokenLocked = await colonyClient.tokenClient.locked(); } - const colonyMutation = await mutate< + const colonyMutation = await amplifyClient.mutate< CreateColonyMutation, CreateColonyMutationVariables >(CreateColonyDocument, { @@ -239,7 +242,7 @@ export const createUniqueColony = async ({ /* * Set the actual colony metadata object */ - const colonyMetadataMutation = await mutate< + const colonyMetadataMutation = await amplifyClient.mutate< CreateColonyMetadataMutation, CreateColonyMetadataMutationVariables >(CreateColonyMetadataDocument, { @@ -258,7 +261,7 @@ export const createUniqueColony = async ({ /* * Delete the ethereal metadata entry */ - await mutate< + await amplifyClient.mutate< DeleteColonyMetadataMutation, DeleteColonyMetadataMutationVariables >(DeleteColonyMetadataDocument, { @@ -268,7 +271,7 @@ export const createUniqueColony = async ({ /* * Create the member invite */ - const inviteMutation = await mutate< + const inviteMutation = await amplifyClient.mutate< CreateColonyMemberInviteMutation, CreateColonyMemberInviteMutationVariables >(CreateColonyMemberInviteDocument, { @@ -286,20 +289,20 @@ export const createUniqueColony = async ({ /* * Add token to the colony's token list */ - await mutate( - CreateColonyTokensDocument, - { - input: { - colonyID: checksummedAddress, - tokenID: checksummedToken, - }, + await amplifyClient.mutate< + CreateColonyTokensMutation, + CreateColonyTokensMutationVariables + >(CreateColonyTokensDocument, { + input: { + colonyID: checksummedAddress, + tokenID: checksummedToken, }, - ); + }); /* * Create the root domain metadata */ - await mutate< + await amplifyClient.mutate< CreateDomainMetadataMutation, CreateDomainMetadataMutationVariables >(CreateDomainMetadataDocument, { @@ -316,17 +319,17 @@ export const createUniqueColony = async ({ /* * Create the root domain */ - await mutate( - CreateDomainDocument, - { - input: { - id: `${checksummedAddress}_${Id.RootDomain}`, - colonyId: checksummedAddress, - isRoot: true, - nativeId: Id.RootDomain, - nativeSkillId: skillId.toString(), - nativeFundingPotId: fundingPotId.toNumber(), - }, + await amplifyClient.mutate< + CreateDomainMutation, + CreateDomainMutationVariables + >(CreateDomainDocument, { + input: { + id: `${checksummedAddress}_${Id.RootDomain}`, + colonyId: checksummedAddress, + isRoot: true, + nativeId: Id.RootDomain, + nativeSkillId: skillId.toString(), + nativeFundingPotId: fundingPotId.toNumber(), }, - ); + }); }; diff --git a/apps/main-chain/src/handlers/colonies/transfer.ts b/apps/main-chain/src/handlers/colonies/transfer.ts index b75db84ef..ce58c3d04 100644 --- a/apps/main-chain/src/handlers/colonies/transfer.ts +++ b/apps/main-chain/src/handlers/colonies/transfer.ts @@ -1,7 +1,7 @@ -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import networkClient from '~networkClient'; -import { getChainId } from '~provider'; -import { ContractEvent } from '~types'; +import rpcProvider from '~provider'; +import { ContractEvent } from '@joincolony/blocks'; import { GetColonyUnclaimedFundDocument, GetColonyUnclaimedFundQuery, @@ -10,11 +10,12 @@ import { GetTokenFromEverywhereQuery, GetTokenFromEverywhereQueryVariables, } from '@joincolony/graphql'; -import { output, createFundsClaim } from '~utils'; +import { createFundsClaim } from '~utils'; +import { output } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { contractAddress: tokenAddress, logIndex, transactionHash } = event; - const chainId = getChainId(); + const chainId = rpcProvider.getChainId(); /* * @NOTE Take the values from the "array" rather than from the named properties * This is because our native tokens differ in abi from ERC20 or SAI tokens @@ -62,7 +63,7 @@ export default async (event: ContractEvent): Promise => { if (process.env.NODE_ENV !== 'production') { const { id: existingClaimId } = ( - await query< + await amplifyClient.query< GetColonyUnclaimedFundQuery, GetColonyUnclaimedFundQueryVariables >(GetColonyUnclaimedFundDocument, { claimId }) @@ -89,7 +90,7 @@ export default async (event: ContractEvent): Promise => { * gets added to the DB if it doesn't already exist */ try { - const dbTokenQuery = await query< + const dbTokenQuery = await amplifyClient.query< GetTokenFromEverywhereQuery, GetTokenFromEverywhereQueryVariables >(GetTokenFromEverywhereDocument, { diff --git a/apps/main-chain/src/handlers/expenditures/expenditureAdded.ts b/apps/main-chain/src/handlers/expenditures/expenditureAdded.ts index 8fa11b81b..63d2a3865 100644 --- a/apps/main-chain/src/handlers/expenditures/expenditureAdded.ts +++ b/apps/main-chain/src/handlers/expenditures/expenditureAdded.ts @@ -1,4 +1,4 @@ -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyActionType, CreateExpenditureDocument, @@ -8,19 +8,18 @@ import { ExpenditureType, NotificationType, } from '@joincolony/graphql'; -import { ContractEvent, ContractEventsSignatures } from '~types'; +import { ContractEvent, ContractEventsSignatures } from '@joincolony/blocks'; import { transactionHasEvent, getDomainDatabaseId, getExpenditureDatabaseId, - output, toNumber, - verbose, writeActionFromEvent, } from '~utils'; import { getExpenditure } from './helpers'; import { sendExpenditureUpdateNotifications } from '~utils/notifications'; +import { output, verbose } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { contractAddress: colonyAddress, transactionHash } = event; @@ -53,24 +52,24 @@ export default async (event: ContractEvent): Promise => { convertedExpenditureId, ); - await mutate( - CreateExpenditureDocument, - { - input: { - id: databaseId, - type: ExpenditureType.PaymentBuilder, - colonyId: colonyAddress, - nativeId: convertedExpenditureId, - ownerAddress, - status: ExpenditureStatus.Draft, - slots: [], - nativeFundingPotId: fundingPotId, - nativeDomainId: domainId, - isStaked: false, - balances: [], - }, + await amplifyClient.mutate< + CreateExpenditureMutation, + CreateExpenditureMutationVariables + >(CreateExpenditureDocument, { + input: { + id: databaseId, + type: ExpenditureType.PaymentBuilder, + colonyId: colonyAddress, + nativeId: convertedExpenditureId, + ownerAddress, + status: ExpenditureStatus.Draft, + slots: [], + nativeFundingPotId: fundingPotId, + nativeDomainId: domainId, + isStaked: false, + balances: [], }, - ); + }); /** * @NOTE: Only create a `CREATE_EXPENDITURE` action if the expenditure was not created as part of a OneTxPayment diff --git a/apps/main-chain/src/handlers/expenditures/expenditureCancelled.ts b/apps/main-chain/src/handlers/expenditures/expenditureCancelled.ts index 930087740..371d28dc7 100644 --- a/apps/main-chain/src/handlers/expenditures/expenditureCancelled.ts +++ b/apps/main-chain/src/handlers/expenditures/expenditureCancelled.ts @@ -1,11 +1,9 @@ -import { EventHandler } from '~types'; import { getExpenditureDatabaseId, toNumber, - verbose, writeActionFromEvent, } from '~utils'; -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyActionType, ExpenditureStatus, @@ -14,8 +12,9 @@ import { UpdateExpenditureMutation, UpdateExpenditureMutationVariables, } from '@joincolony/graphql'; -import { EventListenerType } from '~eventListeners'; +import { EventListenerType, EventHandler } from '@joincolony/blocks'; import { sendExpenditureUpdateNotifications } from '~utils/notifications'; +import { verbose } from '@joincolony/utils'; export const handleExpenditureCancelled: EventHandler = async ( event, @@ -45,15 +44,15 @@ export const handleExpenditureCancelled: EventHandler = async ( colonyAddress, ); - await mutate( - UpdateExpenditureDocument, - { - input: { - id: databaseId, - status: ExpenditureStatus.Cancelled, - }, + await amplifyClient.mutate< + UpdateExpenditureMutation, + UpdateExpenditureMutationVariables + >(UpdateExpenditureDocument, { + input: { + id: databaseId, + status: ExpenditureStatus.Cancelled, }, - ); + }); await writeActionFromEvent(event, colonyAddress, { type: ColonyActionType.CancelExpenditure, diff --git a/apps/main-chain/src/handlers/expenditures/expenditureClaimDelaySet.ts b/apps/main-chain/src/handlers/expenditures/expenditureClaimDelaySet.ts index 8a8bd30d2..eefee4c74 100644 --- a/apps/main-chain/src/handlers/expenditures/expenditureClaimDelaySet.ts +++ b/apps/main-chain/src/handlers/expenditures/expenditureClaimDelaySet.ts @@ -1,14 +1,15 @@ import { BigNumber } from 'ethers'; -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { UpdateExpenditureDocument, UpdateExpenditureMutation, UpdateExpenditureMutationVariables, } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; -import { getExpenditureDatabaseId, output, toNumber, verbose } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; +import { getExpenditureDatabaseId, toNumber } from '~utils'; import { getExpenditureFromDB, getUpdatedExpenditureSlots } from './helpers'; +import { output, verbose } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { contractAddress: colonyAddress } = event; @@ -42,13 +43,13 @@ export default async (event: ContractEvent): Promise => { `Claim delay set for expenditure with ID ${convertedExpenditureId} in colony ${colonyAddress}`, ); - await mutate( - UpdateExpenditureDocument, - { - input: { - id: databaseId, - slots: updatedSlots, - }, + await amplifyClient.mutate< + UpdateExpenditureMutation, + UpdateExpenditureMutationVariables + >(UpdateExpenditureDocument, { + input: { + id: databaseId, + slots: updatedSlots, }, - ); + }); }; diff --git a/apps/main-chain/src/handlers/expenditures/expenditureFinalized.ts b/apps/main-chain/src/handlers/expenditures/expenditureFinalized.ts index 89ee92441..f31c95f32 100644 --- a/apps/main-chain/src/handlers/expenditures/expenditureFinalized.ts +++ b/apps/main-chain/src/handlers/expenditures/expenditureFinalized.ts @@ -1,4 +1,4 @@ -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyActionType, ExpenditureStatus, @@ -7,15 +7,15 @@ import { UpdateExpenditureMutation, UpdateExpenditureMutationVariables, } from '@joincolony/graphql'; -import { ContractEvent, ContractEventsSignatures } from '~types'; +import { ContractEvent, ContractEventsSignatures } from '@joincolony/blocks'; import { getExpenditureDatabaseId, toNumber, transactionHasEvent, - verbose, writeActionFromEvent, } from '~utils'; import { sendExpenditureUpdateNotifications } from '~utils/notifications'; +import { verbose } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { contractAddress: colonyAddress } = event; @@ -34,16 +34,16 @@ export default async (event: ContractEvent): Promise => { colonyAddress, ); - await mutate( - UpdateExpenditureDocument, - { - input: { - id: databaseId, - status: ExpenditureStatus.Finalized, - finalizedAt: event.timestamp, - }, + await amplifyClient.mutate< + UpdateExpenditureMutation, + UpdateExpenditureMutationVariables + >(UpdateExpenditureDocument, { + input: { + id: databaseId, + status: ExpenditureStatus.Finalized, + finalizedAt: event.timestamp, }, - ); + }); /** * @NOTE: Only create a `FINALIZE_EXPENDITURE` action if the expenditure was not created as part of a OneTxPayment diff --git a/apps/main-chain/src/handlers/expenditures/expenditureGlobalClaimDelaySet.ts b/apps/main-chain/src/handlers/expenditures/expenditureGlobalClaimDelaySet.ts index cba65bc01..1cfb806b5 100644 --- a/apps/main-chain/src/handlers/expenditures/expenditureGlobalClaimDelaySet.ts +++ b/apps/main-chain/src/handlers/expenditures/expenditureGlobalClaimDelaySet.ts @@ -1,24 +1,24 @@ import { BigNumber } from 'ethers'; -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { UpdateColonyDocument, UpdateColonyMutation, UpdateColonyMutationVariables, } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; export default async (event: ContractEvent): Promise => { const { contractAddress: colonyAddress } = event; const { globalClaimDelay } = event.args; const convertedGlobalClaimDelay = BigNumber.from(globalClaimDelay).toString(); - await mutate( - UpdateColonyDocument, - { - input: { - id: colonyAddress, - expendituresGlobalClaimDelay: convertedGlobalClaimDelay, - }, + await amplifyClient.mutate< + UpdateColonyMutation, + UpdateColonyMutationVariables + >(UpdateColonyDocument, { + input: { + id: colonyAddress, + expendituresGlobalClaimDelay: convertedGlobalClaimDelay, }, - ); + }); }; diff --git a/apps/main-chain/src/handlers/expenditures/expenditureLocked.ts b/apps/main-chain/src/handlers/expenditures/expenditureLocked.ts index 47c8a570a..85b7773bd 100644 --- a/apps/main-chain/src/handlers/expenditures/expenditureLocked.ts +++ b/apps/main-chain/src/handlers/expenditures/expenditureLocked.ts @@ -1,4 +1,4 @@ -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyActionType, ExpenditureStatus, @@ -7,15 +7,15 @@ import { UpdateExpenditureMutation, UpdateExpenditureMutationVariables, } from '@joincolony/graphql'; -import { ContractEvent, ContractEventsSignatures } from '~types'; +import { ContractEvent, ContractEventsSignatures } from '@joincolony/blocks'; import { getExpenditureDatabaseId, toNumber, transactionHasEvent, - verbose, writeActionFromEvent, } from '~utils'; import { sendExpenditureUpdateNotifications } from '~utils/notifications'; +import { verbose } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { contractAddress: colonyAddress } = event; @@ -34,15 +34,15 @@ export default async (event: ContractEvent): Promise => { colonyAddress, ); - await mutate( - UpdateExpenditureDocument, - { - input: { - id: databaseId, - status: ExpenditureStatus.Locked, - }, + await amplifyClient.mutate< + UpdateExpenditureMutation, + UpdateExpenditureMutationVariables + >(UpdateExpenditureDocument, { + input: { + id: databaseId, + status: ExpenditureStatus.Locked, }, - ); + }); /** * @NOTE: Only create a `LOCK_EXPENDITURE` action if the expenditure was not created as part of a OneTxPayment diff --git a/apps/main-chain/src/handlers/expenditures/expenditureMadeStaged.ts b/apps/main-chain/src/handlers/expenditures/expenditureMadeStaged.ts index 9053c9fb2..4f54855a8 100644 --- a/apps/main-chain/src/handlers/expenditures/expenditureMadeStaged.ts +++ b/apps/main-chain/src/handlers/expenditures/expenditureMadeStaged.ts @@ -1,13 +1,13 @@ -import { mutate } from '~amplifyClient'; -import { ExtensionEventListener } from '~eventListeners'; +import amplifyClient from '~amplifyClient'; import { ExpenditureType, UpdateExpenditureDocument, UpdateExpenditureMutation, UpdateExpenditureMutationVariables, } from '@joincolony/graphql'; -import { EventHandler } from '~types'; -import { getExpenditureDatabaseId, toNumber, verbose } from '~utils'; +import { getExpenditureDatabaseId, toNumber } from '~utils'; +import { verbose } from '@joincolony/utils'; +import { EventHandler, ExtensionEventListener } from '@joincolony/blocks'; export const handleExpenditureMadeStaged: EventHandler = async ( event, @@ -23,14 +23,14 @@ export const handleExpenditureMadeStaged: EventHandler = async ( } as staged`, ); - await mutate( - UpdateExpenditureDocument, - { - input: { - id: getExpenditureDatabaseId(colonyAddress, convertedExpenditureId), - type: ExpenditureType.Staged, - stagedExpenditureAddress: event.contractAddress, - }, + await amplifyClient.mutate< + UpdateExpenditureMutation, + UpdateExpenditureMutationVariables + >(UpdateExpenditureDocument, { + input: { + id: getExpenditureDatabaseId(colonyAddress, convertedExpenditureId), + type: ExpenditureType.Staged, + stagedExpenditureAddress: event.contractAddress, }, - ); + }); }; diff --git a/apps/main-chain/src/handlers/expenditures/expenditureMadeViaStake.ts b/apps/main-chain/src/handlers/expenditures/expenditureMadeViaStake.ts index 6191b90c2..856d598af 100644 --- a/apps/main-chain/src/handlers/expenditures/expenditureMadeViaStake.ts +++ b/apps/main-chain/src/handlers/expenditures/expenditureMadeViaStake.ts @@ -1,5 +1,4 @@ -import { mutate } from '~amplifyClient'; -import { ExtensionEventListener } from '~eventListeners'; +import amplifyClient from '~amplifyClient'; import { CreateUserStakeDocument, CreateUserStakeMutation, @@ -12,10 +11,11 @@ import { UpdateExpenditureMutationVariables, UserStakeType, } from '@joincolony/graphql'; -import { EventHandler } from '~types'; -import { getExpenditureDatabaseId, output, toNumber, verbose } from '~utils'; +import { getExpenditureDatabaseId, toNumber } from '~utils'; import { getUserStakeDatabaseId } from '~utils/stakes'; import { getExpenditureFromDB } from './helpers'; +import { output, verbose } from '@joincolony/utils'; +import { EventHandler, ExtensionEventListener } from '@joincolony/blocks'; export const handleExpenditureMadeViaStake: EventHandler = async ( event, @@ -45,41 +45,41 @@ export const handleExpenditureMadeViaStake: EventHandler = async ( const stakeDatabaseId = getUserStakeDatabaseId(creator, transactionHash); - await mutate( - UpdateExpenditureDocument, - { - input: { - id: databaseId, - isStaked: true, - userStakeId: stakeDatabaseId, - stakedExpenditureAddress: contractAddress, - }, + await amplifyClient.mutate< + UpdateExpenditureMutation, + UpdateExpenditureMutationVariables + >(UpdateExpenditureDocument, { + input: { + id: databaseId, + isStaked: true, + userStakeId: stakeDatabaseId, + stakedExpenditureAddress: contractAddress, }, - ); + }); - await mutate( - CreateUserStakeDocument, - { - input: { - id: stakeDatabaseId, - actionId: transactionHash, - amount: stake.toString(), - userAddress: creator, - colonyAddress, - isClaimed: false, - type: UserStakeType.StakedExpenditure, - }, + await amplifyClient.mutate< + CreateUserStakeMutation, + CreateUserStakeMutationVariables + >(CreateUserStakeDocument, { + input: { + id: stakeDatabaseId, + actionId: transactionHash, + amount: stake.toString(), + userAddress: creator, + colonyAddress, + isClaimed: false, + type: UserStakeType.StakedExpenditure, }, - ); + }); - await mutate( - UpdateColonyActionDocument, - { - input: { - id: transactionHash, - showInActionsList: true, - initiatorAddress: creator, - }, + await amplifyClient.mutate< + UpdateColonyActionMutation, + UpdateColonyActionMutationVariables + >(UpdateColonyActionDocument, { + input: { + id: transactionHash, + showInActionsList: true, + initiatorAddress: creator, }, - ); + }); }; diff --git a/apps/main-chain/src/handlers/expenditures/expenditurePayoutClaimed.ts b/apps/main-chain/src/handlers/expenditures/expenditurePayoutClaimed.ts index b86dff9a0..565473ba0 100644 --- a/apps/main-chain/src/handlers/expenditures/expenditurePayoutClaimed.ts +++ b/apps/main-chain/src/handlers/expenditures/expenditurePayoutClaimed.ts @@ -1,12 +1,10 @@ -import { ContractEvent, ContractEventsSignatures } from '~types'; +import { ContractEvent, ContractEventsSignatures } from '@joincolony/blocks'; import { getExpenditureDatabaseId, getUpdatedExpenditureBalances, insertAtIndex, - output, toNumber, transactionHasEvent, - verbose, } from '~utils'; import { ExpenditurePayout, @@ -15,11 +13,12 @@ import { UpdateExpenditureMutation, UpdateExpenditureMutationVariables, } from '@joincolony/graphql'; -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { getAmountWithFee, getNetworkInverseFee } from '~utils/networkFee'; import { getExpenditureFromDB } from './helpers'; import { sendExpenditureUpdateNotifications } from '~utils/notifications'; +import { output, verbose } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { contractAddress: colonyAddress } = event; @@ -90,16 +89,16 @@ export default async (event: ContractEvent): Promise => { verbose(`Payout claimed in expenditure with ID ${databaseId}`); - await mutate( - UpdateExpenditureDocument, - { - input: { - id: databaseId, - slots: updatedSlots, - balances: updatedBalances, - }, + await amplifyClient.mutate< + UpdateExpenditureMutation, + UpdateExpenditureMutationVariables + >(UpdateExpenditureDocument, { + input: { + id: databaseId, + slots: updatedSlots, + balances: updatedBalances, }, - ); + }); const hasOneTxPaymentEvent = await transactionHasEvent( event.transactionHash, diff --git a/apps/main-chain/src/handlers/expenditures/expenditurePayoutModifierSet.ts b/apps/main-chain/src/handlers/expenditures/expenditurePayoutModifierSet.ts index 7e271c700..64e60dfcf 100644 --- a/apps/main-chain/src/handlers/expenditures/expenditurePayoutModifierSet.ts +++ b/apps/main-chain/src/handlers/expenditures/expenditurePayoutModifierSet.ts @@ -1,13 +1,14 @@ -import { ContractEvent } from '~types'; -import { getExpenditureDatabaseId, output, toNumber, verbose } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; +import { getExpenditureDatabaseId, toNumber } from '~utils'; import { UpdateExpenditureDocument, UpdateExpenditureMutation, UpdateExpenditureMutationVariables, } from '@joincolony/graphql'; -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { getExpenditureFromDB, getUpdatedExpenditureSlots } from './helpers'; +import { output, verbose } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { contractAddress: colonyAddress } = event; @@ -38,13 +39,13 @@ export default async (event: ContractEvent): Promise => { `Payout modifier set for expenditure with ID ${convertedExpenditureId} in colony ${colonyAddress}`, ); - await mutate( - UpdateExpenditureDocument, - { - input: { - id: databaseId, - slots: updatedSlots, - }, + await amplifyClient.mutate< + UpdateExpenditureMutation, + UpdateExpenditureMutationVariables + >(UpdateExpenditureDocument, { + input: { + id: databaseId, + slots: updatedSlots, }, - ); + }); }; diff --git a/apps/main-chain/src/handlers/expenditures/expenditurePayoutSet.ts b/apps/main-chain/src/handlers/expenditures/expenditurePayoutSet.ts index 0fa52c6c3..2deecc425 100644 --- a/apps/main-chain/src/handlers/expenditures/expenditurePayoutSet.ts +++ b/apps/main-chain/src/handlers/expenditures/expenditurePayoutSet.ts @@ -1,10 +1,8 @@ -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; import { getCachedColonyClient, getExpenditureDatabaseId, - output, toNumber, - verbose, } from '~utils'; import { ExpenditurePayout, @@ -12,7 +10,7 @@ import { UpdateExpenditureMutation, UpdateExpenditureMutationVariables, } from '@joincolony/graphql'; -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { splitAmountAndFee } from '~utils/networkFee'; import { @@ -21,6 +19,7 @@ import { createEditExpenditureAction, NotEditActionError, } from './helpers'; +import { output, verbose } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { contractAddress: colonyAddress } = event; @@ -81,7 +80,7 @@ export default async (event: ContractEvent): Promise => { `Payout set for expenditure with ID ${convertedExpenditureId} in colony ${colonyAddress}`, ); - await mutate< + await amplifyClient.mutate< UpdateExpenditureMutation, UpdateExpenditureMutationVariables >(UpdateExpenditureDocument, { diff --git a/apps/main-chain/src/handlers/expenditures/expenditureRecipientSet.ts b/apps/main-chain/src/handlers/expenditures/expenditureRecipientSet.ts index a50f16111..3e5abff0c 100644 --- a/apps/main-chain/src/handlers/expenditures/expenditureRecipientSet.ts +++ b/apps/main-chain/src/handlers/expenditures/expenditureRecipientSet.ts @@ -1,15 +1,16 @@ -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyActionType, UpdateExpenditureDocument, UpdateExpenditureMutation, UpdateExpenditureMutationVariables, } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; -import { getExpenditureDatabaseId, output, toNumber, verbose } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; +import { getExpenditureDatabaseId, toNumber } from '~utils'; import { getExpenditureFromDB, getUpdatedExpenditureSlots } from './helpers'; import { sendMentionNotifications } from '~utils/notifications'; +import { output, verbose } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { contractAddress: colonyAddress } = event; @@ -42,15 +43,15 @@ export default async (event: ContractEvent): Promise => { `Recipient set for expenditure with ID ${convertedExpenditureId} in colony ${colonyAddress}`, ); - await mutate( - UpdateExpenditureDocument, - { - input: { - id: databaseId, - slots: updatedSlots, - }, + await amplifyClient.mutate< + UpdateExpenditureMutation, + UpdateExpenditureMutationVariables + >(UpdateExpenditureDocument, { + input: { + id: databaseId, + slots: updatedSlots, }, - ); + }); const mentionRecipients: string[] = []; updatedSlots.forEach((updatedSlot) => { diff --git a/apps/main-chain/src/handlers/expenditures/expenditureStakerPunished.ts b/apps/main-chain/src/handlers/expenditures/expenditureStakerPunished.ts index 8b308f16e..948f2a50e 100644 --- a/apps/main-chain/src/handlers/expenditures/expenditureStakerPunished.ts +++ b/apps/main-chain/src/handlers/expenditures/expenditureStakerPunished.ts @@ -1,8 +1,8 @@ -import { ExtensionEventListener } from '~eventListeners'; -import { EventHandler } from '~types'; -import { getExpenditureDatabaseId, toNumber, verbose } from '~utils'; +import { getExpenditureDatabaseId, toNumber } from '~utils'; import { updateExpenditureStake } from './helpers'; +import { verbose } from '@joincolony/utils'; +import { EventHandler, ExtensionEventListener } from '@joincolony/blocks'; export const handleExpenditureStakerPunished: EventHandler = async ( event, diff --git a/apps/main-chain/src/handlers/expenditures/expenditureStateChanged.ts b/apps/main-chain/src/handlers/expenditures/expenditureStateChanged.ts index 61c7a1acf..eb93c482e 100644 --- a/apps/main-chain/src/handlers/expenditures/expenditureStateChanged.ts +++ b/apps/main-chain/src/handlers/expenditures/expenditureStateChanged.ts @@ -1,16 +1,13 @@ -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { UpdateExpenditureDocument, UpdateExpenditureMutation, UpdateExpenditureMutationVariables, } from '@joincolony/graphql'; -import { EventHandler } from '~types'; import { getCachedColonyClient, getExpenditureDatabaseId, - output, toNumber, - verbose, } from '~utils'; import { getExpenditureFromDB, @@ -20,6 +17,8 @@ import { createEditExpenditureAction, NotEditActionError, } from './helpers'; +import { output, verbose } from '@joincolony/utils'; +import { EventHandler } from '@joincolony/blocks'; export const handleExpenditureStateChanged: EventHandler = async (event) => { const { contractAddress: colonyAddress } = event; @@ -70,7 +69,7 @@ export const handleExpenditureStateChanged: EventHandler = async (event) => { verbose(`State of expenditure with ID ${databaseId} changed`); if (!!updatedSlots || !!updatedStatus) { - await mutate< + await amplifyClient.mutate< UpdateExpenditureMutation, UpdateExpenditureMutationVariables >(UpdateExpenditureDocument, { diff --git a/apps/main-chain/src/handlers/expenditures/expenditureTransferred.ts b/apps/main-chain/src/handlers/expenditures/expenditureTransferred.ts index 6f9740982..77823c807 100644 --- a/apps/main-chain/src/handlers/expenditures/expenditureTransferred.ts +++ b/apps/main-chain/src/handlers/expenditures/expenditureTransferred.ts @@ -1,11 +1,12 @@ -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { UpdateExpenditureDocument, UpdateExpenditureMutation, UpdateExpenditureMutationVariables, } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; -import { getExpenditureDatabaseId, toNumber, verbose } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; +import { getExpenditureDatabaseId, toNumber } from '~utils'; +import { verbose } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { contractAddress: colonyAddress } = event; @@ -21,13 +22,13 @@ export default async (event: ContractEvent): Promise => { colonyAddress, ); - await mutate( - UpdateExpenditureDocument, - { - input: { - id: getExpenditureDatabaseId(colonyAddress, convertedExpenditureId), - ownerAddress: newOwnerAddress, - }, + await amplifyClient.mutate< + UpdateExpenditureMutation, + UpdateExpenditureMutationVariables + >(UpdateExpenditureDocument, { + input: { + id: getExpenditureDatabaseId(colonyAddress, convertedExpenditureId), + ownerAddress: newOwnerAddress, }, - ); + }); }; diff --git a/apps/main-chain/src/handlers/expenditures/helpers/createEditExpenditureAction.ts b/apps/main-chain/src/handlers/expenditures/helpers/createEditExpenditureAction.ts index 89934831f..e6950eec9 100644 --- a/apps/main-chain/src/handlers/expenditures/helpers/createEditExpenditureAction.ts +++ b/apps/main-chain/src/handlers/expenditures/helpers/createEditExpenditureAction.ts @@ -1,7 +1,7 @@ import { AnyColonyClient } from '@colony/colony-js'; import { utils } from 'ethers'; import { isEqual, omit } from 'lodash'; -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyActionType, ExpenditureFragment, @@ -13,8 +13,8 @@ import { UpdateExpenditureMutation, UpdateExpenditureMutationVariables, } from '@joincolony/graphql'; -import provider from '~provider'; -import { ContractEvent, ContractEventsSignatures } from '~types'; +import rpcProvider from '~provider'; +import { ContractEvent, ContractEventsSignatures } from '@joincolony/blocks'; import { checkActionExists, getExpenditureDatabaseId, @@ -84,7 +84,7 @@ export const createEditExpenditureAction = async ( convertedExpenditureId, ); - const logs = await provider.getLogs({ + const logs = await rpcProvider.getProviderInstance().getLogs({ fromBlock: blockNumber, toBlock: blockNumber, topics: [ @@ -198,16 +198,16 @@ export const createEditExpenditureAction = async ( } } - await mutate( - UpdateExpenditureDocument, - { - input: { - id: databaseId, - slots: updatedSlots, - status: updatedStatus, - }, + await amplifyClient.mutate< + UpdateExpenditureMutation, + UpdateExpenditureMutationVariables + >(UpdateExpenditureDocument, { + input: { + id: databaseId, + slots: updatedSlots, + status: updatedStatus, }, - ); + }); if (shouldCreateAction) { const { agent: initiatorAddress } = event.args; diff --git a/apps/main-chain/src/handlers/expenditures/helpers/decodeSetExpenditureState.ts b/apps/main-chain/src/handlers/expenditures/helpers/decodeSetExpenditureState.ts index 1d98730bd..4f847e8e6 100644 --- a/apps/main-chain/src/handlers/expenditures/helpers/decodeSetExpenditureState.ts +++ b/apps/main-chain/src/handlers/expenditures/helpers/decodeSetExpenditureState.ts @@ -14,7 +14,7 @@ import { EXPENDITURES_SLOT, EXPENDITURE_OWNER_AND_STATUS, } from '~constants'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; interface SetExpenditureStateParams { storageSlot: BigNumberish; diff --git a/apps/main-chain/src/handlers/expenditures/helpers/getExpenditure.ts b/apps/main-chain/src/handlers/expenditures/helpers/getExpenditure.ts index ea6d66b42..7ce8e3026 100644 --- a/apps/main-chain/src/handlers/expenditures/helpers/getExpenditure.ts +++ b/apps/main-chain/src/handlers/expenditures/helpers/getExpenditure.ts @@ -1,6 +1,6 @@ import { AnyColonyClient } from '@colony/colony-js'; -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { GetExpenditureDocument, GetExpenditureQuery, @@ -14,7 +14,7 @@ import { getCachedColonyClient } from '~utils'; export const getExpenditureFromDB = async ( expenditureDatabaseId: string, ): Promise => { - const response = await query< + const response = await amplifyClient.query< GetExpenditureQuery, GetExpenditureQueryVariables >(GetExpenditureDocument, { @@ -52,7 +52,7 @@ export const getExpenditure = async ( export const getStreamingPaymentFromDB = async ( paymentDatabaseId: string, ): Promise => { - const response = await query< + const response = await amplifyClient.query< GetStreamingPaymentQuery, GetStreamingPaymentQueryVariables >(GetStreamingPaymentDocument, { diff --git a/apps/main-chain/src/handlers/expenditures/helpers/updateExpenditureStake.ts b/apps/main-chain/src/handlers/expenditures/helpers/updateExpenditureStake.ts index 31120c747..92e090ada 100644 --- a/apps/main-chain/src/handlers/expenditures/helpers/updateExpenditureStake.ts +++ b/apps/main-chain/src/handlers/expenditures/helpers/updateExpenditureStake.ts @@ -1,4 +1,4 @@ -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { UpdateUserStakeDocument, UpdateUserStakeMutation, @@ -6,7 +6,7 @@ import { UpdateUserStakeInput, } from '@joincolony/graphql'; import { getExpenditureFromDB } from './getExpenditure'; -import { output, verbose } from '~utils'; +import { output, verbose } from '@joincolony/utils'; export const updateExpenditureStake = async ( expenditureDatabaseId: string, @@ -21,15 +21,15 @@ export const updateExpenditureStake = async ( return; } - await mutate( - UpdateUserStakeDocument, - { - input: { - id: expenditure.userStakeId, - ...fieldsToUpdate, - }, + await amplifyClient.mutate< + UpdateUserStakeMutation, + UpdateUserStakeMutationVariables + >(UpdateUserStakeDocument, { + input: { + id: expenditure.userStakeId, + ...fieldsToUpdate, }, - ); + }); verbose( `Updated stake with ID ${expenditure.userStakeId} for expenditure ${expenditureDatabaseId}`, diff --git a/apps/main-chain/src/handlers/expenditures/paymentTokenUpdated.ts b/apps/main-chain/src/handlers/expenditures/paymentTokenUpdated.ts index f44663da7..2a32909a6 100644 --- a/apps/main-chain/src/handlers/expenditures/paymentTokenUpdated.ts +++ b/apps/main-chain/src/handlers/expenditures/paymentTokenUpdated.ts @@ -1,5 +1,5 @@ -import { getExpenditureDatabaseId, toNumber, verbose } from '~utils'; -import { mutate } from '~amplifyClient'; +import { getExpenditureDatabaseId, toNumber } from '~utils'; +import amplifyClient from '~amplifyClient'; import { UpdateStreamingPaymentDocument, UpdateStreamingPaymentMutation, @@ -7,8 +7,8 @@ import { } from '@joincolony/graphql'; import { getStreamingPaymentFromDB } from './helpers'; -import { EventHandler } from '~types'; -import { ExtensionEventListener } from '~eventListeners'; +import { verbose } from '@joincolony/utils'; +import { EventHandler, ExtensionEventListener } from '@joincolony/blocks'; export const handlePaymentTokenUpdated: EventHandler = async ( event, @@ -39,7 +39,7 @@ export const handlePaymentTokenUpdated: EventHandler = async ( verbose(`Payment token updated for streaming payment with ID ${databaseId}`); - await mutate< + await amplifyClient.mutate< UpdateStreamingPaymentMutation, UpdateStreamingPaymentMutationVariables >(UpdateStreamingPaymentDocument, { diff --git a/apps/main-chain/src/handlers/expenditures/stagedPaymentReleased.ts b/apps/main-chain/src/handlers/expenditures/stagedPaymentReleased.ts index b5e068e50..d4adab270 100644 --- a/apps/main-chain/src/handlers/expenditures/stagedPaymentReleased.ts +++ b/apps/main-chain/src/handlers/expenditures/stagedPaymentReleased.ts @@ -1,9 +1,11 @@ import { utils } from 'ethers'; -import { ExtensionEventListener } from '~eventListeners'; import { ColonyActionType } from '@joincolony/graphql'; -import { getInterfaceByListener } from '~interfaces'; -import provider from '~provider'; -import { ContractEventsSignatures, EventHandler } from '~types'; +import rpcProvider from '~provider'; +import { + ContractEventsSignatures, + EventHandler, + ExtensionEventListener, +} from '@joincolony/blocks'; import { checkActionExists, getCachedColonyClient, @@ -12,6 +14,7 @@ import { toNumber, writeActionFromEvent, } from '~utils'; +import eventManager from '~eventManager'; export const handleStagedPaymentReleased: EventHandler = async ( event, @@ -41,13 +44,13 @@ export const handleStagedPaymentReleased: EventHandler = async ( const releasedSlotIds = []; - const logs = await provider.getLogs({ + const logs = await rpcProvider.getProviderInstance().getLogs({ fromBlock: blockNumber, toBlock: blockNumber, topics: [utils.id(ContractEventsSignatures.StagedPaymentReleased)], }); - const iface = getInterfaceByListener(listener); + const iface = eventManager.getInterfaceByListener(listener); if (!iface) { return; } diff --git a/apps/main-chain/src/handlers/expenditures/stakeFractionSet.ts b/apps/main-chain/src/handlers/expenditures/stakeFractionSet.ts index 7ac1c18ee..02586b6b9 100644 --- a/apps/main-chain/src/handlers/expenditures/stakeFractionSet.ts +++ b/apps/main-chain/src/handlers/expenditures/stakeFractionSet.ts @@ -1,9 +1,9 @@ import { constants } from 'ethers'; import { NotificationType } from '@joincolony/graphql'; import networkClient from '~networkClient'; -import { EventHandler } from '~types'; import { updateExtension } from '~utils/extensions/updateExtension'; import { sendExtensionUpdateNotifications } from '~utils/notifications'; +import { EventHandler } from '@joincolony/blocks'; export const handleStakeFractionSet: EventHandler = async ( event, diff --git a/apps/main-chain/src/handlers/expenditures/stakeReclaimed.ts b/apps/main-chain/src/handlers/expenditures/stakeReclaimed.ts index abd393587..4f8b130ee 100644 --- a/apps/main-chain/src/handlers/expenditures/stakeReclaimed.ts +++ b/apps/main-chain/src/handlers/expenditures/stakeReclaimed.ts @@ -1,8 +1,8 @@ -import { ExtensionEventListener } from '~eventListeners'; -import { EventHandler } from '~types'; -import { getExpenditureDatabaseId, toNumber, verbose } from '~utils'; +import { getExpenditureDatabaseId, toNumber } from '~utils'; import { updateExpenditureStake } from './helpers'; +import { verbose } from '@joincolony/utils'; +import { EventHandler, ExtensionEventListener } from '@joincolony/blocks'; export const handleStakeReclaimed: EventHandler = async (event, listener) => { const { expenditureId } = event.args; diff --git a/apps/main-chain/src/handlers/expenditures/streamingPaymentCreated.ts b/apps/main-chain/src/handlers/expenditures/streamingPaymentCreated.ts index 5e2853274..8cb3272f8 100644 --- a/apps/main-chain/src/handlers/expenditures/streamingPaymentCreated.ts +++ b/apps/main-chain/src/handlers/expenditures/streamingPaymentCreated.ts @@ -1,17 +1,16 @@ -import { mutate } from '~amplifyClient'; -import { ExtensionEventListener } from '~eventListeners'; +import amplifyClient from '~amplifyClient'; import { CreateStreamingPaymentDocument, CreateStreamingPaymentMutation, CreateStreamingPaymentMutationVariables, } from '@joincolony/graphql'; -import { EventHandler } from '~types'; import { getExpenditureDatabaseId, getStreamingPaymentsClient, toNumber, - verbose, } from '~utils'; +import { verbose } from '@joincolony/utils'; +import { EventHandler, ExtensionEventListener } from '@joincolony/blocks'; export const handleStreamingPaymentCreated: EventHandler = async ( event, @@ -49,7 +48,7 @@ export const handleStreamingPaymentCreated: EventHandler = async ( verbose(`Streaming payment with ID ${databaseId} created`); - await mutate< + await amplifyClient.mutate< CreateStreamingPaymentMutation, CreateStreamingPaymentMutationVariables >(CreateStreamingPaymentDocument, { diff --git a/apps/main-chain/src/handlers/extensions/extensionAddedToNetwork.ts b/apps/main-chain/src/handlers/extensions/extensionAddedToNetwork.ts index 865981744..6f8d5a46d 100644 --- a/apps/main-chain/src/handlers/extensions/extensionAddedToNetwork.ts +++ b/apps/main-chain/src/handlers/extensions/extensionAddedToNetwork.ts @@ -1,4 +1,4 @@ -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; import { writeExtensionVersionFromEvent } from '~utils'; export default async (event: ContractEvent): Promise => { diff --git a/apps/main-chain/src/handlers/extensions/extensionDeprecated.ts b/apps/main-chain/src/handlers/extensions/extensionDeprecated.ts index 36a7feb2e..38a3b16d8 100644 --- a/apps/main-chain/src/handlers/extensions/extensionDeprecated.ts +++ b/apps/main-chain/src/handlers/extensions/extensionDeprecated.ts @@ -1,5 +1,5 @@ import { constants } from 'ethers'; -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { GetColonyExtensionByHashAndColonyDocument, GetColonyExtensionByHashAndColonyQuery, @@ -7,8 +7,8 @@ import { NotificationType, } from '@joincolony/graphql'; import networkClient from '~networkClient'; -import { ContractEvent } from '~types'; -import { verbose } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; +import { verbose } from '@joincolony/utils'; import { updateExtension } from '~utils/extensions/updateExtension'; import { sendExtensionUpdateNotifications } from '~utils/notifications'; @@ -38,7 +38,7 @@ export default async (event: ContractEvent): Promise => { }); const { data } = - (await query< + (await amplifyClient.query< GetColonyExtensionByHashAndColonyQuery, GetColonyExtensionByHashAndColonyQueryVariables >(GetColonyExtensionByHashAndColonyDocument, { diff --git a/apps/main-chain/src/handlers/extensions/extensionInitialised.ts b/apps/main-chain/src/handlers/extensions/extensionInitialised.ts index 7c773b3ea..3b9dbdd1e 100644 --- a/apps/main-chain/src/handlers/extensions/extensionInitialised.ts +++ b/apps/main-chain/src/handlers/extensions/extensionInitialised.ts @@ -1,7 +1,7 @@ import { Extension, getExtensionHash } from '@colony/colony-js'; -import { ContractEvent } from '~types'; -import { verbose, addVotingReputationParamsToDB } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; +import { addVotingReputationParamsToDB } from '~utils'; import { setupListenersForStakedExpenditure, setupMotionsListeners, @@ -11,6 +11,7 @@ import networkClient from '~networkClient'; import { constants } from 'ethers'; import { updateExtension } from '~utils/extensions/updateExtension'; import { NotificationType } from '@joincolony/graphql'; +import { verbose } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { contractAddress: extensionAddress, transactionHash } = event; diff --git a/apps/main-chain/src/handlers/extensions/extensionInstalled.ts b/apps/main-chain/src/handlers/extensions/extensionInstalled.ts index 84ed3855e..b26b31c75 100644 --- a/apps/main-chain/src/handlers/extensions/extensionInstalled.ts +++ b/apps/main-chain/src/handlers/extensions/extensionInstalled.ts @@ -9,7 +9,7 @@ import { import { handleMultiSigInstalled } from '~eventListeners/extension/multiSig'; import { setupListenersForStreamingPayments } from '~eventListeners/extension/streamingPayments'; import networkClient from '~networkClient'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; import { writeExtensionFromEvent } from '~utils'; import { updateExtensionCount } from '~utils/extensions'; diff --git a/apps/main-chain/src/handlers/extensions/extensionUninstalled.ts b/apps/main-chain/src/handlers/extensions/extensionUninstalled.ts index 239d519a6..f60b79136 100644 --- a/apps/main-chain/src/handlers/extensions/extensionUninstalled.ts +++ b/apps/main-chain/src/handlers/extensions/extensionUninstalled.ts @@ -4,7 +4,7 @@ import { removeExtensionEventListeners } from '~eventListeners'; import { handleMultiSigUninstalled } from '~eventListeners/extension/multiSig'; import { NotificationType } from '@joincolony/graphql'; import networkClient from '~networkClient'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; import { deleteExtensionFromEvent } from '~utils'; import { sendExtensionUpdateNotifications } from '~utils/notifications'; diff --git a/apps/main-chain/src/handlers/extensions/extensionUpgraded.ts b/apps/main-chain/src/handlers/extensions/extensionUpgraded.ts index 22a6a74b6..5d84a2daf 100644 --- a/apps/main-chain/src/handlers/extensions/extensionUpgraded.ts +++ b/apps/main-chain/src/handlers/extensions/extensionUpgraded.ts @@ -1,12 +1,13 @@ -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { GetColonyExtensionByHashAndColonyDocument, GetColonyExtensionByHashAndColonyQuery, GetColonyExtensionByHashAndColonyQueryVariables, } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; -import { toNumber, verbose } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; +import { toNumber } from '~utils'; import { updateExtension } from '~utils/extensions/updateExtension'; +import { verbose } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { extensionId: extensionHash, colony, version } = event.args; @@ -22,7 +23,7 @@ export default async (event: ContractEvent): Promise => { ); const { data } = - (await query< + (await amplifyClient.query< GetColonyExtensionByHashAndColonyQuery, GetColonyExtensionByHashAndColonyQueryVariables >(GetColonyExtensionByHashAndColonyDocument, { diff --git a/apps/main-chain/src/handlers/metadataDelta/handlers/addVerifiedMembers.ts b/apps/main-chain/src/handlers/metadataDelta/handlers/addVerifiedMembers.ts index a01719d40..0285eb5c0 100644 --- a/apps/main-chain/src/handlers/metadataDelta/handlers/addVerifiedMembers.ts +++ b/apps/main-chain/src/handlers/metadataDelta/handlers/addVerifiedMembers.ts @@ -1,6 +1,6 @@ import { Id } from '@colony/colony-js'; import { utils } from 'ethers'; -import { mutate, query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyActionType, GetColonyContributorDocument, @@ -10,7 +10,7 @@ import { UpdateColonyContributorMutation, UpdateColonyContributorMutationVariables, } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; import { NotificationCategory } from '~types/notifications'; import { AddVerifiedMembersOperation, @@ -41,7 +41,7 @@ export const handleAddVerifiedMembers = async ( return; } - const item = await query< + const item = await amplifyClient.query< GetColonyContributorQuery, GetColonyContributorQueryVariables >(GetColonyContributorDocument, { @@ -67,7 +67,7 @@ export const handleAddVerifiedMembers = async ( return; } - await mutate< + await amplifyClient.mutate< UpdateColonyContributorMutation, UpdateColonyContributorMutationVariables >(UpdateColonyContributorDocument, { diff --git a/apps/main-chain/src/handlers/metadataDelta/handlers/manageTokens.ts b/apps/main-chain/src/handlers/metadataDelta/handlers/manageTokens.ts index 196e27c54..f1bcef270 100644 --- a/apps/main-chain/src/handlers/metadataDelta/handlers/manageTokens.ts +++ b/apps/main-chain/src/handlers/metadataDelta/handlers/manageTokens.ts @@ -1,6 +1,6 @@ import { Id } from '@colony/colony-js'; import { ColonyActionType } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; import { NotificationCategory } from '~types/notifications'; import { ManageTokensOperation, diff --git a/apps/main-chain/src/handlers/metadataDelta/handlers/removeVerifiedMembers.ts b/apps/main-chain/src/handlers/metadataDelta/handlers/removeVerifiedMembers.ts index 7b9f40bb8..8972fcc6d 100644 --- a/apps/main-chain/src/handlers/metadataDelta/handlers/removeVerifiedMembers.ts +++ b/apps/main-chain/src/handlers/metadataDelta/handlers/removeVerifiedMembers.ts @@ -1,6 +1,6 @@ import { Id } from '@colony/colony-js'; import { utils } from 'ethers'; -import { mutate, query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyActionType, GetColonyContributorDocument, @@ -10,7 +10,7 @@ import { UpdateColonyContributorMutation, UpdateColonyContributorMutationVariables, } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; import { NotificationCategory } from '~types/notifications'; import { getDomainDatabaseId, @@ -38,7 +38,7 @@ export const handleRemoveVerifiedMembers = async ( return; } - const item = await query< + const item = await amplifyClient.query< GetColonyContributorQuery, GetColonyContributorQueryVariables >(GetColonyContributorDocument, { @@ -50,7 +50,7 @@ export const handleRemoveVerifiedMembers = async ( return; } - await mutate< + await amplifyClient.mutate< UpdateColonyContributorMutation, UpdateColonyContributorMutationVariables >(UpdateColonyContributorDocument, { diff --git a/apps/main-chain/src/handlers/metadataDelta/metadataDelta.ts b/apps/main-chain/src/handlers/metadataDelta/metadataDelta.ts index 396f287e9..2089290e3 100644 --- a/apps/main-chain/src/handlers/metadataDelta/metadataDelta.ts +++ b/apps/main-chain/src/handlers/metadataDelta/metadataDelta.ts @@ -1,14 +1,14 @@ -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; import { isAddVerifiedMembersOperation, isManageTokensOperation, isRemoveVerifiedMembersOperation, parseMetadataDeltaOperation, - verbose, } from '~utils'; import { handleAddVerifiedMembers } from './handlers/addVerifiedMembers'; import { handleRemoveVerifiedMembers } from './handlers/removeVerifiedMembers'; import { handleManageTokens } from './handlers/manageTokens'; +import { verbose } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const operationString = event.args.metadata; diff --git a/apps/main-chain/src/handlers/motions/helpers.ts b/apps/main-chain/src/handlers/motions/helpers.ts index 25c6df409..e48a930b8 100644 --- a/apps/main-chain/src/handlers/motions/helpers.ts +++ b/apps/main-chain/src/handlers/motions/helpers.ts @@ -1,5 +1,4 @@ import { BigNumber } from 'ethers'; -import { mutate, query } from '~amplifyClient'; import { ColonyActionType, ColonyMotion, @@ -13,7 +12,7 @@ import { UpdateColonyMotionDocument, } from '@joincolony/graphql'; import { MotionSide, MotionVote } from '~types'; -import { verbose, output } from '~utils'; +import { output, verbose } from '@joincolony/utils'; import { getActionByMotionId } from '~utils/actions'; import { updateDecisionInDB } from '~utils/decisions'; import { @@ -21,6 +20,7 @@ import { sendMentionNotifications, sendMotionNotifications, } from '~utils/notifications'; +import amplifyClient from '~amplifyClient'; export * from './motionStaked/helpers'; @@ -32,7 +32,7 @@ export const updateMotionInDB = async ( newMotionMessages?: CreateMotionMessageInput[], showInActionsList?: boolean, ): Promise => { - await mutate(UpdateColonyMotionDocument, { + await amplifyClient.mutate(UpdateColonyMotionDocument, { input: { ...motionData, }, @@ -40,7 +40,7 @@ export const updateMotionInDB = async ( if (newMotionMessages?.length) { for (const message of newMotionMessages) { - await mutate(CreateMotionMessageDocument, { + await amplifyClient.mutate(CreateMotionMessageDocument, { input: { ...message, }, @@ -56,7 +56,7 @@ export const updateMotionInDB = async ( 'Could not find the action in the db. This is a bug and needs investigating.', ); } else { - await mutate(UpdateColonyActionDocument, { + await amplifyClient.mutate(UpdateColonyActionDocument, { input: { id: colonyAction.id, showInActionsList, @@ -151,12 +151,12 @@ export const getMotionFromDB = async ( databaseMotionId: string, ): Promise => { const { data } = - (await query( - GetColonyMotionDocument, - { - id: databaseMotionId, - }, - )) ?? {}; + (await amplifyClient.query< + GetColonyMotionQuery, + GetColonyMotionQueryVariables + >(GetColonyMotionDocument, { + id: databaseMotionId, + })) ?? {}; const motion = data?.getColonyMotion; diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/addDomain.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/addDomain.ts index 8d96006be..3204b3fa5 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/addDomain.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/addDomain.ts @@ -1,7 +1,8 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, motionNameMapping } from '~types'; +import { motionNameMapping } from '~types'; import { getPendingMetadataDatabaseId } from '~utils'; import { createMotionInDB } from '../helpers'; +import { ContractEvent } from '@joincolony/blocks'; export const handleAddDomainMotion = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/editColony.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/editColony.ts index 233e86400..6b8c36b99 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/editColony.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/editColony.ts @@ -1,7 +1,8 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, motionNameMapping } from '~types'; +import { motionNameMapping } from '~types'; import { getPendingMetadataDatabaseId } from '~utils'; import { createMotionInDB } from '../helpers'; +import { ContractEvent } from '@joincolony/blocks'; export const handleEditColonyMotion = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/editDomain.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/editDomain.ts index dbea4bc41..4dd652512 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/editDomain.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/editDomain.ts @@ -1,7 +1,8 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, motionNameMapping } from '~types'; +import { motionNameMapping } from '~types'; import { getDomainDatabaseId, getPendingMetadataDatabaseId } from '~utils'; import { createMotionInDB } from '../helpers'; +import { ContractEvent } from '@joincolony/blocks'; export const handleEditDomainMotion = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/expenditures/cancelExpenditureViaArbitration.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/expenditures/cancelExpenditureViaArbitration.ts index 50b424aff..4f60d96a0 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/expenditures/cancelExpenditureViaArbitration.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/expenditures/cancelExpenditureViaArbitration.ts @@ -1,11 +1,12 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, motionNameMapping } from '~types'; +import { motionNameMapping } from '~types'; import { createMotionInDB } from '../../helpers'; import { getDomainDatabaseId, getExpenditureDatabaseId, toNumber, } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; export default async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/expenditures/cancelStakedExpenditures.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/expenditures/cancelStakedExpenditures.ts index 35fd79b5c..00100ab54 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/expenditures/cancelStakedExpenditures.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/expenditures/cancelStakedExpenditures.ts @@ -1,11 +1,12 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, motionNameMapping } from '~types'; +import { motionNameMapping } from '~types'; import { createMotionInDB } from '../../helpers'; import { getDomainDatabaseId, getExpenditureDatabaseId, toNumber, } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; export default async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/expenditures/finalizeExpenditureViaArbitration.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/expenditures/finalizeExpenditureViaArbitration.ts index 50b424aff..4f60d96a0 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/expenditures/finalizeExpenditureViaArbitration.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/expenditures/finalizeExpenditureViaArbitration.ts @@ -1,11 +1,12 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, motionNameMapping } from '~types'; +import { motionNameMapping } from '~types'; import { createMotionInDB } from '../../helpers'; import { getDomainDatabaseId, getExpenditureDatabaseId, toNumber, } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; export default async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/expenditures/releaseStagedPaymentViaArbitration.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/expenditures/releaseStagedPaymentViaArbitration.ts index 4decaf6f9..78ff1d027 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/expenditures/releaseStagedPaymentViaArbitration.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/expenditures/releaseStagedPaymentViaArbitration.ts @@ -1,11 +1,12 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, motionNameMapping } from '~types'; +import { motionNameMapping } from '~types'; import { createMotionInDB } from '../../helpers'; import { getDomainDatabaseId, getExpenditureDatabaseId, toNumber, } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; export default async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/makeArbitraryTransactions.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/makeArbitraryTransactions.ts index ef77cc9dd..786130f3c 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/makeArbitraryTransactions.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/makeArbitraryTransactions.ts @@ -1,9 +1,10 @@ import { TransactionDescription } from 'ethers/lib/utils'; import { Id } from '@colony/colony-js'; -import { ContractEvent, motionNameMapping } from '~types'; +import { motionNameMapping } from '~types'; import { getDomainDatabaseId } from '~utils'; import { createMotionInDB } from '../helpers'; +import { ContractEvent } from '@joincolony/blocks'; export const handleMakeArbitraryTransactionsMotion = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/metadataDelta.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/metadataDelta.ts index b2c60fb18..b38d0e48a 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/metadataDelta.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/metadataDelta.ts @@ -1,15 +1,15 @@ import { TransactionDescription } from 'ethers/lib/utils'; import { ColonyActionType } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; import { isAddVerifiedMembersOperation, isManageTokensOperation, isRemoveVerifiedMembersOperation, parseMetadataDeltaOperation, - verbose, } from '~utils'; import { createMotionInDB } from '../helpers'; import { manageTokensMotionHandler } from './metadataDeltaHandlers/manageTokens'; +import { verbose } from '@joincolony/utils'; export const handleMetadataDeltaMotion = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/metadataDeltaHandlers/manageTokens.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/metadataDeltaHandlers/manageTokens.ts index e67d53d09..5ffa35578 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/metadataDeltaHandlers/manageTokens.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/metadataDeltaHandlers/manageTokens.ts @@ -5,7 +5,7 @@ import { } from '~utils'; import { createMotionInDB } from '../../helpers'; import { ColonyActionType } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; export const manageTokensMotionHandler = async ({ colonyAddress, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/mintTokens.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/mintTokens.ts index 6c651334b..8e9c2b047 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/mintTokens.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/mintTokens.ts @@ -1,7 +1,8 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, motionNameMapping } from '~types'; +import { motionNameMapping } from '~types'; import { getColonyTokenAddress, getDomainDatabaseId } from '~utils'; import { createMotionInDB } from '../helpers'; +import { ContractEvent } from '@joincolony/blocks'; export const handleMintTokensMotion = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/moveFunds.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/moveFunds.ts index 49a0688d5..1ee27f88d 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/moveFunds.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/moveFunds.ts @@ -1,7 +1,7 @@ import { TransactionDescription } from 'ethers/lib/utils'; import { BigNumber } from 'ethers'; -import { ContractEvent, motionNameMapping } from '~types'; +import { motionNameMapping } from '~types'; import { getCachedColonyClient, getDomainDatabaseId, @@ -11,6 +11,7 @@ import { } from '~utils'; import { createMotionInDB } from '../helpers'; +import { ContractEvent } from '@joincolony/blocks'; export const handleMoveFundsMotion = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/multicall/multicall.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/multicall/multicall.ts index f566f50c0..82c817673 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/multicall/multicall.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/multicall/multicall.ts @@ -1,8 +1,9 @@ import { TransactionDescription } from 'ethers/lib/utils'; import { utils } from 'ethers'; -import { getCachedColonyClient, output, parseFunctionData } from '~utils'; -import { ContractEvent } from '~types'; +import { getCachedColonyClient, parseFunctionData } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; import { multicallHandlers } from './multicallHandlers'; +import { output } from '@joincolony/utils'; /** * @NOTE: This is a rather rudimentary way of handling multicall motions diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/multicall/multicallHandlers/fundExpenditureMotion.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/multicall/multicallHandlers/fundExpenditureMotion.ts index 4165d5f78..34c67fe96 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/multicall/multicallHandlers/fundExpenditureMotion.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/multicall/multicallHandlers/fundExpenditureMotion.ts @@ -1,4 +1,4 @@ -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyActionType, ExpenditureFundingItem, @@ -30,7 +30,7 @@ export const fundExpenditureMotionHandler: MulticallHandler = async ({ // This means if the multicall funds multiple expenditures, we will only create a motion for the first one const targetPotId = decodedFunctions[0]?.args._toPot; - const response = await query< + const response = await amplifyClient.query< GetExpenditureByNativeFundingPotIdAndColonyQuery, GetExpenditureByNativeFundingPotIdAndColonyQueryVariables >(GetExpenditureByNativeFundingPotIdAndColonyDocument, { diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/multicall/multicallHandlers/types.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/multicall/multicallHandlers/types.ts index 4d2750d37..0241ac0ba 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/multicall/multicallHandlers/types.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/multicall/multicallHandlers/types.ts @@ -1,5 +1,5 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; interface MulticallHandlerParams { colonyAddress: string; diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/networkUpgrade.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/networkUpgrade.ts index 063c1383c..aa0126512 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/networkUpgrade.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/networkUpgrade.ts @@ -1,9 +1,10 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, motionNameMapping } from '~types'; +import { motionNameMapping } from '~types'; import { toNumber } from '~utils'; import { createMotionInDB } from '../helpers'; +import { ContractEvent } from '@joincolony/blocks'; export const handleNetworkUpgradeMotion = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/payment.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/payment.ts index c0fd683fd..2db463457 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/payment.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/payment.ts @@ -1,12 +1,13 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, motionNameMapping } from '~types'; +import { motionNameMapping } from '~types'; import { getDomainDatabaseId, toNumber } from '~utils'; import { ColonyActionType } from '@joincolony/graphql'; import { MultiPayment } from '~handlers/actions/oneTxPayment'; import { createMotionInDB } from '../helpers'; +import { ContractEvent } from '@joincolony/blocks'; export const handlePaymentMotion = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/reputation.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/reputation.ts index 643fd06a4..691f01b8d 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/reputation.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/reputation.ts @@ -1,8 +1,9 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, motionNameMapping } from '~types'; +import { motionNameMapping } from '~types'; import { getDomainDatabaseId } from '~utils'; import { createMotionInDB } from '../helpers'; +import { ContractEvent } from '@joincolony/blocks'; export const handleDomainEditReputationMotion = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/setUserRoles.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/setUserRoles.ts index 85cb0fea9..b9510fe29 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/setUserRoles.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/setUserRoles.ts @@ -1,7 +1,7 @@ import { TransactionDescription } from 'ethers/lib/utils'; import { constants } from 'ethers'; -import { ContractEvent, motionNameMapping } from '~types'; +import { motionNameMapping } from '~types'; import { getColonyRolesDatabaseId, getDomainDatabaseId, @@ -9,6 +9,7 @@ import { } from '~utils'; import { createMotionInDB } from '../helpers'; +import { ContractEvent } from '@joincolony/blocks'; export const handleSetUserRolesMotion = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/simpleDecision.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/simpleDecision.ts index 0326c4668..7d88b9d65 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/simpleDecision.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/simpleDecision.ts @@ -1,8 +1,9 @@ -import { ContractEvent, motionNameMapping } from '~types'; +import { motionNameMapping } from '~types'; import { SimpleTransactionDescription } from '~utils'; import { getColonyDecisionId } from '~utils/decisions'; import { createMotionInDB } from '../helpers'; +import { ContractEvent } from '@joincolony/blocks'; export const handleSimpleDecisionMotion = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/handlers/unlockToken.ts b/apps/main-chain/src/handlers/motions/motionCreated/handlers/unlockToken.ts index 8ff70a8c4..dc9ed6296 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/handlers/unlockToken.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/handlers/unlockToken.ts @@ -1,8 +1,9 @@ import { Id } from '@colony/colony-js'; import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, motionNameMapping } from '~types'; +import { motionNameMapping } from '~types'; import { getColonyTokenAddress, getDomainDatabaseId } from '~utils'; import { createMotionInDB } from '../helpers'; +import { ContractEvent } from '@joincolony/blocks'; export const handleUnlockTokenMotion = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/motions/motionCreated/helpers.ts b/apps/main-chain/src/handlers/motions/motionCreated/helpers.ts index 664ce9594..50837c878 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/helpers.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/helpers.ts @@ -1,13 +1,13 @@ import { BigNumber } from 'ethers'; import { AnyVotingReputationClient } from '@colony/colony-js'; -import { ContractEvent, MotionEvents } from '~types'; +import { MotionEvents } from '~types'; import { createColonyAction, getDomainDatabaseId, getVotingClient, } from '~utils'; -import { GraphQLFnReturn, mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyMotion, CreateColonyActionInput, @@ -28,6 +28,8 @@ import { getUserMinStake, getMessageKey, } from '../helpers'; +import { type GraphQLFnReturn } from '@joincolony/clients'; +import { ContractEvent } from '@joincolony/blocks'; interface GetMotionDataArgs { transactionHash: string; @@ -140,20 +142,20 @@ const getInitialMotionMessage = async ( const createColonyMotion = async ( motionData: CreateColonyMotionInput, ): Promise => { - await mutate( - CreateColonyMotionDocument, - { - input: { - ...motionData, - }, + await amplifyClient.mutate< + CreateColonyMotionMutation, + CreateColonyMotionMutationVariables + >(CreateColonyMotionDocument, { + input: { + ...motionData, }, - ); + }); }; const createMotionMessage = async ( initialMotionMessage: CreateMotionMessageInput, ): Promise => { - await mutate< + await amplifyClient.mutate< CreateMotionMessageMutation, CreateMotionMessageMutationVariables >(CreateMotionMessageDocument, { diff --git a/apps/main-chain/src/handlers/motions/motionCreated/motionCreated.ts b/apps/main-chain/src/handlers/motions/motionCreated/motionCreated.ts index d42c18a6f..dc4ed77a5 100644 --- a/apps/main-chain/src/handlers/motions/motionCreated/motionCreated.ts +++ b/apps/main-chain/src/handlers/motions/motionCreated/motionCreated.ts @@ -1,14 +1,12 @@ import { utils } from 'ethers'; -import { ColonyOperations, EventHandler } from '~types'; +import { ColonyOperations } from '~types'; import { getCachedColonyClient, getStakedExpenditureClient, getStagedExpenditureClient, getOneTxPaymentClient, getVotingClient, - verbose, - output, SimpleTransactionDescription, parseMotionAction, } from '~utils'; @@ -32,7 +30,8 @@ import { handleFinalizeExpenditureViaArbitrationMotion, handleReleaseStagedPaymentViaArbitration, } from './handlers'; -import { ExtensionEventListener } from '~eventListeners'; +import { output, verbose } from '@joincolony/utils'; +import { EventHandler, ExtensionEventListener } from '@joincolony/blocks'; export const handleMotionCreated: EventHandler = async ( event, diff --git a/apps/main-chain/src/handlers/motions/motionEventSet/index.ts b/apps/main-chain/src/handlers/motions/motionEventSet/index.ts index a1870dba4..36b99f088 100644 --- a/apps/main-chain/src/handlers/motions/motionEventSet/index.ts +++ b/apps/main-chain/src/handlers/motions/motionEventSet/index.ts @@ -1,6 +1,5 @@ -import { ExtensionEventListener } from '~eventListeners'; -import { EventHandler } from '~types'; -import { verbose, getVotingClient } from '~utils'; +import { ExtensionEventListener, EventHandler } from '@joincolony/blocks'; +import { getVotingClient } from '~utils'; import { getBlockChainTimestampISODate } from '~utils/dates'; import { @@ -8,6 +7,7 @@ import { getMotionFromDB, updateMotionInDB, } from '../helpers'; +import { verbose } from '@joincolony/utils'; export const handleMotionEventSet: EventHandler = async (event, listener) => { const { diff --git a/apps/main-chain/src/handlers/motions/motionFinalized/helpers.ts b/apps/main-chain/src/handlers/motions/motionFinalized/helpers.ts index ba43b73ed..70c9d44d4 100644 --- a/apps/main-chain/src/handlers/motions/motionFinalized/helpers.ts +++ b/apps/main-chain/src/handlers/motions/motionFinalized/helpers.ts @@ -6,10 +6,9 @@ import { ColonyOperations, MotionVote } from '~types'; import { getCachedColonyClient, getColonyFromDB, - output, parseFunctionData, } from '~utils'; -import { mutate, query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyActionType, ColonyMotion, @@ -23,6 +22,7 @@ import { UpdateColonyDocument, } from '@joincolony/graphql'; import { getAmountLessFee, getNetworkInverseFee } from '~utils/networkFee'; +import { output } from '@joincolony/utils'; export const getStakerReward = async ( motionId: string, @@ -99,7 +99,7 @@ export const updateColonyUnclaimedStakes = async ( motionsWithUnclaimedStakes = [unclaimedMotionStake]; } - await mutate(UpdateColonyDocument, { + await amplifyClient.mutate(UpdateColonyDocument, { input: { id: colonyAddress, motionsWithUnclaimedStakes, @@ -137,7 +137,7 @@ export const updateAmountToExcludeNetworkFee = async ( } const { data } = - (await query< + (await amplifyClient.query< GetColonyActionByMotionIdQuery, GetColonyActionByMotionIdQueryVariables >(GetColonyActionByMotionIdDocument, { @@ -172,7 +172,7 @@ export const updateAmountToExcludeNetworkFee = async ( const amountLessFee = getAmountLessFee(amountWithFee, networkInverseFee); const networkFee = BigNumber.from(amountWithFee).sub(amountLessFee); - await mutate< + await amplifyClient.mutate< UpdateColonyActionMutation, UpdateColonyActionMutationVariables >(UpdateColonyActionDocument, { diff --git a/apps/main-chain/src/handlers/motions/motionFinalized/motionFinalized.ts b/apps/main-chain/src/handlers/motions/motionFinalized/motionFinalized.ts index 7bde98d34..2e24e244f 100644 --- a/apps/main-chain/src/handlers/motions/motionFinalized/motionFinalized.ts +++ b/apps/main-chain/src/handlers/motions/motionFinalized/motionFinalized.ts @@ -1,7 +1,7 @@ import { BigNumber, constants } from 'ethers'; -import { ExtensionEventListener } from '~eventListeners'; +import { EventHandler, ExtensionEventListener } from '@joincolony/blocks'; -import { EventHandler, MotionEvents } from '~types'; +import { MotionEvents } from '~types'; import { getActionByMotionId, getVotingClient } from '~utils'; import { linkPendingMetadata } from '~utils/colonyMetadata'; import { getBlockChainTimestampISODate } from '~utils/dates'; diff --git a/apps/main-chain/src/handlers/motions/motionRewardClaimed/helpers.ts b/apps/main-chain/src/handlers/motions/motionRewardClaimed/helpers.ts index dfbaa3d28..cabedfd5b 100644 --- a/apps/main-chain/src/handlers/motions/motionRewardClaimed/helpers.ts +++ b/apps/main-chain/src/handlers/motions/motionRewardClaimed/helpers.ts @@ -1,4 +1,4 @@ -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { StakerReward, UpdateColonyDocument, @@ -8,8 +8,9 @@ import { UpdateUserStakeMutation, UpdateUserStakeMutationVariables, } from '@joincolony/graphql'; -import { getColonyFromDB, output } from '~utils'; +import { getColonyFromDB } from '~utils'; import { getUserStakeDatabaseId } from '~utils/stakes'; +import { output } from '@joincolony/utils'; export const getUpdatedStakerRewards = ( stakerRewards: StakerReward[], @@ -54,15 +55,15 @@ export const updateColonyUnclaimedStakes = async ( /* If we still have some unclaimed stakes, update the array */ if (unclaimedRewards.length) { motionWithUnclaimedStakes.unclaimedRewards = unclaimedRewards; - await mutate( - UpdateColonyDocument, - { - input: { - id: colonyAddress, - motionsWithUnclaimedStakes, - }, + await amplifyClient.mutate< + UpdateColonyMutation, + UpdateColonyMutationVariables + >(UpdateColonyDocument, { + input: { + id: colonyAddress, + motionsWithUnclaimedStakes, }, - ); + }); } else { /* If there are no more unclaimed stakes, remove this motion from the array of motions with unclaimed stakes */ @@ -70,15 +71,15 @@ export const updateColonyUnclaimedStakes = async ( motionsWithUnclaimedStakes?.filter( ({ motionId }) => motionDatabaseId !== motionId, ); - await mutate( - UpdateColonyDocument, - { - input: { - id: colonyAddress, - motionsWithUnclaimedStakes: updatedMotionsWithUnclaimedStakes, - }, + await amplifyClient.mutate< + UpdateColonyMutation, + UpdateColonyMutationVariables + >(UpdateColonyDocument, { + input: { + id: colonyAddress, + motionsWithUnclaimedStakes: updatedMotionsWithUnclaimedStakes, }, - ); + }); } } else { output( @@ -99,13 +100,13 @@ export const reclaimUserStake = async ( motionTransactionHash: string, ): Promise => { // Update user stake status - await mutate( - UpdateUserStakeDocument, - { - input: { - id: getUserStakeDatabaseId(userAddress, motionTransactionHash), - isClaimed: true, - }, + await amplifyClient.mutate< + UpdateUserStakeMutation, + UpdateUserStakeMutationVariables + >(UpdateUserStakeDocument, { + input: { + id: getUserStakeDatabaseId(userAddress, motionTransactionHash), + isClaimed: true, }, - ); + }); }; diff --git a/apps/main-chain/src/handlers/motions/motionRewardClaimed/motionRewardClaimed.ts b/apps/main-chain/src/handlers/motions/motionRewardClaimed/motionRewardClaimed.ts index 7250fbd11..73b49c0c5 100644 --- a/apps/main-chain/src/handlers/motions/motionRewardClaimed/motionRewardClaimed.ts +++ b/apps/main-chain/src/handlers/motions/motionRewardClaimed/motionRewardClaimed.ts @@ -1,4 +1,4 @@ -import { EventHandler, MotionEvents } from '~types'; +import { MotionEvents } from '~types'; import { getVotingClient } from '~utils'; import { getMotionDatabaseId, @@ -12,7 +12,7 @@ import { getUpdatedStakerRewards, } from './helpers'; import { ColonyMotion } from '@joincolony/graphql'; -import { ExtensionEventListener } from '~eventListeners'; +import { EventHandler, ExtensionEventListener } from '@joincolony/blocks'; export const handleMotionRewardClaimed: EventHandler = async ( event, diff --git a/apps/main-chain/src/handlers/motions/motionStaked/helpers.ts b/apps/main-chain/src/handlers/motions/motionStaked/helpers.ts index 780b058c4..5cabefa86 100644 --- a/apps/main-chain/src/handlers/motions/motionStaked/helpers.ts +++ b/apps/main-chain/src/handlers/motions/motionStaked/helpers.ts @@ -16,7 +16,7 @@ import { UserMotionStakes, UserStakeType, } from '@joincolony/graphql'; -import { mutate, query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { getUserStakeDatabaseId } from '~utils/stakes'; import { getMotionSide } from '../helpers'; import { getBlockChainTimestampISODate } from '~utils/dates'; @@ -302,7 +302,7 @@ export const updateUserStake = async ( ): Promise => { const userStakeId = getUserStakeDatabaseId(userAddress, transactionHash); const { data } = - (await query( + (await amplifyClient.query( GetUserStakeDocument, { id: userStakeId, @@ -313,30 +313,30 @@ export const updateUserStake = async ( if (existingUserStake) { const { amount: existingAmount } = existingUserStake; - await mutate( - UpdateUserStakeDocument, - { - input: { - id: userStakeId, - amount: BigNumber.from(existingAmount).add(amount).toString(), - }, + await amplifyClient.mutate< + UpdateUserStakeMutation, + UpdateUserStakeMutationVariables + >(UpdateUserStakeDocument, { + input: { + id: userStakeId, + amount: BigNumber.from(existingAmount).add(amount).toString(), }, - ); + }); } else { - await mutate( - CreateUserStakeDocument, - { - input: { - id: userStakeId, - userAddress, - colonyAddress, - actionId: transactionHash, - amount: amount.toString(), - isClaimed: false, - createdAt: getBlockChainTimestampISODate(timestamp), - type: UserStakeType.Motion, - }, + await amplifyClient.mutate< + CreateUserStakeMutation, + CreateUserStakeMutationVariables + >(CreateUserStakeDocument, { + input: { + id: userStakeId, + userAddress, + colonyAddress, + actionId: transactionHash, + amount: amount.toString(), + isClaimed: false, + createdAt: getBlockChainTimestampISODate(timestamp), + type: UserStakeType.Motion, }, - ); + }); } }; diff --git a/apps/main-chain/src/handlers/motions/motionStaked/motionStaked.ts b/apps/main-chain/src/handlers/motions/motionStaked/motionStaked.ts index 1e4e5362b..6dab4e903 100644 --- a/apps/main-chain/src/handlers/motions/motionStaked/motionStaked.ts +++ b/apps/main-chain/src/handlers/motions/motionStaked/motionStaked.ts @@ -1,6 +1,5 @@ -import { ExtensionEventListener } from '~eventListeners'; -import { EventHandler, MotionSide } from '~types'; -import { verbose, getVotingClient, getActionByMotionId } from '~utils'; +import { MotionSide } from '~types'; +import { getVotingClient, getActionByMotionId } from '~utils'; import { getBlockChainTimestampISODate } from '~utils/dates'; import { getMotionDatabaseId, @@ -21,6 +20,8 @@ import { } from '~utils/notifications'; import { MotionNotificationVariables } from '~types/notifications'; import { NotificationType } from '@joincolony/graphql'; +import { verbose } from '@joincolony/utils'; +import { EventHandler, ExtensionEventListener } from '@joincolony/blocks'; export const handleMotionStaked: EventHandler = async ( event, diff --git a/apps/main-chain/src/handlers/motions/motionVoteRevealed/helpers.ts b/apps/main-chain/src/handlers/motions/motionVoteRevealed/helpers.ts index 4aba901b8..095823454 100644 --- a/apps/main-chain/src/handlers/motions/motionVoteRevealed/helpers.ts +++ b/apps/main-chain/src/handlers/motions/motionVoteRevealed/helpers.ts @@ -1,5 +1,5 @@ import { BigNumber } from 'ethers'; -import { mutate, query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { CreateUserVoterRewardDocument, CreateUserVoterRewardMutation, @@ -27,18 +27,18 @@ export const createUserReward = async ({ // Get rewards for voters on the winning side const { data } = - (await query( - GetVoterRewardsDocument, - { - input: { - rootHash, - motionId, - colonyAddress, - nativeMotionDomainId, - voterAddress: userAddress, - }, + (await amplifyClient.query< + GetVoterRewardsQuery, + GetVoterRewardsQueryVariables + >(GetVoterRewardsDocument, { + input: { + rootHash, + motionId, + colonyAddress, + nativeMotionDomainId, + voterAddress: userAddress, }, - )) ?? {}; + })) ?? {}; const { reward: voterReward } = data?.getVoterRewards ?? {}; @@ -46,7 +46,7 @@ export const createUserReward = async ({ return; } - await mutate< + await amplifyClient.mutate< CreateUserVoterRewardMutation, CreateUserVoterRewardMutationVariables >(CreateUserVoterRewardDocument, { diff --git a/apps/main-chain/src/handlers/motions/motionVoteRevealed/index.ts b/apps/main-chain/src/handlers/motions/motionVoteRevealed/index.ts index 76545e552..a082d103a 100644 --- a/apps/main-chain/src/handlers/motions/motionVoteRevealed/index.ts +++ b/apps/main-chain/src/handlers/motions/motionVoteRevealed/index.ts @@ -1,15 +1,16 @@ -import { EventHandler, MotionSide } from '~types'; -import { getVotingClient, verbose } from '~utils'; +import { MotionSide } from '~types'; +import { getVotingClient } from '~utils'; import { getMotionDatabaseId, getMotionFromDB, updateMotionInDB, } from '../helpers'; import { VoterRecord } from '@joincolony/graphql'; -import { ExtensionEventListener } from '~eventListeners'; import { createUserReward } from './helpers'; import networkClient from '~networkClient'; import { BigNumber } from 'ethers'; +import { verbose } from '@joincolony/utils'; +import { EventHandler, ExtensionEventListener } from '@joincolony/blocks'; export const handleMotionVoteRevealed: EventHandler = async ( event, diff --git a/apps/main-chain/src/handlers/motions/motionVoteSubmitted/index.ts b/apps/main-chain/src/handlers/motions/motionVoteSubmitted/index.ts index 27dbcd92f..a33cdf996 100644 --- a/apps/main-chain/src/handlers/motions/motionVoteSubmitted/index.ts +++ b/apps/main-chain/src/handlers/motions/motionVoteSubmitted/index.ts @@ -1,6 +1,5 @@ -import { ExtensionEventListener } from '~eventListeners'; -import { EventHandler } from '~types'; -import { getActionByMotionId, getVotingClient, verbose } from '~utils'; +import { ExtensionEventListener, EventHandler } from '@joincolony/blocks'; +import { getActionByMotionId, getVotingClient } from '~utils'; import { getMotionDatabaseId, getMotionFromDB, @@ -13,6 +12,7 @@ import { sendMotionNotifications, } from '~utils/notifications'; import { NotificationType } from '@joincolony/graphql'; +import { verbose } from '@joincolony/utils'; export const handleMotionVoteSubmitted: EventHandler = async ( event, diff --git a/apps/main-chain/src/handlers/multiSig/approvalChanged/approvalChanged.ts b/apps/main-chain/src/handlers/multiSig/approvalChanged/approvalChanged.ts index 4f262acec..04406ceaf 100644 --- a/apps/main-chain/src/handlers/multiSig/approvalChanged/approvalChanged.ts +++ b/apps/main-chain/src/handlers/multiSig/approvalChanged/approvalChanged.ts @@ -1,8 +1,6 @@ import { BigNumber } from 'ethers'; -import { ExtensionEventListener } from '~eventListeners'; import { MultiSigVote, NotificationType } from '@joincolony/graphql'; -import { getChainId } from '~provider'; -import { EventHandler } from '~types'; +import rpcProvider from '~provider'; import { addMultiSigVote, getMultiSigDatabaseId, @@ -15,6 +13,7 @@ import { getNotificationCategory, sendMultisigActionNotifications, } from '~utils/notifications'; +import { EventHandler, ExtensionEventListener } from '@joincolony/blocks'; export const handleMultiSigApprovalChanged: EventHandler = async ( event, @@ -24,7 +23,7 @@ export const handleMultiSigApprovalChanged: EventHandler = async ( const { colonyAddress } = listener as ExtensionEventListener; - const chainId = getChainId(); + const chainId = rpcProvider.getChainId(); const { agent: userAddress, motionId, role, approval } = event.args; const multiSigClient = await getMultiSigClient(colonyAddress); diff --git a/apps/main-chain/src/handlers/multiSig/domainSkillThresholdSet.ts b/apps/main-chain/src/handlers/multiSig/domainSkillThresholdSet.ts index dcf44781e..fa2d08852 100644 --- a/apps/main-chain/src/handlers/multiSig/domainSkillThresholdSet.ts +++ b/apps/main-chain/src/handlers/multiSig/domainSkillThresholdSet.ts @@ -1,4 +1,4 @@ -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { GetColonyExtensionByAddressDocument, GetColonyExtensionByAddressQuery, @@ -7,7 +7,7 @@ import { GetDomainsByExtensionAddressQuery, GetDomainsByExtensionAddressQueryVariables, } from '@joincolony/graphql'; -import { ContractEvent, EventHandler } from '~types'; +import { ContractEvent, EventHandler } from '@joincolony/blocks'; import { getCachedColonyClient, toNumber } from '~utils'; import { updateExtension } from '~utils/extensions/updateExtension'; @@ -17,7 +17,7 @@ export const handleMultiSigDomainSkillThresholdSet: EventHandler = async ( const { contractAddress: multiSigAddress } = event; const { domainSkillId, threshold } = event.args; - const colonyExtensionsResponse = await query< + const colonyExtensionsResponse = await amplifyClient.query< GetColonyExtensionByAddressQuery, GetColonyExtensionByAddressQueryVariables >(GetColonyExtensionByAddressDocument, { @@ -28,7 +28,7 @@ export const handleMultiSigDomainSkillThresholdSet: EventHandler = async ( colonyExtensionsResponse?.data?.getColonyExtension?.params ?? {}; if (multiSig) { - const domainsResponse = await query< + const domainsResponse = await amplifyClient.query< GetDomainsByExtensionAddressQuery, GetDomainsByExtensionAddressQueryVariables >(GetDomainsByExtensionAddressDocument, { diff --git a/apps/main-chain/src/handlers/multiSig/globalThresholdSet.ts b/apps/main-chain/src/handlers/multiSig/globalThresholdSet.ts index 5a6ea0e62..deeac81ea 100644 --- a/apps/main-chain/src/handlers/multiSig/globalThresholdSet.ts +++ b/apps/main-chain/src/handlers/multiSig/globalThresholdSet.ts @@ -1,5 +1,5 @@ import { constants } from 'ethers'; -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { GetColonyExtensionByAddressDocument, GetColonyExtensionByAddressQuery, @@ -7,7 +7,7 @@ import { NotificationType, } from '@joincolony/graphql'; import networkClient from '~networkClient'; -import { EventHandler } from '~types'; +import { EventHandler } from '@joincolony/blocks'; import { updateExtension } from '~utils/extensions/updateExtension'; import { sendExtensionUpdateNotifications } from '~utils/notifications'; @@ -15,7 +15,7 @@ export const handleMultiSigGlobalThresholdSet: EventHandler = async (event) => { const { contractAddress: multiSigAddress, transactionHash } = event; const { globalThreshold } = event.args; - const colonyExtensionsResponse = await query< + const colonyExtensionsResponse = await amplifyClient.query< GetColonyExtensionByAddressQuery, GetColonyExtensionByAddressQueryVariables >(GetColonyExtensionByAddressDocument, { diff --git a/apps/main-chain/src/handlers/multiSig/helpers.ts b/apps/main-chain/src/handlers/multiSig/helpers.ts index 9de58c341..a1aefc1bb 100644 --- a/apps/main-chain/src/handlers/multiSig/helpers.ts +++ b/apps/main-chain/src/handlers/multiSig/helpers.ts @@ -1,5 +1,5 @@ import { BigNumber } from 'ethers'; -import { mutate, query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { GetUserMultiSigSignatureDocument, GetUserMultiSigSignatureQuery, @@ -20,7 +20,7 @@ import { CreateMultiSigVoteDocument, } from '@joincolony/graphql'; import { getBlockChainTimestampISODate } from '~utils/dates'; -import { output } from '~utils/logger'; +import { output } from '@joincolony/utils'; export const getMultiSigDatabaseId = ( chainId: string, @@ -40,7 +40,7 @@ export const getUserMultiSigSignature = async ({ vote, role, }: GetUserMultiSigSignatureParams): Promise => { - const response = await query< + const response = await amplifyClient.query< GetUserMultiSigSignatureQuery, GetUserMultiSigSignatureQueryVariables >(GetUserMultiSigSignatureDocument, { @@ -64,12 +64,12 @@ export const getMultiSigFromDB = async ( databaseMultiSigId: string, ): Promise => { const { data } = - (await query( - GetColonyMultiSigDocument, - { - id: databaseMultiSigId, - }, - )) ?? {}; + (await amplifyClient.query< + GetColonyMultiSigQuery, + GetColonyMultiSigQueryVariables + >(GetColonyMultiSigDocument, { + id: databaseMultiSigId, + })) ?? {}; const multiSig = data?.getColonyMultiSig; @@ -85,7 +85,7 @@ export const getMultiSigFromDB = async ( export const updateMultiSigInDB = async ( multiSigData: UpdateColonyMultiSigInput, ): Promise => { - await mutate(UpdateColonyMultiSigDocument, { + await amplifyClient.mutate(UpdateColonyMultiSigDocument, { input: { ...multiSigData, }, @@ -109,24 +109,24 @@ export const addMultiSigVote = async ({ vote, timestamp, }: addMultiSigVoteParams): Promise => { - await mutate( - CreateMultiSigVoteDocument, - { - input: { - colonyAddress, - multiSigId, - userAddress, - role, - vote, - createdAt: getBlockChainTimestampISODate(timestamp), - }, + await amplifyClient.mutate< + CreateMultiSigVoteMutation, + CreateMultiSigVoteMutationVariables + >(CreateMultiSigVoteDocument, { + input: { + colonyAddress, + multiSigId, + userAddress, + role, + vote, + createdAt: getBlockChainTimestampISODate(timestamp), }, - ); + }); }; export const removeMultiSigVote = async (id: string): Promise => { - await mutate( - RemoveMultiSigVoteDocument, - { id }, - ); + await amplifyClient.mutate< + RemoveMultiSigVoteMutation, + RemoveMultiSigVoteMutationVariables + >(RemoveMultiSigVoteDocument, { id }); }; diff --git a/apps/main-chain/src/handlers/multiSig/multiSigCancelled.ts b/apps/main-chain/src/handlers/multiSig/multiSigCancelled.ts index 2f6c92fb0..cbb68f304 100644 --- a/apps/main-chain/src/handlers/multiSig/multiSigCancelled.ts +++ b/apps/main-chain/src/handlers/multiSig/multiSigCancelled.ts @@ -1,20 +1,19 @@ -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { NotificationType, UpdateColonyMultiSigDocument, UpdateColonyMultiSigInput, UpdateColonyMultiSigMutationVariables, } from '@joincolony/graphql'; -import { EventHandler } from '~types'; -import { verbose } from '~utils'; +import { EventHandler, ExtensionEventListener } from '@joincolony/blocks'; +import { verbose } from '@joincolony/utils'; import { getMultiSigDatabaseId, getMultiSigFromDB } from './helpers'; -import { getChainId } from '~provider'; +import rpcProvider from '~provider'; import { getBlockChainTimestampISODate } from '~utils/dates'; import { getNotificationCategory, sendMultisigActionNotifications, } from '~utils/notifications'; -import { ExtensionEventListener } from '~eventListeners'; export const handleMultiSigMotionCancelled: EventHandler = async ( event, @@ -28,7 +27,7 @@ export const handleMultiSigMotionCancelled: EventHandler = async ( const { colonyAddress } = listener as ExtensionEventListener; - const chainId = getChainId(); + const chainId = rpcProvider.getChainId(); const multiSigDatabaseId = getMultiSigDatabaseId( chainId, @@ -38,7 +37,7 @@ export const handleMultiSigMotionCancelled: EventHandler = async ( verbose(`MultiSig motion: ${motionId} has been rejected`); - await mutate< + await amplifyClient.mutate< UpdateColonyMultiSigInput, UpdateColonyMultiSigMutationVariables >(UpdateColonyMultiSigDocument, { diff --git a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/addOrEditDomain.ts b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/addOrEditDomain.ts index 9eee61f9b..888efc5b4 100644 --- a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/addOrEditDomain.ts +++ b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/addOrEditDomain.ts @@ -1,7 +1,8 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, multiSigNameMapping } from '~types'; +import { multiSigNameMapping } from '~types'; import { createMultiSigInDB } from '../helpers'; import { getDomainDatabaseId, getPendingMetadataDatabaseId } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; export const handleAddOrEditDomainMultiSig = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/colonyVersionUpgrade.ts b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/colonyVersionUpgrade.ts index b99c515c7..a7726516e 100644 --- a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/colonyVersionUpgrade.ts +++ b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/colonyVersionUpgrade.ts @@ -1,7 +1,8 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, multiSigNameMapping } from '~types'; +import { multiSigNameMapping } from '~types'; import { createMultiSigInDB } from '../helpers'; import { toNumber } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; export const handleColonyVersionUpgrade = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/editColony.ts b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/editColony.ts index fe28a4afb..bcc51c6c9 100644 --- a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/editColony.ts +++ b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/editColony.ts @@ -1,7 +1,8 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, multiSigNameMapping } from '~types'; +import { multiSigNameMapping } from '~types'; import { getPendingMetadataDatabaseId } from '~utils'; import { createMultiSigInDB } from '../helpers'; +import { ContractEvent } from '@joincolony/blocks'; export const handleEditColonyMultiSig = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/manageReputation.ts b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/manageReputation.ts index 3db172244..2ca808b1d 100644 --- a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/manageReputation.ts +++ b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/manageReputation.ts @@ -1,8 +1,9 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, multiSigNameMapping } from '~types'; +import { multiSigNameMapping } from '~types'; import { createMultiSigInDB } from '../helpers'; import { getDomainDatabaseId } from '~utils'; import { sendMentionNotifications } from '~utils/notifications'; +import { ContractEvent } from '@joincolony/blocks'; export const handleManageReputationMultiSig = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/metadataDelta.ts b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/metadataDelta.ts index 48317d5ff..f33d3c7de 100644 --- a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/metadataDelta.ts +++ b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/metadataDelta.ts @@ -1,15 +1,15 @@ import { TransactionDescription } from 'ethers/lib/utils'; import { ColonyActionType } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; import { isAddVerifiedMembersOperation, isManageTokensOperation, isRemoveVerifiedMembersOperation, parseMetadataDeltaOperation, - verbose, } from '~utils'; import { createMultiSigInDB } from '../helpers'; import { manageTokensMultisigHandler } from './metadataDeltaHandlers/manageTokens'; +import { verbose } from '@joincolony/utils'; export const handleMetadataDeltaMultiSig = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/metadataDeltaHandlers/manageTokens.ts b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/metadataDeltaHandlers/manageTokens.ts index af2733cf5..05739096e 100644 --- a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/metadataDeltaHandlers/manageTokens.ts +++ b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/metadataDeltaHandlers/manageTokens.ts @@ -5,7 +5,7 @@ import { } from '~utils'; import { createMultiSigInDB } from '../../helpers'; import { ColonyActionType } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; export const manageTokensMultisigHandler = async ({ colonyAddress, diff --git a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/mintTokens.ts b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/mintTokens.ts index aecabe59a..e6cec2f54 100644 --- a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/mintTokens.ts +++ b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/mintTokens.ts @@ -1,7 +1,8 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, multiSigNameMapping } from '~types'; +import { multiSigNameMapping } from '~types'; import { getColonyTokenAddress } from '~utils'; import { createMultiSigInDB } from '../helpers'; +import { ContractEvent } from '@joincolony/blocks'; export const handleMintTokensMultiSig = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/moveFunds.ts b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/moveFunds.ts index c958ce004..0b35aceb7 100644 --- a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/moveFunds.ts +++ b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/moveFunds.ts @@ -1,5 +1,5 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, multiSigNameMapping } from '~types'; +import { multiSigNameMapping } from '~types'; import { getCachedColonyClient, getDomainDatabaseId, @@ -8,6 +8,7 @@ import { toNumber, } from '~utils'; import { createMultiSigInDB } from '../helpers'; +import { ContractEvent } from '@joincolony/blocks'; import { BigNumber } from 'ethers'; export const handleMoveFundsMultiSig = async ( diff --git a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/payment.ts b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/payment.ts index 01e98d18b..df4d62b3d 100644 --- a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/payment.ts +++ b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/payment.ts @@ -1,6 +1,6 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, multiSigNameMapping } from '~types'; +import { multiSigNameMapping } from '~types'; import { getDomainDatabaseId, toNumber } from '~utils'; import { ColonyActionType } from '@joincolony/graphql'; @@ -8,6 +8,7 @@ import { MultiPayment } from '~handlers/actions/oneTxPayment'; import { createMultiSigInDB } from '../helpers'; import { sendMentionNotifications } from '~utils/notifications'; +import { ContractEvent } from '@joincolony/blocks'; export const handlePaymentMultiSig = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/setUserRoles.ts b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/setUserRoles.ts index 3371662ba..07b5a45ed 100644 --- a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/setUserRoles.ts +++ b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/setUserRoles.ts @@ -1,6 +1,6 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, multiSigNameMapping } from '~types'; +import { multiSigNameMapping } from '~types'; import { getColonyRolesDatabaseId, getDomainDatabaseId, @@ -8,6 +8,7 @@ import { } from '~utils'; import { createMultiSigInDB } from '../helpers'; import { sendMentionNotifications } from '~utils/notifications'; +import { ContractEvent } from '@joincolony/blocks'; export const handleSetUserRolesMultiSig = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/unlockToken.ts b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/unlockToken.ts index fb11ac2d4..8f44512c1 100644 --- a/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/unlockToken.ts +++ b/apps/main-chain/src/handlers/multiSig/multiSigCreated/handlers/unlockToken.ts @@ -1,7 +1,8 @@ import { TransactionDescription } from 'ethers/lib/utils'; -import { ContractEvent, multiSigNameMapping } from '~types'; +import { multiSigNameMapping } from '~types'; import { getColonyTokenAddress } from '~utils'; import { createMultiSigInDB } from '../helpers'; +import { ContractEvent } from '@joincolony/blocks'; export const handleUnlockTokenMultiSig = async ( colonyAddress: string, diff --git a/apps/main-chain/src/handlers/multiSig/multiSigCreated/helpers.ts b/apps/main-chain/src/handlers/multiSig/multiSigCreated/helpers.ts index ace1d4b25..5a51ac248 100644 --- a/apps/main-chain/src/handlers/multiSig/multiSigCreated/helpers.ts +++ b/apps/main-chain/src/handlers/multiSig/multiSigCreated/helpers.ts @@ -1,6 +1,6 @@ import { AnyMultisigPermissionsClient } from '@colony/colony-js'; import { BigNumber } from 'ethers'; -import { GraphQLFnReturn, mutate, query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyMultiSig, CreateColonyActionInput, @@ -12,21 +12,22 @@ import { GetDomainByNativeSkillIdQueryVariables, } from '@joincolony/graphql'; import networkClient from '~networkClient'; -import { getChainId } from '~provider'; -import { ContractEvent } from '~types'; +import rpcProvider from '~provider'; +import { ContractEvent } from '@joincolony/blocks'; import { getDomainDatabaseId, getMultiSigClient, - output, createColonyAction, } from '~utils'; import { getBlockChainTimestampISODate } from '~utils/dates'; import { getMultiSigDatabaseId } from '../helpers'; +import { output } from '@joincolony/utils'; +import { type GraphQLFnReturn } from '@joincolony/clients'; const createColonyMultiSig = async ( motionData: CreateColonyMultiSigInput, ): Promise => { - await mutate< + await amplifyClient.mutate< CreateColonyMultiSigInput, CreateColonyMultiSigMutationVariables >(CreateColonyMultiSigDocument, { @@ -57,7 +58,7 @@ export const getMultiSigData = async ({ isDecision = false, timestamp, }: GetMultiSigDataArgs): Promise => { - const chainId = getChainId(); + const chainId = rpcProvider.getChainId(); const multiSigDatabaseId = getMultiSigDatabaseId( chainId, multiSigClient.address, @@ -84,7 +85,7 @@ const getDomainIdByNativeSkillId = async ( colonyAddress: string, nativeSkillId: string, ): Promise => { - const result = await query< + const result = await amplifyClient.query< GetDomainByNativeSkillIdQuery, GetDomainByNativeSkillIdQueryVariables >(GetDomainByNativeSkillIdDocument, { diff --git a/apps/main-chain/src/handlers/multiSig/multiSigCreated/multiSigCreated.ts b/apps/main-chain/src/handlers/multiSig/multiSigCreated/multiSigCreated.ts index 6a591437f..77d86beda 100644 --- a/apps/main-chain/src/handlers/multiSig/multiSigCreated/multiSigCreated.ts +++ b/apps/main-chain/src/handlers/multiSig/multiSigCreated/multiSigCreated.ts @@ -1,6 +1,5 @@ import { utils } from 'ethers'; -import { ExtensionEventListener } from '~eventListeners'; -import { ColonyOperations, EventHandler } from '~types'; +import { ColonyOperations } from '~types'; import { getCachedColonyClient, getMultiSigClient, @@ -8,7 +7,6 @@ import { getStagedExpenditureClient, getStakedExpenditureClient, parseMotionAction, - verbose, } from '~utils'; import { handleEditColonyMultiSig, @@ -25,6 +23,8 @@ import { handlePaymentMultiSig } from './handlers/payment'; import { sendMultisigActionNotifications } from '~utils/notifications'; import { NotificationCategory } from '~types/notifications'; import { NotificationType } from '@joincolony/graphql'; +import { verbose } from '@joincolony/utils'; +import { EventHandler, ExtensionEventListener } from '@joincolony/blocks'; export const handleMultiSigMotionCreated: EventHandler = async ( event, diff --git a/apps/main-chain/src/handlers/multiSig/multiSigExecuted/multiSigExecuted.ts b/apps/main-chain/src/handlers/multiSig/multiSigExecuted/multiSigExecuted.ts index 9db4cadf5..8a547050c 100644 --- a/apps/main-chain/src/handlers/multiSig/multiSigExecuted/multiSigExecuted.ts +++ b/apps/main-chain/src/handlers/multiSig/multiSigExecuted/multiSigExecuted.ts @@ -1,7 +1,5 @@ -import { ExtensionEventListener } from '~eventListeners'; -import { getChainId } from '~provider'; - -import { EventHandler } from '~types'; +import rpcProvider from '~provider'; +import { EventHandler, ExtensionEventListener } from '@joincolony/blocks'; // import { linkPendingMetadata } from '~utils/colonyMetadata'; import { @@ -9,7 +7,7 @@ import { getMultiSigFromDB, updateMultiSigInDB, } from '../helpers'; -import { getMultiSigClient, verbose } from '~utils'; +import { getMultiSigClient } from '~utils'; import { linkPendingMetadata } from '~utils/colonyMetadata'; import { getBlockChainTimestampISODate } from '~utils/dates'; import { @@ -17,6 +15,7 @@ import { sendMultisigActionNotifications, } from '~utils/notifications'; import { NotificationType } from '@joincolony/graphql'; +import { verbose } from '@joincolony/utils'; export const handleMultiSigMotionExecuted: EventHandler = async ( event, @@ -34,7 +33,7 @@ export const handleMultiSigMotionExecuted: EventHandler = async ( return; } - const chainId = getChainId(); + const chainId = rpcProvider.getChainId(); const multiSigDatabaseId = getMultiSigDatabaseId( chainId, multiSigExtensionAddress, diff --git a/apps/main-chain/src/handlers/multiSig/rejectionChanged/rejectionChanged.ts b/apps/main-chain/src/handlers/multiSig/rejectionChanged/rejectionChanged.ts index 0628a36a7..fad60f484 100644 --- a/apps/main-chain/src/handlers/multiSig/rejectionChanged/rejectionChanged.ts +++ b/apps/main-chain/src/handlers/multiSig/rejectionChanged/rejectionChanged.ts @@ -1,13 +1,12 @@ import { MultiSigVote } from '@joincolony/graphql'; -import { getChainId } from '~provider'; -import { EventHandler } from '~types'; +import rpcProvider from '~provider'; import { addMultiSigVote, getMultiSigDatabaseId, getUserMultiSigSignature, removeMultiSigVote, } from '../helpers'; -import { ExtensionEventListener } from '~eventListeners'; +import { EventHandler, ExtensionEventListener } from '@joincolony/blocks'; export const handleMultiSigRejectionChanged: EventHandler = async ( event, @@ -21,7 +20,7 @@ export const handleMultiSigRejectionChanged: EventHandler = async ( return; } - const chainId = getChainId(); + const chainId = rpcProvider.getChainId(); const { agent: userAddress, motionId, role, approval } = event.args; const multiSigId = getMultiSigDatabaseId( diff --git a/apps/main-chain/src/handlers/network/networkFeeInverseSet.ts b/apps/main-chain/src/handlers/network/networkFeeInverseSet.ts index 3cf4c4b05..6b1d07c17 100644 --- a/apps/main-chain/src/handlers/network/networkFeeInverseSet.ts +++ b/apps/main-chain/src/handlers/network/networkFeeInverseSet.ts @@ -1,18 +1,18 @@ -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { NETWORK_INVERSE_FEE_DATABASE_ID } from '~constants'; import { UpdateCurrentNetworkInverseFeeDocument, UpdateCurrentNetworkInverseFeeMutation, UpdateCurrentNetworkInverseFeeMutationVariables, } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; -import { output } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; +import { output } from '@joincolony/utils'; export default async (event: ContractEvent): Promise => { const { feeInverse } = event.args; const convertedFee = feeInverse.toString(); - await mutate< + await amplifyClient.mutate< UpdateCurrentNetworkInverseFeeMutation, UpdateCurrentNetworkInverseFeeMutationVariables >(UpdateCurrentNetworkInverseFeeDocument, { diff --git a/apps/main-chain/src/handlers/proxyColonies/proxyColonyRequested.ts b/apps/main-chain/src/handlers/proxyColonies/proxyColonyRequested.ts index 1718e0adb..7624e32b6 100644 --- a/apps/main-chain/src/handlers/proxyColonies/proxyColonyRequested.ts +++ b/apps/main-chain/src/handlers/proxyColonies/proxyColonyRequested.ts @@ -1,4 +1,4 @@ -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; export const handleProxyColonyRequested = async ( event: ContractEvent, diff --git a/apps/main-chain/src/handlers/reputationMiningCycle/reputationMiningCycleComplete.ts b/apps/main-chain/src/handlers/reputationMiningCycle/reputationMiningCycleComplete.ts index dc3641f3b..c2a217efa 100644 --- a/apps/main-chain/src/handlers/reputationMiningCycle/reputationMiningCycleComplete.ts +++ b/apps/main-chain/src/handlers/reputationMiningCycle/reputationMiningCycleComplete.ts @@ -1,4 +1,4 @@ -import { mutate, query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { CreateReputationMiningCycleMetadataDocument, CreateReputationMiningCycleMetadataMutation, @@ -10,7 +10,7 @@ import { UpdateReputationMiningCycleMetadataMutation, UpdateReputationMiningCycleMetadataMutationVariables, } from '@joincolony/graphql'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; import { reputationMiningCycleMetadataId } from './utils'; export default async (event: ContractEvent): Promise => { @@ -18,7 +18,7 @@ export default async (event: ContractEvent): Promise => { // However, for current purposes (updating colony-wide contributor reputation), we don't care. We just need a timestamp. const { data } = - (await query< + (await amplifyClient.query< GetReputationMiningCycleMetadataQuery, GetReputationMiningCycleMetadataQueryVariables >(GetReputationMiningCycleMetadataDocument, { @@ -28,7 +28,7 @@ export default async (event: ContractEvent): Promise => { const dbEntryExists = !!data?.getReputationMiningCycleMetadata; if (dbEntryExists) { - await mutate< + await amplifyClient.mutate< UpdateReputationMiningCycleMetadataMutation, UpdateReputationMiningCycleMetadataMutationVariables >(UpdateReputationMiningCycleMetadataDocument, { @@ -38,7 +38,7 @@ export default async (event: ContractEvent): Promise => { }, }); } else { - await mutate< + await amplifyClient.mutate< CreateReputationMiningCycleMetadataMutation, CreateReputationMiningCycleMetadataMutationVariables >(CreateReputationMiningCycleMetadataDocument, { diff --git a/apps/main-chain/src/handlers/tokens/setTokenAuthority.ts b/apps/main-chain/src/handlers/tokens/setTokenAuthority.ts index 65c898a5f..d30d05bb7 100644 --- a/apps/main-chain/src/handlers/tokens/setTokenAuthority.ts +++ b/apps/main-chain/src/handlers/tokens/setTokenAuthority.ts @@ -1,6 +1,6 @@ import { TokenClientType } from '@colony/colony-js'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; import { getCachedTokenClient, fetchColoniesByNativeToken, diff --git a/apps/main-chain/src/index.ts b/apps/main-chain/src/index.ts index d0a5d1c82..f5364d6b9 100644 --- a/apps/main-chain/src/index.ts +++ b/apps/main-chain/src/index.ts @@ -1,22 +1,23 @@ import 'cross-fetch/polyfill'; import { utils } from 'ethers'; -import { startBlockListener } from '~blockListener'; -import amplifyClientSetup from '~amplifyClient'; -import { initialiseProvider } from '~provider'; +import '~amplifyClient'; +import '~statsManager'; +import '~eventManager'; +import blockManager from '~blockManager'; import { startStatsServer } from '~stats'; import { setupListenersForColonies, setupListenersForExtensions, } from '~eventListeners'; import { seedDB } from '~utils'; +import rpcProvider from './provider'; import { setupNotificationsClient } from '~utils/notifications'; utils.Logger.setLogLevel(utils.Logger.levels.ERROR); const start = async (): Promise => { - amplifyClientSetup(); - + await rpcProvider.initialiseProvider(); /** * Setup the notifications provider so that notifications can be sent when needed */ @@ -37,9 +38,7 @@ const start = async (): Promise => { /** * Start the main block listener */ - startBlockListener(); - - await initialiseProvider(); + blockManager.startBlockListener(); /** * In development, where both the chain and the DB gets reset everytime, diff --git a/apps/main-chain/src/interfaces.ts b/apps/main-chain/src/interfaces.ts deleted file mode 100644 index 439ef23c3..000000000 --- a/apps/main-chain/src/interfaces.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { utils, constants } from 'ethers'; -import { - IColonyEvents__factory as ColonyEventsFactory, - VotingReputationEvents__factory as VotingReputationEventsFactory, - StakedExpenditureEvents__factory as StakedExpenditureEventsFactory, - TokenEvents__factory as TokenEventsFactory, - StagedExpenditureEvents__factory as StagedExpenditureEventsFactory, - OneTxPaymentEvents__factory as OneTxPaymentEventsFactory, - StreamingPaymentsEvents__factory as StreamingPaymentsEventsFactory, - MultisigPermissionsEvents__factory as MultisigPermissionsEventsFactory, -} from '@colony/events'; -import { Extension, getExtensionHash } from '@colony/colony-js'; - -import networkClient from '~networkClient'; -import provider from '~provider'; -import { EventListener, EventListenerType } from '~eventListeners'; - -// @TODO @chmanie is gonna make this better, for now let's just hardcode the proxy colony events -const ProxyColonyEvents = new utils.Interface([ - 'event ProxyColonyRequested(uint256 destinationChainId, bytes32 salt)', -]); - -/** - * Function returning ABI-derived interface for a given event listener type, - * which is later used for parsing event logs - */ -export const getInterfaceByListener = ( - listener: EventListener, -): utils.Interface | null => { - const { type: listenerType } = listener; - - switch (listenerType) { - case EventListenerType.Network: { - return networkClient.interface; - } - case EventListenerType.ProxyColonies: { - return ProxyColonyEvents; - } - case EventListenerType.Colony: { - return ColonyEventsFactory.connect(constants.AddressZero, provider) - .interface; - } - case EventListenerType.Extension: { - return getInterfaceByExtensionHash(listener.extensionHash); - } - case EventListenerType.Token: { - return TokenEventsFactory.connect(constants.AddressZero, provider) - .interface; - } - default: { - return null; - } - } -}; - -const getInterfaceByExtensionHash = ( - extensionHash: string, -): utils.Interface | null => { - switch (extensionHash) { - case getExtensionHash(Extension.OneTxPayment): { - return OneTxPaymentEventsFactory.connect(constants.AddressZero, provider) - .interface; - } - case getExtensionHash(Extension.VotingReputation): { - return VotingReputationEventsFactory.connect( - constants.AddressZero, - provider, - ).interface; - } - case getExtensionHash(Extension.MultisigPermissions): { - return MultisigPermissionsEventsFactory.connect( - constants.AddressZero, - provider, - ).interface; - } - case getExtensionHash(Extension.StakedExpenditure): { - return StakedExpenditureEventsFactory.connect( - constants.AddressZero, - provider, - ).interface; - } - case getExtensionHash(Extension.StagedExpenditure): { - return StagedExpenditureEventsFactory.connect( - constants.AddressZero, - provider, - ).interface; - } - case getExtensionHash(Extension.StreamingPayments): { - return StreamingPaymentsEventsFactory.connect( - constants.AddressZero, - provider, - ).interface; - } - default: { - return null; - } - } -}; diff --git a/apps/main-chain/src/networkClient.ts b/apps/main-chain/src/networkClient.ts index 1ba5e20ca..d9f351999 100644 --- a/apps/main-chain/src/networkClient.ts +++ b/apps/main-chain/src/networkClient.ts @@ -1,12 +1,11 @@ -import { Network, getColonyNetworkClient } from '@colony/colony-js'; +import { Network } from '@colony/colony-js'; -import provider from './provider'; +import rpcProvider from '~provider'; -export default getColonyNetworkClient( +import { NetworkClient } from '@joincolony/clients'; + +export default (new NetworkClient( + rpcProvider, (process.env.CHAIN_NETWORK as Network) || Network.Custom, - provider, - { - networkAddress: process.env.CHAIN_NETWORK_CONTRACT, - disableVersionCheck: true, - }, -); + process.env.CHAIN_NETWORK_CONTRACT || '', +)).getInstance(); diff --git a/apps/main-chain/src/provider.ts b/apps/main-chain/src/provider.ts index d44bf709b..eed068b14 100644 --- a/apps/main-chain/src/provider.ts +++ b/apps/main-chain/src/provider.ts @@ -1,21 +1,4 @@ -import { providers } from 'ethers'; +import { RpcProvider } from '@joincolony/clients'; -import { ChainID } from './types'; - -let chainId: ChainID; - -export const setChainId = (newChainId: ChainID): void => { - chainId = newChainId; -}; -export const getChainId = (): ChainID => chainId; - -const provider = new providers.StaticJsonRpcProvider( - process.env.CHAIN_RPC_ENDPOINT, -); - -export const initialiseProvider = async (): Promise => { - const { chainId } = await provider.getNetwork(); - setChainId(String(chainId)); -}; - -export default provider; +const rpcProvider = new RpcProvider(process.env.CHAIN_RPC_ENDPOINT); +export default rpcProvider; diff --git a/apps/main-chain/src/stats.ts b/apps/main-chain/src/stats.ts index 141d40e4c..44fbca078 100644 --- a/apps/main-chain/src/stats.ts +++ b/apps/main-chain/src/stats.ts @@ -1,11 +1,14 @@ import express from 'express'; -import { getLastBlockNumber, getStats, initStats, output } from '~utils'; -import { getChainId } from '~provider'; -import { getListenersStats } from '~eventListeners'; +import eventManager from '~eventManager'; +import rpcProvider from '~provider'; +import { output } from '@joincolony/utils'; +import statsManager from '~statsManager'; +// @NOTE this can probably be moved to the colonyAdded handler export const coloniesSet = new Set(); +// @NOTE just copy this entire file later on for now const app = express(); const port = process.env.STATS_PORT; @@ -24,7 +27,7 @@ app.get('/liveness', (_, res) => res.sendStatus(200)); * Use to check various service stats */ app.get('/stats', async (_, res) => { - const stats = getStats(); + const stats = statsManager.getStats(); res.type('json').send(stats); }); @@ -32,7 +35,7 @@ app.get('/stats', async (_, res) => { * Use to check currently active listeners */ app.get('/listeners', async (_, res) => { - res.type('json').send(getListenersStats()); + res.type('json').send(eventManager.getListenersStats()); }); export const startStatsServer = async (): Promise => { @@ -40,11 +43,11 @@ export const startStatsServer = async (): Promise => { return; } - await initStats(); - const lastBlockNumber = getLastBlockNumber(); + await statsManager.initStats(); + const lastBlockNumber = statsManager.getLastBlockNumber(); app.listen(port, async () => { - output('Block Ingestor started on chain', getChainId()); + output('Block Ingestor started on chain', rpcProvider.getChainId()); output(`Stats available at http://localhost:${port}/stats`); output(`Liveness check available at http://localhost:${port}/liveness`); output(`Last processed block number: ${lastBlockNumber}`); diff --git a/apps/main-chain/src/statsManager.ts b/apps/main-chain/src/statsManager.ts new file mode 100644 index 000000000..65a7a19b9 --- /dev/null +++ b/apps/main-chain/src/statsManager.ts @@ -0,0 +1,7 @@ +import { StatsManager } from '@joincolony/blocks'; +import amplifyClient from './amplifyClient'; +import rpcProvider from '~provider'; + +const statsManager = new StatsManager(amplifyClient, rpcProvider); + +export default statsManager; diff --git a/apps/main-chain/src/types/actions.ts b/apps/main-chain/src/types/actions.ts index d8ec9c374..1a4e5e66a 100644 --- a/apps/main-chain/src/types/actions.ts +++ b/apps/main-chain/src/types/actions.ts @@ -1,3 +1,3 @@ -import { ContractEvent } from './events'; +import { ContractEvent } from '@joincolony/blocks'; export type ColonyActionHandler = (event: ContractEvent) => Promise; diff --git a/apps/main-chain/src/types/index.ts b/apps/main-chain/src/types/index.ts index fae0484f7..9ea273236 100644 --- a/apps/main-chain/src/types/index.ts +++ b/apps/main-chain/src/types/index.ts @@ -1,4 +1,3 @@ -export * from './events'; export * from './actions'; export * from './methods'; export * from './motions'; diff --git a/apps/main-chain/src/utils/actionExists.ts b/apps/main-chain/src/utils/actionExists.ts index b2bfbf137..042725c57 100644 --- a/apps/main-chain/src/utils/actionExists.ts +++ b/apps/main-chain/src/utils/actionExists.ts @@ -1,4 +1,4 @@ -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { GetActionByIdDocument, GetActionByIdQuery, @@ -8,7 +8,7 @@ import { export const checkActionExists = async ( transactionHash: string, ): Promise => { - const existingActionQuery = await query< + const existingActionQuery = await amplifyClient.query< GetActionByIdQuery, GetActionByIdQueryVariables >(GetActionByIdDocument, { diff --git a/apps/main-chain/src/utils/actions/getAction.ts b/apps/main-chain/src/utils/actions/getAction.ts index 93279c004..e962a57d3 100644 --- a/apps/main-chain/src/utils/actions/getAction.ts +++ b/apps/main-chain/src/utils/actions/getAction.ts @@ -1,4 +1,4 @@ -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ActionMetadataInfoFragment, GetColonyActionByMotionIdDocument, @@ -12,7 +12,7 @@ import { export const getActionByMotionId = async ( motionId: string, ): Promise => { - const response = await query< + const response = await amplifyClient.query< GetColonyActionByMotionIdQuery, GetColonyActionByMotionIdQueryVariables >(GetColonyActionByMotionIdDocument, { @@ -27,7 +27,7 @@ export const getActionByMotionId = async ( export const getActionByMultiSigId = async ( multiSigId: string, ): Promise => { - const response = await query< + const response = await amplifyClient.query< GetColonyActionByMultiSigIdQuery, GetColonyActionByMultiSigIdQueryVariables >(GetColonyActionByMultiSigIdDocument, { diff --git a/apps/main-chain/src/utils/actions/writeAction.ts b/apps/main-chain/src/utils/actions/writeAction.ts index 31a1a6b91..cdf595f7b 100644 --- a/apps/main-chain/src/utils/actions/writeAction.ts +++ b/apps/main-chain/src/utils/actions/writeAction.ts @@ -1,5 +1,5 @@ import { Extension, getExtensionHash } from '@colony/colony-js'; -import { mutate, query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyActionType, CreateColonyActionDocument, @@ -11,10 +11,11 @@ import { GetExpenditureByNativeFundingPotIdAndColonyQuery, GetExpenditureByNativeFundingPotIdAndColonyQueryVariables, } from '@joincolony/graphql'; -import { toNumber, verbose, getColonyExtensions } from '~utils'; -import { ContractEvent } from '~types'; +import { toNumber, getColonyExtensions } from '~utils'; +import { ContractEvent } from '@joincolony/blocks'; import networkClient from '~networkClient'; import { getBlockChainTimestampISODate } from '~utils/dates'; +import { verbose } from '@joincolony/utils'; export type ActionFields = Omit< CreateColonyActionInput, @@ -54,21 +55,21 @@ export const writeActionFromEvent = async ( verbose('Action', actionType, 'took place in Colony:', colonyAddress); - await mutate( - CreateColonyActionDocument, - { - input: { - id: transactionHash, - colonyId: colonyAddress, - blockNumber, - createdAt: getBlockChainTimestampISODate(timestamp), - showInActionsList, - rootHash, - isMotionFinalization, - ...actionFields, - }, + await amplifyClient.mutate< + CreateColonyActionMutation, + CreateColonyActionMutationVariables + >(CreateColonyActionDocument, { + input: { + id: transactionHash, + colonyId: colonyAddress, + blockNumber, + createdAt: getBlockChainTimestampISODate(timestamp), + showInActionsList, + rootHash, + isMotionFinalization, + ...actionFields, }, - ); + }); }; const showActionInActionsList = async ( @@ -81,7 +82,7 @@ const showActionInActionsList = async ( const [, , toPot] = args; const { data } = - (await query< + (await amplifyClient.query< GetExpenditureByNativeFundingPotIdAndColonyQuery, GetExpenditureByNativeFundingPotIdAndColonyQueryVariables >(GetExpenditureByNativeFundingPotIdAndColonyDocument, { @@ -135,13 +136,13 @@ export const createColonyAction = async ( actionData: CreateColonyActionInput, blockTimestamp: number, ): Promise => { - await mutate( - CreateColonyActionDocument, - { - input: { - ...actionData, - createdAt: getBlockChainTimestampISODate(blockTimestamp), - }, + await amplifyClient.mutate< + CreateColonyActionMutation, + CreateColonyActionMutationVariables + >(CreateColonyActionDocument, { + input: { + ...actionData, + createdAt: getBlockChainTimestampISODate(blockTimestamp), }, - ); + }); }; diff --git a/apps/main-chain/src/utils/clients/index.ts b/apps/main-chain/src/utils/clients/index.ts index c0d26f7e8..b79f3c132 100644 --- a/apps/main-chain/src/utils/clients/index.ts +++ b/apps/main-chain/src/utils/clients/index.ts @@ -1,7 +1,12 @@ -import { ClientType } from '@colony/colony-js'; +import { + AnyColonyClient, + AnyVotingReputationClient, + ClientType, + ColonyNetworkClient, + TokenClient, +} from '@colony/colony-js'; import networkClient from '~networkClient'; -import { NetworkClients } from '~types'; import { getCachedColonyClient } from './colony'; import { getVotingClient } from './voting'; @@ -14,6 +19,12 @@ export * from './streamingPayments'; export * from './oneTxPayment'; export * from './token'; +type NetworkClients = + | ColonyNetworkClient + | TokenClient + | AnyColonyClient + | AnyVotingReputationClient; + /** * Function returning a (hopefully) cached client for the given type and colony address * Currently, it supports colony and voting clients, for other client types it returns the network client diff --git a/apps/main-chain/src/utils/colony.ts b/apps/main-chain/src/utils/colony.ts index 4c7667904..bc7de3a36 100644 --- a/apps/main-chain/src/utils/colony.ts +++ b/apps/main-chain/src/utils/colony.ts @@ -1,4 +1,4 @@ -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyWithRootRolesFragment, ListColoniesWithRootPermissionHoldersDocument, @@ -12,7 +12,7 @@ const getColoniesData: GetDataFn< ColonyWithRootRolesFragment, undefined > = async (_params, nextToken) => { - const response = await query< + const response = await amplifyClient.query< ListColoniesWithRootPermissionHoldersQuery, ListColoniesWithRootPermissionHoldersQueryVariables >(ListColoniesWithRootPermissionHoldersDocument, { diff --git a/apps/main-chain/src/utils/colonyClient.ts b/apps/main-chain/src/utils/colonyClient.ts index 5b907b175..151ff2126 100644 --- a/apps/main-chain/src/utils/colonyClient.ts +++ b/apps/main-chain/src/utils/colonyClient.ts @@ -1,20 +1,23 @@ -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { Colony, GetColonyDocument, GetColonyQuery, GetColonyQueryVariables, } from '@joincolony/graphql'; -import { output } from './logger'; +import { output } from '@joincolony/utils'; // @TODO: Consider refactoring this as it doesn't feel like it's in the right place export const getColonyFromDB = async ( colonyAddress: string, ): Promise => { const { data } = - (await query(GetColonyDocument, { - id: colonyAddress, - })) ?? {}; + (await amplifyClient.query( + GetColonyDocument, + { + id: colonyAddress, + }, + )) ?? {}; const colony = data?.getColony; diff --git a/apps/main-chain/src/utils/colonyMetadata.ts b/apps/main-chain/src/utils/colonyMetadata.ts index 825c90379..a12fd9983 100644 --- a/apps/main-chain/src/utils/colonyMetadata.ts +++ b/apps/main-chain/src/utils/colonyMetadata.ts @@ -1,7 +1,7 @@ import { TransactionDescription } from 'ethers/lib/utils'; import { ColonyOperations } from '~types'; -import { query, mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyMetadata, CreateDomainMetadataDocument, @@ -16,7 +16,7 @@ import { UpdateDomainMetadataDocument, } from '@joincolony/graphql'; import { getDomainDatabaseId } from './domains'; -import { output } from './logger'; +import { output } from '@joincolony/utils'; import { getCachedColonyClient } from './clients'; import { getActionByMotionId, getActionByMultiSigId } from './actions'; import { parseFunctionData } from './parseFunction'; @@ -39,7 +39,7 @@ const linkPendingDomainMetadataWithDomain = async ( // and use that as an id to link the pending metadata. const nativeDomainId = domainCount.toNumber(); - await mutate(CreateDomainMetadataDocument, { + await amplifyClient.mutate(CreateDomainMetadataDocument, { input: { ...pendingDomainMetadata, id: getDomainDatabaseId(colonyAddress, nativeDomainId), @@ -50,12 +50,12 @@ const linkPendingDomainMetadataWithDomain = async ( const databaseDomainId = getDomainDatabaseId(colonyAddress, nativeDomainId); const { data } = - (await query( - GetDomainMetadataDocument, - { - id: databaseDomainId, - }, - )) ?? {}; + (await amplifyClient.query< + GetDomainMetadataQuery, + GetDomainMetadataQueryVariables + >(GetDomainMetadataDocument, { + id: databaseDomainId, + })) ?? {}; const currentDomainMetadata = data?.getDomainMetadata; @@ -104,7 +104,7 @@ const linkPendingDomainMetadataWithDomain = async ( updatedMetadata.name = newName; } - await mutate(UpdateDomainMetadataDocument, { + await amplifyClient.mutate(UpdateDomainMetadataDocument, { input: { ...updatedMetadata, id: databaseDomainId, @@ -118,12 +118,12 @@ const linkPendingColonyMetadataWithColony = async ( colonyAddress: string, ): Promise => { const { data } = - (await query( - GetColonyMetadataDocument, - { - id: colonyAddress, - }, - )) ?? {}; + (await amplifyClient.query< + GetColonyMetadataQuery, + GetColonyMetadataQueryVariables + >(GetColonyMetadataDocument, { + id: colonyAddress, + })) ?? {}; const currentColonyMetadata = data?.getColonyMetadata; @@ -175,7 +175,7 @@ const linkPendingColonyMetadataWithColony = async ( updatedMetadata.objective = pendingColonyMetadata.objective; } - await mutate(UpdateColonyMetadataDocument, { + await amplifyClient.mutate(UpdateColonyMetadataDocument, { input: { ...updatedMetadata, changelog: [ diff --git a/apps/main-chain/src/utils/contributors.ts b/apps/main-chain/src/utils/contributors.ts index 966797d02..a60285a96 100644 --- a/apps/main-chain/src/utils/contributors.ts +++ b/apps/main-chain/src/utils/contributors.ts @@ -1,4 +1,4 @@ -import { query, mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { CreateColonyContributorDocument, CreateColonyContributorInput, @@ -44,10 +44,13 @@ const getColonyContributor = async ({ contributorAddress: string; }): Promise< ReturnType< - typeof query + typeof amplifyClient.query< + GetColonyContributorQuery, + GetColonyContributorQueryVariables + > > > => { - return await query< + return await amplifyClient.query< GetColonyContributorQuery, GetColonyContributorQueryVariables >(GetColonyContributorDocument, { @@ -60,7 +63,7 @@ export const createColonyContributor = async ({ contributorAddress, ...rest }: CreateColonyContributorInput): Promise => { - await mutate< + await amplifyClient.mutate< CreateColonyContributorMutation, CreateColonyContributorMutationVariables >(CreateColonyContributorDocument, { @@ -81,13 +84,13 @@ export const updateColonyContributor = async ({ contributorAddress: string; }): Promise => { const { data } = - (await query( - GetAllColonyRolesDocument, - { - colonyAddress, - targetAddress: contributorAddress, - }, - )) ?? {}; + (await amplifyClient.query< + GetAllColonyRolesQuery, + GetAllColonyRolesQueryVariables + >(GetAllColonyRolesDocument, { + colonyAddress, + targetAddress: contributorAddress, + })) ?? {}; // Is there at least one role for which user has at least one permission? const hasAtLeastOnePermissionInColony = @@ -101,7 +104,7 @@ export const updateColonyContributor = async ({ ), ); - await mutate< + await amplifyClient.mutate< UpdateColonyContributorMutation, UpdateColonyContributorMutationVariables >(UpdateColonyContributorDocument, { diff --git a/apps/main-chain/src/utils/currentVersion.ts b/apps/main-chain/src/utils/currentVersion.ts index 65f1d0556..339fb3320 100644 --- a/apps/main-chain/src/utils/currentVersion.ts +++ b/apps/main-chain/src/utils/currentVersion.ts @@ -1,4 +1,4 @@ -import { mutate, query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { CreateCurrentVersionDocument, CreateCurrentVersionMutation, @@ -19,7 +19,7 @@ export const updateCurrentVersion = async ( version: number, onVersionUpdated?: () => Promise, ): Promise => { - const response = await query< + const response = await amplifyClient.query< GetCurrentVersionQuery, GetCurrentVersionQueryVariables >(GetCurrentVersionDocument, { @@ -30,7 +30,7 @@ export const updateCurrentVersion = async ( if (!currentVersion) { // If there is no DB entry for the key, create one - await mutate< + await amplifyClient.mutate< CreateCurrentVersionMutation, CreateCurrentVersionMutationVariables >(CreateCurrentVersionDocument, { @@ -44,7 +44,7 @@ export const updateCurrentVersion = async ( const databaseId = response.data?.getCurrentVersionByKey?.items[0]?.id ?? ''; - await mutate< + await amplifyClient.mutate< UpdateCurrentVersionMutation, UpdateCurrentVersionMutationVariables >(UpdateCurrentVersionDocument, { diff --git a/apps/main-chain/src/utils/decisions.ts b/apps/main-chain/src/utils/decisions.ts index 7923595e4..72f4f8a40 100644 --- a/apps/main-chain/src/utils/decisions.ts +++ b/apps/main-chain/src/utils/decisions.ts @@ -1,4 +1,4 @@ -import { mutate, query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { GetColonyDecisionByActionIdDocument, GetColonyDecisionByActionIdQuery, @@ -18,7 +18,7 @@ export const updateDecisionInDB = async ( decisionData: Omit, ): Promise => { const { data } = - (await query< + (await amplifyClient.query< GetColonyDecisionByActionIdQuery, GetColonyDecisionByActionIdQueryVariables >(GetColonyDecisionByActionIdDocument, { @@ -28,7 +28,7 @@ export const updateDecisionInDB = async ( const decision = data?.getColonyDecisionByActionId?.items[0]; if (decision) - await mutate< + await amplifyClient.mutate< UpdateColonyDecisionMutation, UpdateColonyDecisionMutationVariables >(UpdateColonyDecisionDocument, { diff --git a/apps/main-chain/src/utils/events.ts b/apps/main-chain/src/utils/events.ts index c4df945ba..ecd34f410 100644 --- a/apps/main-chain/src/utils/events.ts +++ b/apps/main-chain/src/utils/events.ts @@ -2,9 +2,8 @@ import { BigNumber, utils } from 'ethers'; import { Log } from '@ethersproject/providers'; import networkClient from '~networkClient'; -import { ContractEvent, ContractEventsSignatures } from '~types'; -import { mutate, query } from '~amplifyClient'; -import { getChainId } from '~provider'; +import amplifyClient from '~amplifyClient'; +import rpcProvider from '~provider'; import { CreateContractEventDocument, CreateContractEventMutation, @@ -14,9 +13,9 @@ import { GetContractEventQueryVariables, ChainMetadata, } from '@joincolony/graphql'; -import { blocksMap } from '~blockListener'; - -import { verbose } from './logger'; +import blockManager from '~blockManager'; +import { verbose } from '@joincolony/utils'; +import { ContractEvent, ContractEventsSignatures } from '@joincolony/blocks'; export const mapLogToContractEvent = async ( log: Log, @@ -32,10 +31,10 @@ export const mapLogToContractEvent = async ( try { // Attempt to first get a block from the map as we might have already fetched its info - let block = blocksMap.get(blockNumber); + let block = blockManager.getBlock(blockNumber); if (!block) { block = await provider.getBlock(blockNumber); - blocksMap.set(blockNumber, block); + blockManager.updateBlocksMap(blockNumber, block); } const { hash: blockHash, timestamp } = block; @@ -68,7 +67,7 @@ export const saveEvent = async (event: ContractEvent): Promise => { 'Event does not have a signature. Possibly bad event data. Refusing the save to database!', ); } - const chainId = getChainId(); + const chainId = rpcProvider.getChainId(); const { name, @@ -153,17 +152,17 @@ export const saveEvent = async (event: ContractEvent): Promise => { if (process.env.NODE_ENV !== 'production') { const { id: existingContractEventId } = ( - await query( - GetContractEventDocument, - { - id: contractEvent.id, - }, - ) + await amplifyClient.query< + GetContractEventQuery, + GetContractEventQueryVariables + >(GetContractEventDocument, { + id: contractEvent.id, + }) )?.data?.getContractEvent ?? {}; existingContractEvent = existingContractEventId; } if (!existingContractEvent) { - await mutate< + await amplifyClient.mutate< CreateContractEventMutation, CreateContractEventMutationVariables >(CreateContractEventDocument, { input: contractEvent }); diff --git a/apps/main-chain/src/utils/expenditures.ts b/apps/main-chain/src/utils/expenditures.ts index 25d5fe588..c91a26eb8 100644 --- a/apps/main-chain/src/utils/expenditures.ts +++ b/apps/main-chain/src/utils/expenditures.ts @@ -1,5 +1,5 @@ import { BigNumber, utils } from 'ethers'; -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ExpenditureBalance, @@ -9,7 +9,7 @@ import { GetExpenditureByNativeFundingPotIdAndColonyQueryVariables, } from '@joincolony/graphql'; -import { output } from './logger'; +import { output } from '@joincolony/utils'; import { insertAtIndex } from './arrays'; export const getExpenditureDatabaseId = ( @@ -85,7 +85,7 @@ export const getExpenditureByFundingPot = async ( colonyAddress: string, fundingPotId: number, ): Promise => { - const response = await query< + const response = await amplifyClient.query< GetExpenditureByNativeFundingPotIdAndColonyQuery, GetExpenditureByNativeFundingPotIdAndColonyQueryVariables >(GetExpenditureByNativeFundingPotIdAndColonyDocument, { diff --git a/apps/main-chain/src/utils/extensions/getColonyExtensions.ts b/apps/main-chain/src/utils/extensions/getColonyExtensions.ts index dd2ede243..34841fbec 100644 --- a/apps/main-chain/src/utils/extensions/getColonyExtensions.ts +++ b/apps/main-chain/src/utils/extensions/getColonyExtensions.ts @@ -1,4 +1,4 @@ -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ExtensionFragment, GetColonyExtensionsByColonyAddressDocument, @@ -10,7 +10,7 @@ import { notNull } from '~utils/arrays'; export const getColonyExtensions = async ( colonyAddress: string, ): Promise => { - const response = await query< + const response = await amplifyClient.query< GetColonyExtensionsByColonyAddressQuery, GetColonyExtensionsByColonyAddressQueryVariables >(GetColonyExtensionsByColonyAddressDocument, { diff --git a/apps/main-chain/src/utils/extensions/installationCount.ts b/apps/main-chain/src/utils/extensions/installationCount.ts index 36bea659b..88abe19a5 100644 --- a/apps/main-chain/src/utils/extensions/installationCount.ts +++ b/apps/main-chain/src/utils/extensions/installationCount.ts @@ -1,5 +1,5 @@ import { Extension, getExtensionHash } from '@colony/colony-js'; -import { mutate, query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { CreateExtensionInstallationsCountDocument, CreateExtensionInstallationsCountMutation, @@ -11,7 +11,7 @@ import { UpdateExtensionInstallationsCountMutation, UpdateExtensionInstallationsCountMutationVariables, } from '@joincolony/graphql'; -import provider from '~provider'; +import rpcProvider from '~provider'; const extensionHashDBKeyMap = { [getExtensionHash(Extension.VotingReputation)]: 'reputationWeighted', @@ -23,8 +23,10 @@ const extensionHashDBKeyMap = { }; const getExtensionCount = async (extensionHash: string): Promise => { + const provider = rpcProvider.getProviderInstance(); + const { data } = - (await query< + (await amplifyClient.query< GetExtensionInstallationsCountQuery, GetExtensionInstallationsCountQueryVariables >(GetExtensionInstallationsCountDocument, { @@ -32,7 +34,7 @@ const getExtensionCount = async (extensionHash: string): Promise => { })) ?? {}; if (!data?.getExtensionInstallationsCount) { - await mutate< + await amplifyClient.mutate< CreateExtensionInstallationsCountMutation, CreateExtensionInstallationsCountMutationVariables >(CreateExtensionInstallationsCountDocument, { @@ -76,12 +78,12 @@ export const updateExtensionCount = async ( const key = extensionHashDBKeyMap[extensionHash]; - await mutate< + await amplifyClient.mutate< UpdateExtensionInstallationsCountMutation, UpdateExtensionInstallationsCountMutationVariables >(UpdateExtensionInstallationsCountDocument, { input: { - id: provider.network.chainId.toString(), + id: rpcProvider.getProviderInstance().network.chainId.toString(), [key]: count + 1, }, }); diff --git a/apps/main-chain/src/utils/extensions/isAddressExtension.ts b/apps/main-chain/src/utils/extensions/isAddressExtension.ts index 81e705923..c6df86ded 100644 --- a/apps/main-chain/src/utils/extensions/isAddressExtension.ts +++ b/apps/main-chain/src/utils/extensions/isAddressExtension.ts @@ -3,10 +3,10 @@ import { GetColonyExtensionQuery, GetColonyExtensionQueryVariables, } from '@joincolony/graphql'; -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; export const isAddressExtension = async (address: string): Promise => { - const response = await query< + const response = await amplifyClient.query< GetColonyExtensionQuery, GetColonyExtensionQueryVariables >(GetColonyExtensionDocument, { diff --git a/apps/main-chain/src/utils/extensions/multiSig.ts b/apps/main-chain/src/utils/extensions/multiSig.ts index 833ebc082..f3bff4b58 100644 --- a/apps/main-chain/src/utils/extensions/multiSig.ts +++ b/apps/main-chain/src/utils/extensions/multiSig.ts @@ -1,5 +1,5 @@ import { AnyMultisigPermissionsClient } from '@colony/colony-js'; -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ExtensionParams, UpdateColonyExtensionByAddressDocument, @@ -31,7 +31,7 @@ export const addMultiSigParamsToDB = async ( } const params = await getInitialMultiSigParams(multiSigClient); - await mutate< + await amplifyClient.mutate< UpdateColonyExtensionByAddressMutation, UpdateColonyExtensionByAddressMutationVariables >(UpdateColonyExtensionByAddressDocument, { diff --git a/apps/main-chain/src/utils/extensions/updateExtension.ts b/apps/main-chain/src/utils/extensions/updateExtension.ts index 1cdb87c2c..87c32c88d 100644 --- a/apps/main-chain/src/utils/extensions/updateExtension.ts +++ b/apps/main-chain/src/utils/extensions/updateExtension.ts @@ -1,4 +1,4 @@ -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { UpdateColonyExtensionByAddressDocument, UpdateColonyExtensionByAddressMutation, @@ -10,7 +10,7 @@ export const updateExtension = async ( extensionAddress: string, fieldsToUpdate: Omit, ): Promise => { - const result = await mutate< + const result = await amplifyClient.mutate< UpdateColonyExtensionByAddressMutation, UpdateColonyExtensionByAddressMutationVariables >(UpdateColonyExtensionByAddressDocument, { diff --git a/apps/main-chain/src/utils/extensions/writeExtension.ts b/apps/main-chain/src/utils/extensions/writeExtension.ts index ab12548e7..0ebaeede1 100644 --- a/apps/main-chain/src/utils/extensions/writeExtension.ts +++ b/apps/main-chain/src/utils/extensions/writeExtension.ts @@ -1,9 +1,9 @@ import { constants } from 'ethers'; import networkClient from '~networkClient'; -import { mutate, query } from '~amplifyClient'; -import { ContractEvent } from '~types'; -import { verbose, toNumber } from '~utils'; +import amplifyClient from '~amplifyClient'; +import { ContractEvent } from '@joincolony/blocks'; +import { toNumber } from '~utils'; import { CreateColonyExtensionDocument, CreateColonyExtensionMutation, @@ -24,6 +24,7 @@ import { } from '~utils/notifications'; import { updateExtension } from './updateExtension'; import { Extension, getExtensionHash } from '@colony/colony-js'; +import { verbose } from '@joincolony/utils'; const EXTENSION_SUPPORTING_NOTIFICATIONS = [ Extension.OneTxPayment, @@ -120,7 +121,7 @@ export const deleteExtensionFromEvent = async ( verbose('Extension:', extensionHash, 'uninstalled in Colony:', colony); const { data } = - (await query< + (await amplifyClient.query< GetColonyExtensionByHashAndColonyQuery, GetColonyExtensionByHashAndColonyQueryVariables >(GetColonyExtensionByHashAndColonyDocument, { @@ -144,12 +145,12 @@ const createOrUpdateColonyExtension = async ( const { isDeprecated, isDeleted, isInitialized, version } = input; const { data } = - (await query( - GetColonyExtensionDocument, - { - id: extensionAddress, - }, - )) ?? {}; + (await amplifyClient.query< + GetColonyExtensionQuery, + GetColonyExtensionQueryVariables + >(GetColonyExtensionDocument, { + id: extensionAddress, + })) ?? {}; const extension = data?.getColonyExtension?.colonyId; @@ -162,7 +163,7 @@ const createOrUpdateColonyExtension = async ( extensionHash: input.hash, }); - await mutate< + await amplifyClient.mutate< CreateColonyExtensionMutation, CreateColonyExtensionMutationVariables >(CreateColonyExtensionDocument, { diff --git a/apps/main-chain/src/utils/fundsClaims.ts b/apps/main-chain/src/utils/fundsClaims.ts index b1fd09ae0..31b2807f2 100644 --- a/apps/main-chain/src/utils/fundsClaims.ts +++ b/apps/main-chain/src/utils/fundsClaims.ts @@ -1,11 +1,11 @@ -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { CreateColonyFundsClaimDocument, CreateColonyFundsClaimMutation, CreateColonyFundsClaimMutationVariables, } from '@joincolony/graphql'; -import { getChainId } from '~provider'; -import { ContractEvent } from '~types'; +import { ContractEvent } from '@joincolony/blocks'; +import rpcProvider from '~provider'; interface CreateFundsClaimsParams { event: ContractEvent; @@ -20,9 +20,9 @@ export const createFundsClaim = async ({ amount, event: { transactionHash, logIndex, blockNumber }, }: CreateFundsClaimsParams): Promise => { - const chainId = getChainId(); + const chainId = rpcProvider.getChainId(); - await mutate< + await amplifyClient.mutate< CreateColonyFundsClaimMutation, CreateColonyFundsClaimMutationVariables >(CreateColonyFundsClaimDocument, { diff --git a/apps/main-chain/src/utils/graphql.ts b/apps/main-chain/src/utils/graphql.ts index 0485efe60..1635c3005 100644 --- a/apps/main-chain/src/utils/graphql.ts +++ b/apps/main-chain/src/utils/graphql.ts @@ -1,6 +1,6 @@ import { DocumentNode, Kind, isExecutableDefinitionNode } from 'graphql'; -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; interface GetDataResponse { items: Array | undefined; @@ -52,10 +52,10 @@ export const tryFetchGraphqlQuery = async < let currentTry = 0; while (true) { - const result = await query, TVariables>( - queryString, - variables, - ); + const result = await amplifyClient.query< + Record, + TVariables + >(queryString, variables); /* * @NOTE That this limits to only fetching one operation at a time diff --git a/apps/main-chain/src/utils/index.ts b/apps/main-chain/src/utils/index.ts index 0e3622b39..599520e66 100644 --- a/apps/main-chain/src/utils/index.ts +++ b/apps/main-chain/src/utils/index.ts @@ -1,6 +1,4 @@ -export * from './logger'; export * from './events'; -export * from './stats'; export * from './extensions'; export * from './numbers'; export * from './tokens'; diff --git a/apps/main-chain/src/utils/metadataDelta/utils.ts b/apps/main-chain/src/utils/metadataDelta/utils.ts index d7de41f6d..57ba52108 100644 --- a/apps/main-chain/src/utils/metadataDelta/utils.ts +++ b/apps/main-chain/src/utils/metadataDelta/utils.ts @@ -1,4 +1,4 @@ -import { verbose } from '~utils'; +import { verbose } from '@joincolony/utils'; import { AddVerifiedMembersOperation, RemoveVerifiedMembersOperation, diff --git a/apps/main-chain/src/utils/networkFee.ts b/apps/main-chain/src/utils/networkFee.ts index f1e1c6220..da0bbe327 100644 --- a/apps/main-chain/src/utils/networkFee.ts +++ b/apps/main-chain/src/utils/networkFee.ts @@ -1,5 +1,5 @@ import { BigNumber, BigNumberish } from 'ethers'; -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { GetCurrentNetworkInverseFeeDocument, GetCurrentNetworkInverseFeeQuery, @@ -41,7 +41,7 @@ export const getAmountWithFee = ( export const getNetworkInverseFee = async (): Promise => { const { data: networkFeeData } = - (await query< + (await amplifyClient.query< GetCurrentNetworkInverseFeeQuery, GetCurrentNetworkInverseFeeQueryVariables >(GetCurrentNetworkInverseFeeDocument)) ?? {}; diff --git a/apps/main-chain/src/utils/notifications.ts b/apps/main-chain/src/utils/notifications.ts index be3e8c8e1..292ec8cfe 100644 --- a/apps/main-chain/src/utils/notifications.ts +++ b/apps/main-chain/src/utils/notifications.ts @@ -1,5 +1,5 @@ import MagicBellClient, { Notification } from '@magicbell/core'; -import { query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { ColonyActionType, GetColonyContributorsNotificationDataDocument, @@ -70,7 +70,7 @@ const getMembersData: GetDataFn< NotificationUserFragment, { colonyAddress: string } > = async ({ colonyAddress }, nextToken) => { - const response = await query< + const response = await amplifyClient.query< GetColonyContributorsNotificationDataQuery, GetColonyContributorsNotificationDataQueryVariables >(GetColonyContributorsNotificationDataDocument, { @@ -289,7 +289,7 @@ export const sendMentionNotifications = async ({ return; } - const response = await query< + const response = await amplifyClient.query< GetNotificationUsersQuery, GetNotificationUsersQueryVariables >(GetNotificationUsersDocument, { diff --git a/apps/main-chain/src/utils/permissions.ts b/apps/main-chain/src/utils/permissions.ts index f3b60e693..7d468154f 100644 --- a/apps/main-chain/src/utils/permissions.ts +++ b/apps/main-chain/src/utils/permissions.ts @@ -3,10 +3,9 @@ import { ColonyRole, Id } from '@colony/colony-js'; import { hexStripZeros } from 'ethers/lib/utils'; -import { mutate, query } from '~amplifyClient'; -import { ContractEvent, ContractEventsSignatures } from '~types'; +import amplifyClient from '~amplifyClient'; +import { ContractEvent, ContractEventsSignatures } from '@joincolony/blocks'; import { - verbose, getCachedColonyClient, getDomainDatabaseId, mapLogToContractEvent, @@ -33,6 +32,7 @@ import { import { createColonyContributor, isAlreadyContributor } from './contributors'; import { sendPermissionsActionNotifications } from './notifications'; import { NotificationCategory } from '~types/notifications'; +import { verbose } from '@joincolony/utils'; export const BASE_ROLES_MAP = { [`role_${ColonyRole.Recovery}`]: null, @@ -221,10 +221,10 @@ export const getRolesMapFromHexString = async ( const getColonyRoleData = ( - await query( - GetColonyRoleDocument, - { id: colonyRolesDatabaseId }, - ) + await amplifyClient.query< + GetColonyRoleQuery, + GetColonyRoleQueryVariables + >(GetColonyRoleDocument, { id: colonyRolesDatabaseId }) )?.data?.getColonyRole ?? {}; Object.keys(BASE_ROLES_MAP).forEach((role) => { @@ -312,44 +312,44 @@ export const createInitialColonyRolesDatabaseEntry = async ( ); const blockNumber = firstRoleSetEvent?.blockNumber ?? 0; - await mutate( - CreateColonyRoleDocument, - { - input: { - id: rolesDatabaseId, - latestBlock: blockNumber, - // Link the Domain Model - domainId: domainDatabaseId, - // Link the Colony Model - colonyRolesId: colonyAddress, - colonyAddress, - /* - * @NOTE Link the target - * - * Note that this handler will fire even for events where the target - * is something or someone not in the database. - * - * We try to account for this, by linking address to either a user, colony, or - * extension via the target address, but it can happen regardless as the - * address can be totally random - * - * Make sure to be aware of that when fetching the query (you can still fetch - * the "targetAddress" value manually, and linking it yourself to the - * appropriate entity) - */ - targetAddress, - - // Set the permissions - ...BASE_ROLES_MAP, - role_0, - role_1, - role_2, - role_3, - role_5, - role_6, - }, + await amplifyClient.mutate< + CreateColonyRoleMutation, + CreateColonyRoleMutationVariables + >(CreateColonyRoleDocument, { + input: { + id: rolesDatabaseId, + latestBlock: blockNumber, + // Link the Domain Model + domainId: domainDatabaseId, + // Link the Colony Model + colonyRolesId: colonyAddress, + colonyAddress, + /* + * @NOTE Link the target + * + * Note that this handler will fire even for events where the target + * is something or someone not in the database. + * + * We try to account for this, by linking address to either a user, colony, or + * extension via the target address, but it can happen regardless as the + * address can be totally random + * + * Make sure to be aware of that when fetching the query (you can still fetch + * the "targetAddress" value manually, and linking it yourself to the + * appropriate entity) + */ + targetAddress, + + // Set the permissions + ...BASE_ROLES_MAP, + role_0, + role_1, + role_2, + role_3, + role_5, + role_6, }, - ); + }); verbose( `Create new Roles entry for ${targetAddress} in colony ${colonyAddress}, under domain ${nativeDomainId}`, @@ -503,45 +503,45 @@ export const createInitialMultiSigRolesDatabaseEntry = async ( ); const blockNumber = firstRoleSetEvent?.blockNumber ?? 0; - await mutate( - CreateColonyRoleDocument, - { - input: { - id: rolesDatabaseId, - latestBlock: blockNumber, - // Link the Domain Model - domainId: domainDatabaseId, - // Link the Colony Model - colonyRolesId: colonyAddress, - colonyAddress, - /* - * @NOTE Link the target - * - * Note that this handler will fire even for events where the target - * is something or someone not in the database. - * - * We try to account for this, by linking address to either a user, colony, or - * extension via the target address, but it can happen regardless as the - * address can be totally random - * - * Make sure to be aware of that when fetching the query (you can still fetch - * the "targetAddress" value manually, and linking it yourself to the - * appropriate entity) - */ - targetAddress, - - // Set the permissions - ...BASE_ROLES_MAP, - role_0, - role_1, - role_2, - role_3, - role_5, - role_6, - isMultiSig: true, - }, + await amplifyClient.mutate< + CreateColonyRoleMutation, + CreateColonyRoleMutationVariables + >(CreateColonyRoleDocument, { + input: { + id: rolesDatabaseId, + latestBlock: blockNumber, + // Link the Domain Model + domainId: domainDatabaseId, + // Link the Colony Model + colonyRolesId: colonyAddress, + colonyAddress, + /* + * @NOTE Link the target + * + * Note that this handler will fire even for events where the target + * is something or someone not in the database. + * + * We try to account for this, by linking address to either a user, colony, or + * extension via the target address, but it can happen regardless as the + * address can be totally random + * + * Make sure to be aware of that when fetching the query (you can still fetch + * the "targetAddress" value manually, and linking it yourself to the + * appropriate entity) + */ + targetAddress, + + // Set the permissions + ...BASE_ROLES_MAP, + role_0, + role_1, + role_2, + role_3, + role_5, + role_6, + isMultiSig: true, }, - ); + }); verbose( `Create new multi sig Roles entry for ${targetAddress} in colony ${colonyAddress}, under domain ${nativeDomainId}`, @@ -690,14 +690,14 @@ export const createColonyHistoricRoleDatabaseEntry = async ( const { id: existingColonyRoleId } = ( - await query< + await amplifyClient.query< GetColonyHistoricRoleQuery, GetColonyHistoricRoleQueryVariables >(GetColonyHistoricRoleDocument, { id }) )?.data?.getColonyHistoricRole ?? {}; if (!existingColonyRoleId) { - await mutate< + await amplifyClient.mutate< CreateColonyHistoricRoleMutation, CreateColonyHistoricRoleMutationVariables >(CreateColonyHistoricRoleDocument, { diff --git a/apps/main-chain/src/utils/seedDB.ts b/apps/main-chain/src/utils/seedDB.ts index 6c00b120c..ba758e35f 100644 --- a/apps/main-chain/src/utils/seedDB.ts +++ b/apps/main-chain/src/utils/seedDB.ts @@ -1,5 +1,5 @@ import { getExtensionHash, getLogs } from '@colony/colony-js'; -import { mutate } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { COLONY_CURRENT_VERSION_KEY, NETWORK_INVERSE_FEE_DATABASE_ID, @@ -22,7 +22,7 @@ const seedNetworkFee = async (): Promise => { const networkInverseFee = await networkClient.getFeeInverse(); const convertedFee = networkInverseFee.toString(); - await mutate< + await amplifyClient.mutate< CreateCurrentNetworkInverseFeeMutation, CreateCurrentNetworkInverseFeeMutationVariables >(CreateCurrentNetworkInverseFeeDocument, { diff --git a/apps/main-chain/src/utils/stats.ts b/apps/main-chain/src/utils/stats.ts deleted file mode 100644 index c9921ac98..000000000 --- a/apps/main-chain/src/utils/stats.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { mutate, query } from '~amplifyClient'; -import { - CreateStatsDocument, - CreateStatsMutation, - CreateStatsMutationVariables, - GetStatsDocument, - GetStatsQuery, - GetStatsQueryVariables, - UpdateStatsDocument, - UpdateStatsMutation, - UpdateStatsMutationVariables, -} from '@joincolony/graphql'; - -import { output, verbose } from './logger'; - -let stats: Record = {}; - -type ObjectOrFunction = - | Record - | ((jsonFile: Record) => Record); - -/* - * Update stats with a given argument - * It accepts either a object fragment (or full object) that will get appended to the stats, - * or a callback (which receives the current stats) and needs to return the new object - * that will be written back - */ -export const updateStats = async ( - objectOrFunction: ObjectOrFunction, -): Promise => { - if (typeof objectOrFunction === 'function') { - stats = { - ...stats, - ...objectOrFunction(stats), - }; - } else { - stats = { - ...stats, - ...objectOrFunction, - }; - } - - await mutate( - UpdateStatsDocument, - { - value: JSON.stringify(stats), - }, - ); - - verbose('Stats file updated'); -}; - -// This exists as a function to prevent accidental overwriting of the `stats` variable -export const getStats = (): typeof stats => ({ ...stats }); - -export const getLastBlockNumber = (): number => { - if (Number.isInteger(stats.lastBlockNumber)) { - return Number(stats.lastBlockNumber); - } - /* - * @NOTE This prevents accidental database stats overwriting if the API / GraphQL - * endpoint is not accessible - * - * It will throw the block ingestor (the pod that it's running on) into an restart - * loop until the API is accessible again - */ - throw new Error('Could not get last block number from stats. Aborting.'); -}; - -export const setLastBlockNumber = (lastBlockNumber: number): void => { - updateStats({ lastBlockNumber }); -}; - -/** - * Function fetching the last stored stats from the DB - * If no stats entry is found, it will create one - */ -export const initStats = async (): Promise => { - const { value: jsonStats } = - (await query(GetStatsDocument, {})) - ?.data?.getIngestorStats ?? {}; - - if (!jsonStats) { - stats = { - lastBlockNumber: 0, - }; - - await mutate( - CreateStatsDocument, - { - value: JSON.stringify(stats), - }, - ); - } else { - try { - stats = JSON.parse(jsonStats); - } catch { - output( - 'Could not parse stats from the DB. The value is not a valid JSON.', - ); - } - } -}; diff --git a/apps/main-chain/src/utils/tokens.ts b/apps/main-chain/src/utils/tokens.ts index 829b5ff88..d0ec80f0f 100644 --- a/apps/main-chain/src/utils/tokens.ts +++ b/apps/main-chain/src/utils/tokens.ts @@ -1,7 +1,7 @@ import { constants } from 'ethers'; import { BlockTag } from '@ethersproject/abstract-provider'; -import { mutate, query } from '~amplifyClient'; +import amplifyClient from '~amplifyClient'; import { getCachedColonyClient } from './clients'; import { notNull } from './arrays'; @@ -136,7 +136,7 @@ export const updateColonyTokens = async ( * Call the GetTokenFromEverywhere query to ensure the token * gets added to the DB if it doesn't already exist */ - await query< + await amplifyClient.query< GetTokenFromEverywhereQuery, GetTokenFromEverywhereQueryVariables >(GetTokenFromEverywhereDocument, { @@ -149,7 +149,7 @@ export const updateColonyTokens = async ( * Only create colony/token entry in the DB if the token data was returned by the GetTokenFromEverywhereQuery. * Otherwise, it will cause any query referencing it to fail */ - await mutate< + await amplifyClient.mutate< CreateColonyTokensMutation, CreateColonyTokensMutationVariables >(CreateColonyTokensDocument, { @@ -171,7 +171,7 @@ export const updateColonyTokens = async ( // If we can't find it, e.g. because it has already been removed by another motion, do nothing. if (colonyTokenId) { - await mutate< + await amplifyClient.mutate< DeleteColonyTokensMutation, DeleteColonyTokensMutationVariables >(DeleteColonyTokensDocument, { @@ -201,7 +201,7 @@ export const fetchColoniesByNativeToken = async ( }; const { data } = - (await query< + (await amplifyClient.query< GetColonyByNativeTokenIdQuery, GetColonyByNativeTokenIdQueryVariables >(GetColonyByNativeTokenIdDocument, queryVariables)) ?? {}; @@ -212,7 +212,7 @@ export const fetchColoniesByNativeToken = async ( while (queryVariables.nextToken) { const { data: nextData } = - (await query< + (await amplifyClient.query< GetColonyByNativeTokenIdQuery, GetColonyByNativeTokenIdQueryVariables >(GetColonyByNativeTokenIdDocument, queryVariables)) ?? {}; @@ -232,21 +232,21 @@ export const updateSingleColonyNativeTokenStatuses = async ( colony: Pick, nativeTokenStatus: Omit, ): Promise => { - await mutate( - UpdateColonyDocument, - { - input: { - id: colony.id, - status: { - ...colony.status, - nativeToken: { - ...colony.status?.nativeToken, - ...nativeTokenStatus, - }, + await amplifyClient.mutate< + UpdateColonyMutation, + UpdateColonyMutationVariables + >(UpdateColonyDocument, { + input: { + id: colony.id, + status: { + ...colony.status, + nativeToken: { + ...colony.status?.nativeToken, + ...nativeTokenStatus, }, }, }, - ); + }); }; /* diff --git a/apps/main-chain/src/utils/transactionHasEvent.ts b/apps/main-chain/src/utils/transactionHasEvent.ts index 821965fdb..ad53ffd7f 100644 --- a/apps/main-chain/src/utils/transactionHasEvent.ts +++ b/apps/main-chain/src/utils/transactionHasEvent.ts @@ -1,7 +1,8 @@ import { utils } from 'ethers'; -import provider from '~provider'; -import { ContractEventsSignatures } from '~types'; +import rpcProvider from '~provider'; + +import { ContractEventsSignatures } from '@joincolony/blocks'; /** * For a given tx hash, checks whether the transaction contains a matching event @@ -10,7 +11,9 @@ export const transactionHasEvent = async ( transactionHash: string, eventSignature: ContractEventsSignatures, ): Promise => { - const receipt = await provider.getTransactionReceipt(transactionHash); + const receipt = await rpcProvider + .getProviderInstance() + .getTransactionReceipt(transactionHash); return receipt.logs.some((log) => log.topics.includes(utils.id(eventSignature)), ); diff --git a/apps/proxy-chain/.env.example b/apps/proxy-chain/.env.example new file mode 100644 index 000000000..3a340963c --- /dev/null +++ b/apps/proxy-chain/.env.example @@ -0,0 +1,4 @@ +# for another app, just add an env filed called .env.proxy2 +CHAIN_RPC_ENDPOINT=http://localhost:8546 +CHAIN_NETWORK_CONTRACT=0x777760996135F0791E2e1a74aFAa060711197777 +STATS_PORT=10002 diff --git a/apps/proxy-chain/package.json b/apps/proxy-chain/package.json new file mode 100644 index 000000000..65a2a49ec --- /dev/null +++ b/apps/proxy-chain/package.json @@ -0,0 +1,18 @@ +{ + "name": "@joincolony/proxy-chain", + "version": "1.0.0", + "main": "src/index.ts", + "scripts": { + "build": "rm -rf dist/* && npx tsc", + "start": "node -r ts-node/register/transpile-only -r tsconfig-paths/register -r ./dist/env.js dist/index.js", + "dev": "NODE_ENV=development ts-node-dev -r tsconfig-paths/register -r ./src/env.ts src/index.ts", + "prod": "pnpm run build && NODE_ENV=production pnpm run start", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@joincolony/blocks": "workspace:^", + "@joincolony/clients": "workspace:^", + "@joincolony/graphql": "workspace:*", + "@joincolony/utils": "workspace:^" + } +} diff --git a/apps/proxy-chain/src/amplifyClient.ts b/apps/proxy-chain/src/amplifyClient.ts new file mode 100644 index 000000000..381535806 --- /dev/null +++ b/apps/proxy-chain/src/amplifyClient.ts @@ -0,0 +1,8 @@ +import { AmplifyClient } from '@joincolony/clients'; + +const amplifyClient = new AmplifyClient( + process.env.AWS_APPSYNC_ENDPOINT || '', + process.env.AWS_APPSYNC_KEY || '', +); + +export default amplifyClient; diff --git a/apps/proxy-chain/src/blockManager.ts b/apps/proxy-chain/src/blockManager.ts new file mode 100644 index 000000000..bbaac0e00 --- /dev/null +++ b/apps/proxy-chain/src/blockManager.ts @@ -0,0 +1,8 @@ +import { BlockManager } from '@joincolony/blocks'; +import eventManager from '~eventManager'; +import rpcProvider from '~provider'; +import statsManager from '~statsManager'; + +const blockManager = new BlockManager(eventManager, rpcProvider, statsManager); + +export default blockManager; diff --git a/apps/proxy-chain/src/env.ts b/apps/proxy-chain/src/env.ts new file mode 100644 index 000000000..4cc0180df --- /dev/null +++ b/apps/proxy-chain/src/env.ts @@ -0,0 +1,6 @@ +import path from 'path'; +import dotenv from 'dotenv'; + +const appEnvFile = process.env.ENV_FILE || '.env'; +dotenv.config({ path: path.resolve(__dirname, `../${appEnvFile}`) }); +dotenv.config({ path: path.resolve(__dirname, '../../../.env') }); diff --git a/apps/proxy-chain/src/eventListeners/colony.ts b/apps/proxy-chain/src/eventListeners/colony.ts new file mode 100644 index 000000000..96f993a75 --- /dev/null +++ b/apps/proxy-chain/src/eventListeners/colony.ts @@ -0,0 +1,12 @@ +import { ContractEventsSignatures } from '@joincolony/blocks'; +import { addProxyColoniesEventListener } from './proxyColonies'; +import { handleProxyColonyDeployed } from '~handlers/proxyColonies'; + +export const setupListenersForColonies = async (): Promise => { + + addProxyColoniesEventListener( + ContractEventsSignatures.ProxyColonyDeployed, + handleProxyColonyDeployed, + ); + +}; \ No newline at end of file diff --git a/apps/proxy-chain/src/eventListeners/index.ts b/apps/proxy-chain/src/eventListeners/index.ts new file mode 100644 index 000000000..7990ae747 --- /dev/null +++ b/apps/proxy-chain/src/eventListeners/index.ts @@ -0,0 +1,3 @@ +export * from './network'; +export * from './proxyColonies'; +export * from './colony'; diff --git a/apps/proxy-chain/src/eventListeners/network.ts b/apps/proxy-chain/src/eventListeners/network.ts new file mode 100644 index 000000000..7ec858f07 --- /dev/null +++ b/apps/proxy-chain/src/eventListeners/network.ts @@ -0,0 +1,16 @@ +import { EventListenerType , ContractEventsSignatures, EventHandler } from '@joincolony/blocks'; +import { utils } from 'ethers'; + +import eventManager from '~eventManager'; + +export const addNetworkEventListener = ( + eventSignature: ContractEventsSignatures, + handler: EventHandler, +): void => + eventManager.addEventListener({ + type: EventListenerType.Network, + eventSignature, + topics: [utils.id(eventSignature)], + address: process.env.CHAIN_CONTRACT_ADDRESS ?? '', + handler, + }); diff --git a/apps/proxy-chain/src/eventListeners/proxyColonies.ts b/apps/proxy-chain/src/eventListeners/proxyColonies.ts new file mode 100644 index 000000000..73ea92e5c --- /dev/null +++ b/apps/proxy-chain/src/eventListeners/proxyColonies.ts @@ -0,0 +1,16 @@ +import { utils } from 'ethers'; + +import { ContractEventsSignatures, EventHandler , EventListenerType } from '@joincolony/blocks'; +import eventManager from '~eventManager'; + +export const addProxyColoniesEventListener = ( + eventSignature: ContractEventsSignatures, + handler: EventHandler, +): void => + eventManager.addEventListener({ + type: EventListenerType.ProxyColonies, + eventSignature, + topics: [utils.id(eventSignature)], + address: process.env.CHAIN_CONTRACT_ADDRESS ?? '', + handler, + }); diff --git a/apps/proxy-chain/src/eventManager.ts b/apps/proxy-chain/src/eventManager.ts new file mode 100644 index 000000000..b57b8481f --- /dev/null +++ b/apps/proxy-chain/src/eventManager.ts @@ -0,0 +1,6 @@ +import { EventManager } from '@joincolony/blocks'; +import rpcProvider from '~provider'; + +const eventManager = new EventManager(rpcProvider); + +export default eventManager; diff --git a/apps/proxy-chain/src/handlers/proxyColonies/index.ts b/apps/proxy-chain/src/handlers/proxyColonies/index.ts new file mode 100644 index 000000000..504b52d11 --- /dev/null +++ b/apps/proxy-chain/src/handlers/proxyColonies/index.ts @@ -0,0 +1 @@ +export * from './proxyColonyDeployed'; diff --git a/apps/proxy-chain/src/handlers/proxyColonies/proxyColonyDeployed.ts b/apps/proxy-chain/src/handlers/proxyColonies/proxyColonyDeployed.ts new file mode 100644 index 000000000..2e7487334 --- /dev/null +++ b/apps/proxy-chain/src/handlers/proxyColonies/proxyColonyDeployed.ts @@ -0,0 +1,35 @@ +import { + CreateProxyColonyDocument, + CreateProxyColonyMutation, + CreateProxyColonyMutationVariables, +} from '@joincolony/graphql'; +import { ContractEvent } from '@joincolony/blocks'; +import amplifyClient from '~amplifyClient'; +import rpcProvider from '~provider'; +import { output } from '@joincolony/utils'; + +export const handleProxyColonyDeployed = async ( + event: ContractEvent, +): Promise => { + console.log('proxy colony deployed event', event); + const { proxyColony: proxyColonyAddress } = event.args; + + if (!proxyColonyAddress) { + output('No proxyColony emitted!'); + return; + } + + const chainId = rpcProvider.getChainId(); + + await amplifyClient.mutate< + CreateProxyColonyMutation, + CreateProxyColonyMutationVariables + >(CreateProxyColonyDocument, { + input: { + id: `${proxyColonyAddress}_${chainId}`, + colonyAddress: proxyColonyAddress, + chainId, + isActive: true, + }, + }); +}; diff --git a/apps/proxy-chain/src/index.ts b/apps/proxy-chain/src/index.ts new file mode 100644 index 000000000..78cd28653 --- /dev/null +++ b/apps/proxy-chain/src/index.ts @@ -0,0 +1,34 @@ +import 'cross-fetch/polyfill'; +import { utils } from 'ethers'; + +import '~amplifyClient'; +import '~eventManager'; +import blockManager from '~blockManager'; +import rpcProvider from '~provider'; +import { startStatsServer } from '~stats'; +import { setupListenersForColonies } from '~eventListeners'; + +utils.Logger.setLogLevel(utils.Logger.levels.ERROR); + +const start = async (): Promise => { + await rpcProvider.initialiseProvider(); + /** + * Start express server providing stats and fetch existing stats from the DB + */ + await startStatsServer(); + + /** + * Setup the listeners we care about for existing colonies + * This has to be done before the block listener is started to ensure the events are not missed + */ + await setupListenersForColonies(); + + /** + * Start the main block listener + */ + blockManager.startBlockListener(); + + console.log('started'); +}; + +start(); diff --git a/apps/proxy-chain/src/networkClient.ts b/apps/proxy-chain/src/networkClient.ts new file mode 100644 index 000000000..d9f351999 --- /dev/null +++ b/apps/proxy-chain/src/networkClient.ts @@ -0,0 +1,11 @@ +import { Network } from '@colony/colony-js'; + +import rpcProvider from '~provider'; + +import { NetworkClient } from '@joincolony/clients'; + +export default (new NetworkClient( + rpcProvider, + (process.env.CHAIN_NETWORK as Network) || Network.Custom, + process.env.CHAIN_NETWORK_CONTRACT || '', +)).getInstance(); diff --git a/apps/proxy-chain/src/provider.ts b/apps/proxy-chain/src/provider.ts new file mode 100644 index 000000000..eed068b14 --- /dev/null +++ b/apps/proxy-chain/src/provider.ts @@ -0,0 +1,4 @@ +import { RpcProvider } from '@joincolony/clients'; + +const rpcProvider = new RpcProvider(process.env.CHAIN_RPC_ENDPOINT); +export default rpcProvider; diff --git a/apps/proxy-chain/src/stats.ts b/apps/proxy-chain/src/stats.ts new file mode 100644 index 000000000..44fbca078 --- /dev/null +++ b/apps/proxy-chain/src/stats.ts @@ -0,0 +1,55 @@ +import express from 'express'; + +import eventManager from '~eventManager'; +import rpcProvider from '~provider'; +import { output } from '@joincolony/utils'; +import statsManager from '~statsManager'; + +// @NOTE this can probably be moved to the colonyAdded handler +export const coloniesSet = new Set(); + +// @NOTE just copy this entire file later on for now +const app = express(); +const port = process.env.STATS_PORT; + +app.get('/', (_, res) => { + res + .type('text/plain') + .send(process.env.NODE_ENV !== 'production' ? 'Block Ingestor' : ''); +}); + +/* + * Use to check if service is alive + */ +app.get('/liveness', (_, res) => res.sendStatus(200)); + +/* + * Use to check various service stats + */ +app.get('/stats', async (_, res) => { + const stats = statsManager.getStats(); + res.type('json').send(stats); +}); + +/** + * Use to check currently active listeners + */ +app.get('/listeners', async (_, res) => { + res.type('json').send(eventManager.getListenersStats()); +}); + +export const startStatsServer = async (): Promise => { + if (!port) { + return; + } + + await statsManager.initStats(); + const lastBlockNumber = statsManager.getLastBlockNumber(); + + app.listen(port, async () => { + output('Block Ingestor started on chain', rpcProvider.getChainId()); + output(`Stats available at http://localhost:${port}/stats`); + output(`Liveness check available at http://localhost:${port}/liveness`); + output(`Last processed block number: ${lastBlockNumber}`); + }); +}; diff --git a/apps/proxy-chain/src/statsManager.ts b/apps/proxy-chain/src/statsManager.ts new file mode 100644 index 000000000..65a7a19b9 --- /dev/null +++ b/apps/proxy-chain/src/statsManager.ts @@ -0,0 +1,7 @@ +import { StatsManager } from '@joincolony/blocks'; +import amplifyClient from './amplifyClient'; +import rpcProvider from '~provider'; + +const statsManager = new StatsManager(amplifyClient, rpcProvider); + +export default statsManager; diff --git a/apps/proxy-chain/tsconfig.json b/apps/proxy-chain/tsconfig.json new file mode 100644 index 000000000..74d15bca4 --- /dev/null +++ b/apps/proxy-chain/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "baseUrl": ".", + "paths": { + "~*": ["src/*"] + }, + "outDir": "./dist" + }, + "include": ["src"] +} diff --git a/package.json b/package.json index fde15a3e9..c864c9a7c 100644 --- a/package.json +++ b/package.json @@ -10,8 +10,12 @@ "prod": "npm run build && NODE_ENV=production npm run start", "dev:main-chain": "pnpm --filter @joincolony/main-chain run dev", "start:main-chain": "pnpm --filter @joincolony/main-chain run start", + "dev:proxy-chain": "pnpm --filter @joincolony/proxy-chain run dev", + "dev:proxy-chain-2": "ENV_FILE=.env.proxy-2 pnpm --filter @joincolony/proxy-chain run dev", + "dev:all-proxies": "pnpm run dev:proxy-chain & pnpm run dev:proxy-chain-2", + "start:proxy-chain": "pnpm --filter @joincolony/proxy-chain run start", "typecheck": "pnpm -r run typecheck", - "lint": "eslint src/ --ext .ts", + "lint": "eslint . --ext .ts", "preinstall": "bash scripts/generate-temp-files.sh", "prepare": "husky install", "codegen": "pnpm --filter graphql run codegen" diff --git a/packages/blocks/package.json b/packages/blocks/package.json new file mode 100644 index 000000000..1df7ae5d4 --- /dev/null +++ b/packages/blocks/package.json @@ -0,0 +1,10 @@ +{ + "name": "@joincolony/blocks", + "main": "src/index.ts", + "version": "1.0.0", + "dependencies": { + "@joincolony/clients": "workspace:*", + "@joincolony/graphql": "workspace:*", + "@joincolony/utils": "workspace:*" + } +} diff --git a/packages/blocks/src/blocks/blockManager.ts b/packages/blocks/src/blocks/blockManager.ts new file mode 100644 index 000000000..fad1ed524 --- /dev/null +++ b/packages/blocks/src/blocks/blockManager.ts @@ -0,0 +1,344 @@ +import { Log } from '@ethersproject/abstract-provider'; +import { output, verbose } from '@joincolony/utils'; +import { EventManager, ContractEvent, EthersObserverEvents } from '../events'; +import { + Block, + BlockWithTransactions, +} from './types'; +import { RpcProvider } from '@joincolony/clients'; +import { utils } from 'ethers'; +import { StatsManager } from '../stats/statsManager'; + +export const BLOCK_PAGING_SIZE = process.env.BLOCK_PAGING_SIZE + ? parseInt(process.env.BLOCK_PAGING_SIZE, 10) + : 1000; + +export class BlockManager { + private readonly blocksMap = new Map(); + private readonly blockLogs = new Map(); + private latestSeenBlockNumber = 0; + private isProcessing = false; + private readonly eventManager: EventManager; + private readonly rpcProvider: RpcProvider; + private readonly statsManager: StatsManager; + private timeNow = Date.now(); + private timePrev = 0; + + constructor( + eventManager: EventManager, + rpcProvider: RpcProvider, + statsManager: StatsManager, + ) { + this.eventManager = eventManager; + this.rpcProvider = rpcProvider; + this.statsManager = statsManager; + } + + public getBlock(blockNumber: number): Block | BlockWithTransactions { + return this.blocksMap.get(blockNumber); + } + + public updateBlocksMap( + blockNumber: number, + block: Block | BlockWithTransactions, + ): void { + this.blocksMap.set(blockNumber, block); + } + + public getLatestSeenBlockNumber(): number { + return this.latestSeenBlockNumber; + } + + public startBlockListener(): void { + this.rpcProvider + .getProviderInstance() + .on(EthersObserverEvents.Block, async (blockNumber: number) => { + try { + this.latestSeenBlockNumber = Math.max( + this.latestSeenBlockNumber, + blockNumber, + ); + output(`Block ${blockNumber} added to the queue`); + await this.processNextBlock(); + } catch (error) { + throw new Error( + `Observed block ${blockNumber} but failed to get its data: ${error}`, + ); + } + }); + + output('Block listener started'); + this.trackMissedBlocks(); + } + + private async trackMissedBlocks(): Promise { + const lastBlockNumber = this.statsManager.getLastBlockNumber(); + const currentBlockNumber = await this.rpcProvider + .getProviderInstance() + .getBlockNumber(); + + if (lastBlockNumber >= currentBlockNumber) return; + + output( + `Processing blocks from ${lastBlockNumber + 1} to ${currentBlockNumber}`, + ); + this.latestSeenBlockNumber = Math.max( + this.latestSeenBlockNumber, + currentBlockNumber, + ); + await this.processNextBlock(); + } + + private async processNextBlock(): Promise { + if (this.isProcessing) { + return; + } + + // Only allow one instance of the function to run at any given time + this.isProcessing = true; + + let lastBlockNumber = this.statsManager.getLastBlockNumber(); + + // Process as many blocks as are available sequentially + while (lastBlockNumber < this.getLatestSeenBlockNumber()) { + const currentBlockNumber = lastBlockNumber + 1; + if (currentBlockNumber % BLOCK_PAGING_SIZE === 0) { + if (this.timePrev > 0) { + this.timePrev = this.timeNow; + this.timeNow = Date.now(); + output( + `Time taken for last ${BLOCK_PAGING_SIZE} blocks: ${ + this.timeNow - this.timePrev + }ms`, + ); + output( + `Estimated time to sync: ${ + ((this.timeNow - this.timePrev) * + (this.getLatestSeenBlockNumber() - + this.statsManager.getLastBlockNumber())) / + 1000 + }ms`, + ); + output( + `Overall progress: ${currentBlockNumber} / ${this.getLatestSeenBlockNumber()}`, + ); + } else { + this.timePrev = this.timeNow; + } + } + + if (!this.blockLogs.get(currentBlockNumber)) { + // BLOCK_PAGING_SIZE - 1 thanks to fenceposts + const nMoreBlocks = Math.min( + this.getLatestSeenBlockNumber() - currentBlockNumber, + BLOCK_PAGING_SIZE - 1, + ); + + verbose( + 'Querying for logs', + currentBlockNumber, + 'to', + currentBlockNumber + nMoreBlocks, + ); + + const logs = await this.rpcProvider.getProviderInstance().getLogs({ + fromBlock: currentBlockNumber, + toBlock: currentBlockNumber + nMoreBlocks, + }); + + verbose( + `Fetched ${logs.length} logs`, + currentBlockNumber, + 'to', + currentBlockNumber + nMoreBlocks, + ); + + // initialize blockLogs + for ( + let i = currentBlockNumber; + i <= currentBlockNumber + nMoreBlocks; + i += 1 + ) { + this.blockLogs.set(i, []); + } + + let logIndex = 0; + let pushingBlock = 0; + let pushingLogs: Log[] = []; + + logs.forEach((log) => { + // As we push logs in to blockLogs, check they're in order + // (They should be...) + if (log.blockNumber !== pushingBlock) { + if (pushingBlock > log.blockNumber) { + output( + `Blocks (that logs from query are in) are not monotonically increasing`, + ); + process.exit(1); + } + this.blockLogs.set(pushingBlock, [...pushingLogs]); + pushingBlock = log.blockNumber; + pushingLogs = []; + logIndex = 0; + } + if (log.logIndex !== logIndex) { + output(`Logs are out of order for block ${log.blockNumber}`); + process.exit(1); + } + pushingLogs.push(log); + logIndex += 1; + }); + // Push the logs in the last block + this.blockLogs.set(pushingBlock, [...pushingLogs]); + } + + // Get logs contained in the current block + const logs = this.blockLogs.get(currentBlockNumber); + if (!logs) { + throw new Error( + `Could not find logs for block ${currentBlockNumber}, but should have been fetched`, + ); + } + + /* + * Logic needed to account for blocks that get emmited, but which don't have the logs indexed yet + * This happens in networks with very fast block times, like arbitrum (<=250ms block times) + * See: https://github.com/ethers-io/ethers.js/issues/3486 + * + * Basically, the change that @area implemented here is to try and detect if a block actually has + * logs, but which don't get retrived using the `getLogs` call. + * If that happens, it means the block was emitted, but the logs weren't indexed yet, at which point + * we just short-circuit and re-process the block. + * We do this enough times, until the logs are actually indexed. + */ + if (logs.length === 0) { + verbose('No logs seen in block', currentBlockNumber); + // Check whether block actually has no logs + let block = this.blocksMap.get(currentBlockNumber); + if ( + !block || + (block.transactions as string[]).every((tx) => typeof tx === 'string') + ) { + block = await this.rpcProvider + .getProviderInstance() + .getBlockWithTransactions(currentBlockNumber); + // May as well save this block in the blocksMap in case it turns out we need it in mapLogToContractEvent + this.blocksMap.set(currentBlockNumber, block); + } + + let mustReindex = false; + for (const tx of block.transactions) { + if (typeof tx === 'string') { + throw Error('tx was a string, but should have been a TxResponse'); + } + const txReceipt = await this.rpcProvider + .getProviderInstance() + .getTransactionReceipt(tx.hash); + if (txReceipt.logs.length > 0) { + verbose( + `Proved ${currentBlockNumber} has logs, but weren't given any, will reindex`, + ); + mustReindex = true; + // Then the block has events, and they've not been indexed yet. + // We exit out of this handler, and wait until they've been indexed. + // We remove the empty array from blockLogs to cause the getLogs call to be made again + this.blockLogs.delete(currentBlockNumber); + // Now we've proved we're missing events, don't need to look at any other transactions in + // this block. + break; + } + } + if (mustReindex) { + continue; + } + } + + for (const log of logs) { + // Find listeners that match the log + const listeners = this.eventManager.getMatchingListeners( + log.topics, + log.address, + ); + if (!listeners.length) { + continue; + } + + for (const listener of listeners) { + // In order to parse the log, we need an ethers interface + const iface = this.eventManager.getInterfaceByListener(listener); + if (!iface) { + output( + `Failed to get an interface for a log with listener type ${listener.type}`, + ); + continue; + } + + const event = await this.mapLogToContractEvent(log, iface); + if (!event) { + output( + `Failed to map log describing event ${listener.eventSignature} in transaction ${log.transactionHash} `, + ); + continue; + } + + // Call the handler in a blocking way to ensure events get processed sequentially + await listener.handler(event, listener); + } + } + + verbose('processed block', currentBlockNumber); + + lastBlockNumber = currentBlockNumber; + this.statsManager.setLastBlockNumber(currentBlockNumber); + this.blockLogs.delete(currentBlockNumber); + this.blocksMap.delete(currentBlockNumber); + } + + this.isProcessing = false; + } + + public mapLogToContractEvent = async ( + log: Log, + iface: utils.Interface, + ): Promise => { + const { + transactionHash, + logIndex, + blockNumber, + address: eventContractAddress, + } = log; + + try { + // Attempt to first get a block from the map as we might have already fetched its info + let block = this.blocksMap.get(blockNumber); + if (!block) { + block = await this.rpcProvider + .getProviderInstance() + .getBlock(blockNumber); + this.blocksMap.set(blockNumber, block); + } + + const { hash: blockHash, timestamp } = block; + const parsedLog = iface.parseLog(log); + + return { + ...parsedLog, + blockNumber, + transactionHash, + logIndex, + contractAddress: eventContractAddress, + blockHash, + timestamp, + }; + } catch (error) { + /* + * Silent Error + * + * This does not need to be loud since, at times, you'll map through a whole + * lot of events which might not know how to interface with since they were + * generated by other contracts + */ + return null; + } + }; +} diff --git a/packages/blocks/src/blocks/index.ts b/packages/blocks/src/blocks/index.ts new file mode 100644 index 000000000..c0b9249f3 --- /dev/null +++ b/packages/blocks/src/blocks/index.ts @@ -0,0 +1,2 @@ +export * from './types'; +export * from './blockManager'; \ No newline at end of file diff --git a/packages/blocks/src/blocks/types.ts b/packages/blocks/src/blocks/types.ts new file mode 100644 index 000000000..7746c8762 --- /dev/null +++ b/packages/blocks/src/blocks/types.ts @@ -0,0 +1,6 @@ +export type ChainID = string; + +export type Block = Awaited; +// @TODO ReturnType +export type BlockWithTransactions = Awaited; +// @TODO ReturnType \ No newline at end of file diff --git a/packages/blocks/src/events/eventManager.ts b/packages/blocks/src/events/eventManager.ts new file mode 100644 index 000000000..297cb08b5 --- /dev/null +++ b/packages/blocks/src/events/eventManager.ts @@ -0,0 +1,158 @@ +import { verbose } from '@joincolony/utils'; +import { EventListener, EventListenerType } from './types'; +import { RpcProvider } from '@joincolony/clients'; +import { utils, constants } from 'ethers'; +import { + IColonyEvents__factory as ColonyEventsFactory, + VotingReputationEvents__factory as VotingReputationEventsFactory, + StakedExpenditureEvents__factory as StakedExpenditureEventsFactory, + TokenEvents__factory as TokenEventsFactory, + StagedExpenditureEvents__factory as StagedExpenditureEventsFactory, + OneTxPaymentEvents__factory as OneTxPaymentEventsFactory, + StreamingPaymentsEvents__factory as StreamingPaymentsEventsFactory, + MultisigPermissionsEvents__factory as MultisigPermissionsEventsFactory, + IColonyNetworkEvents__factory as ColonyNetworkEventsFactory, +} from '@colony/events'; +import { Extension, getExtensionHash } from '@colony/colony-js'; + +// @TODO @chmanie is gonna make this better, for now let's just hardcode the proxy colony events +const ProxyColonyEvents = new utils.Interface([ + 'event ProxyColonyRequested(uint256 destinationChainId, bytes32 salt)', + 'event ProxyColonyDeployed(address proxyColony)', +]); + +export class EventManager { + private listeners: EventListener[] = []; + private readonly rpcProvider: RpcProvider; + + constructor(rpcProvider: RpcProvider) { + this.rpcProvider = rpcProvider; + } + + public getEventListeners(): EventListener[] { + return this.listeners; + } + + public setEventListeners(newListeners: EventListener[]): void { + this.listeners = newListeners; + } + + public addEventListener(listener: EventListener): void { + verbose( + `Added listener for event ${listener.eventSignature}`, + listener.address ? `filtering address ${listener.address}` : '', + ); + this.listeners.push(listener); + } + + public getMatchingListeners( + logTopics: string[], + logAddress: string, + ): EventListener[] { + return this.listeners.filter((listener) => { + if (listener.address && logAddress !== listener.address) { + return false; + } + + if (listener.topics.length > logTopics.length) { + return false; + } + + return listener.topics.every((topic, index) => { + return ( + topic === null || + topic.toLowerCase() === logTopics[index].toLowerCase() + ); + }); + }); + } + + public getListenersStats(): string { + return JSON.stringify(this.listeners); + } + + /** + * Function returning ABI-derived interface for a given event listener type, + * which is later used for parsing event logs + */ + public getInterfaceByListener( + listener: EventListener, + ): utils.Interface | null { + const provider = this.rpcProvider.getProviderInstance(); + const { type: listenerType } = listener; + + switch (listenerType) { + case EventListenerType.Network: { + return ColonyNetworkEventsFactory.connect( + constants.AddressZero, + provider, + ).interface; + } + case EventListenerType.ProxyColonies: { + return ProxyColonyEvents; + } + case EventListenerType.Colony: { + return ColonyEventsFactory.connect(constants.AddressZero, provider) + .interface; + } + case EventListenerType.Extension: { + return this.getInterfaceByExtensionHash(listener.extensionHash); + } + case EventListenerType.Token: { + return TokenEventsFactory.connect(constants.AddressZero, provider) + .interface; + } + default: { + return null; + } + } + } + + private getInterfaceByExtensionHash( + extensionHash: string, + ): utils.Interface | null { + const provider = this.rpcProvider.getProviderInstance(); + + switch (extensionHash) { + case getExtensionHash(Extension.OneTxPayment): { + return OneTxPaymentEventsFactory.connect( + constants.AddressZero, + provider, + ).interface; + } + case getExtensionHash(Extension.VotingReputation): { + return VotingReputationEventsFactory.connect( + constants.AddressZero, + provider, + ).interface; + } + case getExtensionHash(Extension.MultisigPermissions): { + return MultisigPermissionsEventsFactory.connect( + constants.AddressZero, + provider, + ).interface; + } + case getExtensionHash(Extension.StakedExpenditure): { + return StakedExpenditureEventsFactory.connect( + constants.AddressZero, + provider, + ).interface; + } + case getExtensionHash(Extension.StagedExpenditure): { + return StagedExpenditureEventsFactory.connect( + constants.AddressZero, + provider, + ).interface; + } + case getExtensionHash(Extension.StreamingPayments): { + return StreamingPaymentsEventsFactory.connect( + constants.AddressZero, + provider, + ).interface; + } + default: { + return null; + } + } + } +} diff --git a/packages/blocks/src/events/index.ts b/packages/blocks/src/events/index.ts new file mode 100644 index 000000000..5cbbe874d --- /dev/null +++ b/packages/blocks/src/events/index.ts @@ -0,0 +1,2 @@ +export * from './types'; +export * from './eventManager'; \ No newline at end of file diff --git a/apps/main-chain/src/types/events.ts b/packages/blocks/src/events/types.ts similarity index 77% rename from apps/main-chain/src/types/events.ts rename to packages/blocks/src/events/types.ts index e4c947cf6..33e3e6993 100644 --- a/apps/main-chain/src/types/events.ts +++ b/packages/blocks/src/events/types.ts @@ -1,13 +1,4 @@ -import { - AnyColonyClient, - AnyVotingReputationClient, - ColonyNetworkClient, - TokenClient, -} from '@colony/colony-js'; import { LogDescription } from '@ethersproject/abi'; -import provider from '~provider'; -import { EventListener } from '~eventListeners'; - /* * Custom contract event, since we need some log values as well */ @@ -116,6 +107,7 @@ export enum ContractEventsSignatures { ColonyMetadataDelta = 'ColonyMetadataDelta(address,string)', // Proxy colonies ProxyColonyRequested = 'ProxyColonyRequested(uint256,bytes32)', + ProxyColonyDeployed = 'ProxyColonyDeployed(address)', } /* @@ -126,20 +118,67 @@ export enum EthersObserverEvents { Block = 'block', } -export type ChainID = string; - -export type Block = Awaited>; -export type BlockWithTransactions = Awaited< - ReturnType ->; - -export type NetworkClients = - | ColonyNetworkClient - | TokenClient - | AnyColonyClient - | AnyVotingReputationClient; - export type EventHandler = ( event: ContractEvent, listener: EventListener, ) => Promise; + +export interface BaseEventListener { + type: EventListenerType; + eventSignature: ContractEventsSignatures; + topics: Array; + handler: EventHandler; + address?: string; +} + +export enum EventListenerType { + Colony = 'Colony', + Network = 'Network', + Extension = 'Extension', + Token = 'Token', + MultisigPermissions = 'MultisigPermissions', + ProxyColonies = 'ProxyColonies', +} + +export interface ColonyEventListener extends BaseEventListener { + type: EventListenerType.Colony; + address: string; +} + +export interface NetworkEventListener extends BaseEventListener { + type: EventListenerType.Network; + address: string; +} + +// Special listener just for Token transfers +// Due to the volume of these events, we can't process them in the same way +// as the normal events +export interface TokenTransferEventListener extends BaseEventListener { + type: EventListenerType.Token; +} + +export interface TokenEventListener extends BaseEventListener { + type: EventListenerType.Token; + address: string; +} + +export interface ProxyColoniesListener extends BaseEventListener { + type: EventListenerType.ProxyColonies; + address: string; +} + +export interface ExtensionEventListener extends BaseEventListener { + type: EventListenerType.Extension; + address: string; + colonyAddress: string; + extensionHash: string; + handler: EventHandler; +} + +export type EventListener = + | ColonyEventListener + | NetworkEventListener + | TokenEventListener + | TokenTransferEventListener + | ProxyColoniesListener + | ExtensionEventListener; diff --git a/packages/blocks/src/index.ts b/packages/blocks/src/index.ts new file mode 100644 index 000000000..5676e5a07 --- /dev/null +++ b/packages/blocks/src/index.ts @@ -0,0 +1,3 @@ +export * from './events'; +export * from './stats'; +export * from './blocks'; diff --git a/packages/blocks/src/stats/index.ts b/packages/blocks/src/stats/index.ts new file mode 100644 index 000000000..b4c4c5524 --- /dev/null +++ b/packages/blocks/src/stats/index.ts @@ -0,0 +1,2 @@ +export * from './types'; +export * from './statsManager'; \ No newline at end of file diff --git a/packages/blocks/src/stats/statsManager.ts b/packages/blocks/src/stats/statsManager.ts new file mode 100644 index 000000000..7c90f3499 --- /dev/null +++ b/packages/blocks/src/stats/statsManager.ts @@ -0,0 +1,123 @@ +import { + CreateStatsDocument, + CreateStatsMutation, + CreateStatsMutationVariables, + GetStatsDocument, + GetStatsQuery, + GetStatsQueryVariables, + UpdateStatsDocument, + UpdateStatsMutation, + UpdateStatsMutationVariables, +} from '@joincolony/graphql'; +import { output, verbose } from '@joincolony/utils'; +import { type AmplifyClient, type RpcProvider } from '@joincolony/clients'; +import { ObjectOrFunction } from './types'; + +export class StatsManager { + private stats: Record = {}; + private readonly rpcProvider: RpcProvider; + private readonly amplifyClient: AmplifyClient; + private statsId: string; + + constructor(amplifyClient: AmplifyClient, rpcProvider: RpcProvider) { + this.amplifyClient = amplifyClient; + this.rpcProvider = rpcProvider; + this.statsId = ''; + } + + /** + * Update stats with a given argument. + * Accepts either an object fragment (or full object) to append to stats, + * or a callback (receives current stats) that returns the new object to write back. + */ + public async updateStats(objectOrFunction: ObjectOrFunction): Promise { + if (typeof objectOrFunction === 'function') { + this.stats = { + ...this.stats, + ...objectOrFunction(this.stats), + }; + } else { + this.stats = { + ...this.stats, + ...objectOrFunction, + }; + } + + await this.amplifyClient.mutate< + UpdateStatsMutation, + UpdateStatsMutationVariables + >(UpdateStatsDocument, { + id: this.statsId, + chainId: this.rpcProvider.getChainId(), + value: JSON.stringify(this.stats), + }); + + verbose('Stats file updated'); + } + + // Return a copy of the current stats to avoid accidental overwrites + public getStats(): typeof this.stats { + return { ...this.stats }; + } + + public getLastBlockNumber(): number { + if (Number.isInteger(this.stats.lastBlockNumber)) { + return Number(this.stats.lastBlockNumber); + } + throw new Error('Could not get last block number from stats. Aborting.'); + } + + public setLastBlockNumber(lastBlockNumber: number): void { + this.updateStats({ lastBlockNumber }); + } + + /** + * Fetch the last stored stats from the DB. + * If no stats entry is found, it will create one. + */ + public async initStats(): Promise { + // @TODO need to find a better way for this as something is messed up with the instances + if (!this.rpcProvider.isInitialised) { + output('Force RPC provider initialisation'); + await this.rpcProvider.initialiseProvider(); + } + const { value: jsonStats, id: statsId } = + ( + await this.amplifyClient.query( + GetStatsDocument, + { + chainId: this.rpcProvider.getChainId(), + }, + ) + )?.data?.getIngestorStatsByChainId?.items?.[0] ?? {}; + + if (statsId) { + this.statsId = statsId; + } + + if (!jsonStats) { + this.stats = { lastBlockNumber: 0 }; + + const statsResponse = await this.amplifyClient.mutate< + CreateStatsMutation, + CreateStatsMutationVariables + >(CreateStatsDocument, { + chainId: this.rpcProvider.getChainId(), + value: JSON.stringify(this.stats), + }); + + if (statsResponse?.data?.createIngestorStats?.id) { + this.statsId = statsResponse?.data?.createIngestorStats?.id; + } + + } else { + try { + this.stats = JSON.parse(jsonStats); + } catch { + output( + 'Could not parse stats from the DB. The value is not a valid JSON.', + ); + } + } + } +} diff --git a/packages/blocks/src/stats/types.ts b/packages/blocks/src/stats/types.ts new file mode 100644 index 000000000..750fc9494 --- /dev/null +++ b/packages/blocks/src/stats/types.ts @@ -0,0 +1,3 @@ +export type ObjectOrFunction = + | Record + | ((jsonFile: Record) => Record); \ No newline at end of file diff --git a/packages/blocks/tsconfig.json b/packages/blocks/tsconfig.json new file mode 100644 index 000000000..ea468dfe6 --- /dev/null +++ b/packages/blocks/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": {}, + "include": ["src", "./*.ts"] +} diff --git a/packages/clients/package.json b/packages/clients/package.json new file mode 100644 index 000000000..1506d6627 --- /dev/null +++ b/packages/clients/package.json @@ -0,0 +1,8 @@ +{ + "name": "@joincolony/clients", + "main": "src/index.ts", + "version": "1.0.0", + "dependencies": { + "@joincolony/utils": "workspace:*" + } +} diff --git a/packages/clients/src/amplifyClient.ts b/packages/clients/src/amplifyClient.ts new file mode 100644 index 000000000..3b89cdedd --- /dev/null +++ b/packages/clients/src/amplifyClient.ts @@ -0,0 +1,59 @@ +import { Amplify, API, graphqlOperation } from 'aws-amplify'; +import { GraphQLQuery } from '@aws-amplify/api'; +import { DocumentNode, isExecutableDefinitionNode } from 'graphql'; +import { verbose } from '@joincolony/utils'; + +export type GraphQLFnReturn = Promise< + ReturnType>> | undefined +>; + +export class AmplifyClient { + constructor(appSyncEndpoint: string, appSyncApiKey: string) { + Amplify.configure({ + aws_appsync_graphqlEndpoint: appSyncEndpoint, + aws_appsync_authenticationType: 'API_KEY', + aws_appsync_apiKey: appSyncApiKey, + }); + } + + public async query>( + queryDocument: DocumentNode, + variables?: TVariables, + ): GraphQLFnReturn { + try { + const result = await API.graphql>( + graphqlOperation(queryDocument, variables), + ); + return result; + } catch (error) { + const definitionNode = queryDocument.definitions[0]; + const queryName = isExecutableDefinitionNode(definitionNode) + ? definitionNode.name?.value + : 'Unknown'; + console.error(`Could not fetch query ${queryName}`, error); + return undefined; + } + } + + public async mutate>( + mutationDocument: DocumentNode, + variables?: TVariables, + ): GraphQLFnReturn { + try { + const result = await API.graphql>( + graphqlOperation(mutationDocument, variables), + ); + return result; + } catch (error: any) { + const definitionNode = mutationDocument.definitions[0]; + const name = isExecutableDefinitionNode(definitionNode) + ? definitionNode.name?.value + : 'Unknown'; + + const errMsg = 'errors' in error ? error.errors : error; + verbose(`Could not execute mutation ${name}. Error: `, errMsg); + console.error(`Could not execute mutation ${name}`, error); + return undefined; + } + } +} diff --git a/packages/clients/src/index.ts b/packages/clients/src/index.ts new file mode 100644 index 000000000..a239b1b2d --- /dev/null +++ b/packages/clients/src/index.ts @@ -0,0 +1,4 @@ +export { RpcProvider } from './rpcProvider'; +export * from './amplifyClient'; +export * from './networkClient'; +// @TODO rename clients into providers diff --git a/packages/clients/src/networkClient.ts b/packages/clients/src/networkClient.ts new file mode 100644 index 000000000..ce6d0127c --- /dev/null +++ b/packages/clients/src/networkClient.ts @@ -0,0 +1,23 @@ +import { ColonyNetworkClient, Network, getColonyNetworkClient } from '@colony/colony-js'; + +import { RpcProvider } from './rpcProvider'; + +export class NetworkClient { + private readonly rpcProvider: RpcProvider; + private readonly network: Network; + private readonly networkAddress?: string; + + constructor(rpcProvider: RpcProvider, network: Network, networkAddress?: string) { + this.rpcProvider = rpcProvider; + this.network = network; + this.networkAddress = networkAddress; + } + + // @TODO maybe add here an options object + public getInstance(): ColonyNetworkClient { + return getColonyNetworkClient(this.network, this.rpcProvider.getProviderInstance(), { + networkAddress: this.networkAddress, + disableVersionCheck: true, + }); + } +} \ No newline at end of file diff --git a/packages/clients/src/rpcProvider.ts b/packages/clients/src/rpcProvider.ts new file mode 100644 index 000000000..11377c492 --- /dev/null +++ b/packages/clients/src/rpcProvider.ts @@ -0,0 +1,38 @@ +import { providers } from 'ethers'; +import { ChainID } from './types'; +import { output } from '@joincolony/utils'; + +export class RpcProvider { + public isInitialised = false; + private readonly provider: providers.StaticJsonRpcProvider; + private chainId: ChainID | null; + + constructor(rpcEndpoint?: string) { + this.provider = new providers.StaticJsonRpcProvider(rpcEndpoint); + this.chainId = null; + } + + public async initialiseProvider(): Promise { + const { chainId } = await this.provider.getNetwork(); + this.setChainId(String(chainId)); + this.isInitialised = true; + } + + public setChainId(newChainId: ChainID): void { + this.chainId = newChainId; + } + + public getChainId(): ChainID { + if (!this.chainId) { + output( + 'Chain ID has not been initialized. Call initialiseProvider() first!', + ); + } + // @TODO handle null properly + return this.chainId || 'SOME_DEFAULT_CHAIN_ID'; + } + + public getProviderInstance(): providers.StaticJsonRpcProvider { + return this.provider; + } +} diff --git a/packages/clients/src/types.ts b/packages/clients/src/types.ts new file mode 100644 index 000000000..b5d86141a --- /dev/null +++ b/packages/clients/src/types.ts @@ -0,0 +1 @@ +export type ChainID = string; diff --git a/packages/clients/tsconfig.json b/packages/clients/tsconfig.json new file mode 100644 index 000000000..ea468dfe6 --- /dev/null +++ b/packages/clients/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": {}, + "include": ["src", "./*.ts"] +} diff --git a/packages/graphql/src/generated.ts b/packages/graphql/src/generated.ts index 1caa7af31..aa5c0eb6c 100644 --- a/packages/graphql/src/generated.ts +++ b/packages/graphql/src/generated.ts @@ -1721,6 +1721,7 @@ export type CreateExtensionInstallationsCountInput = { }; export type CreateIngestorStatsInput = { + chainId: Scalars['String']; id?: InputMaybe; value: Scalars['String']; }; @@ -2704,6 +2705,8 @@ export type GetVoterRewardsInput = { /** Model storing block ingestor stats, as key-value entries */ export type IngestorStats = { __typename?: 'IngestorStats'; + /** The chain id the stats are generated on */ + chainId: Scalars['String']; createdAt: Scalars['AWSDateTime']; /** Unique identifier of the ingestor stats */ id: Scalars['ID']; @@ -3756,6 +3759,7 @@ export type ModelIdKeyConditionInput = { export type ModelIngestorStatsConditionInput = { and?: InputMaybe>>; + chainId?: InputMaybe; not?: InputMaybe; or?: InputMaybe>>; value?: InputMaybe; @@ -3769,6 +3773,7 @@ export type ModelIngestorStatsConnection = { export type ModelIngestorStatsFilterInput = { and?: InputMaybe>>; + chainId?: InputMaybe; id?: InputMaybe; not?: InputMaybe; or?: InputMaybe>>; @@ -4654,6 +4659,7 @@ export type ModelSubscriptionIngestorStatsFilterInput = { and?: InputMaybe< Array> >; + chainId?: InputMaybe; id?: InputMaybe; or?: InputMaybe>>; value?: InputMaybe; @@ -6721,6 +6727,7 @@ export type Query = { getExtensionsByHash?: Maybe; getFundsClaimsByColony?: Maybe; getIngestorStats?: Maybe; + getIngestorStatsByChainId?: Maybe; getLiquidationAddress?: Maybe; getLiquidationAddressesByUserAddress?: Maybe; getMotionByExpenditureId?: Maybe; @@ -7178,6 +7185,15 @@ export type QueryGetIngestorStatsArgs = { id: Scalars['ID']; }; +/** Root query type */ +export type QueryGetIngestorStatsByChainIdArgs = { + chainId: Scalars['String']; + filter?: InputMaybe; + limit?: InputMaybe; + nextToken?: InputMaybe; + sortDirection?: InputMaybe; +}; + /** Root query type */ export type QueryGetLiquidationAddressArgs = { id: Scalars['ID']; @@ -9614,6 +9630,7 @@ export type UpdateExtensionInstallationsCountInput = { }; export type UpdateIngestorStatsInput = { + chainId?: InputMaybe; id: Scalars['ID']; value?: InputMaybe; }; @@ -10983,6 +11000,7 @@ export type UpdateUserStakeMutation = { }; export type CreateStatsMutationVariables = Exact<{ + chainId: Scalars['String']; value: Scalars['String']; }>; @@ -10992,6 +11010,8 @@ export type CreateStatsMutation = { }; export type UpdateStatsMutationVariables = Exact<{ + id: Scalars['ID']; + chainId: Scalars['String']; value: Scalars['String']; }>; @@ -12130,11 +12150,20 @@ export type GetUserStakeQuery = { } | null; }; -export type GetStatsQueryVariables = Exact<{ [key: string]: never }>; +export type GetStatsQueryVariables = Exact<{ + chainId: Scalars['String']; +}>; export type GetStatsQuery = { __typename?: 'Query'; - getIngestorStats?: { __typename?: 'IngestorStats'; value: string } | null; + getIngestorStatsByChainId?: { + __typename?: 'ModelIngestorStatsConnection'; + items: Array<{ + __typename?: 'IngestorStats'; + id: string; + value: string; + } | null>; + } | null; }; export type GetTokenFromEverywhereQueryVariables = Exact<{ @@ -12920,15 +12949,15 @@ export const UpdateUserStakeDocument = gql` } `; export const CreateStatsDocument = gql` - mutation CreateStats($value: String!) { - createIngestorStats(input: { id: "STATS", value: $value }) { + mutation CreateStats($chainId: String!, $value: String!) { + createIngestorStats(input: { chainId: $chainId, value: $value }) { id } } `; export const UpdateStatsDocument = gql` - mutation UpdateStats($value: String!) { - updateIngestorStats(input: { id: "STATS", value: $value }) { + mutation UpdateStats($id: ID!, $chainId: String!, $value: String!) { + updateIngestorStats(input: { id: $id, chainId: $chainId, value: $value }) { id } } @@ -13495,9 +13524,12 @@ export const GetUserStakeDocument = gql` } `; export const GetStatsDocument = gql` - query GetStats { - getIngestorStats(id: "STATS") { - value + query GetStats($chainId: String!) { + getIngestorStatsByChainId(chainId: $chainId) { + items { + id + value + } } } `; diff --git a/packages/graphql/src/mutations/stats.graphql b/packages/graphql/src/mutations/stats.graphql index f838e8c99..d22c0791b 100644 --- a/packages/graphql/src/mutations/stats.graphql +++ b/packages/graphql/src/mutations/stats.graphql @@ -1,11 +1,11 @@ -mutation CreateStats($value: String!) { - createIngestorStats(input: { id: "STATS", value: $value }) { +mutation CreateStats($chainId: String!, $value: String!) { + createIngestorStats(input: { chainId: $chainId, value: $value }) { id } } -mutation UpdateStats($value: String!) { - updateIngestorStats(input: { id: "STATS", value: $value }) { +mutation UpdateStats($id: ID!, $chainId: String!, $value: String!) { + updateIngestorStats(input: { id: $id, chainId: $chainId, value: $value }) { id } } diff --git a/packages/graphql/src/queries/stats.graphql b/packages/graphql/src/queries/stats.graphql index c38fcd271..8d16ed159 100644 --- a/packages/graphql/src/queries/stats.graphql +++ b/packages/graphql/src/queries/stats.graphql @@ -1,5 +1,8 @@ -query GetStats { - getIngestorStats(id: "STATS") { - value +query GetStats($chainId: String!) { + getIngestorStatsByChainId(chainId: $chainId) { + items { + id + value + } } } diff --git a/packages/utils/package.json b/packages/utils/package.json new file mode 100644 index 000000000..3180505e1 --- /dev/null +++ b/packages/utils/package.json @@ -0,0 +1,6 @@ +{ + "name": "@joincolony/utils", + "main": "src/index.ts", + "version": "1.0.0", + "dependencies": {} +} diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts new file mode 100644 index 000000000..1ff09efd4 --- /dev/null +++ b/packages/utils/src/index.ts @@ -0,0 +1 @@ +export * from './logger'; diff --git a/apps/main-chain/src/utils/logger.ts b/packages/utils/src/logger.ts similarity index 100% rename from apps/main-chain/src/utils/logger.ts rename to packages/utils/src/logger.ts diff --git a/packages/utils/tsconfig.json b/packages/utils/tsconfig.json new file mode 100644 index 000000000..ea468dfe6 --- /dev/null +++ b/packages/utils/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": {}, + "include": ["src", "./*.ts"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 861f00624..d9c6cda79 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -111,12 +111,56 @@ importers: apps/main-chain: dependencies: + '@joincolony/blocks': + specifier: workspace:* + version: link:../../packages/blocks + '@joincolony/clients': + specifier: workspace:* + version: link:../../packages/clients '@joincolony/graphql': specifier: workspace:* version: link:../../packages/graphql + '@joincolony/utils': + specifier: workspace:* + version: link:../../packages/utils + + apps/proxy-chain: + dependencies: + '@joincolony/blocks': + specifier: workspace:^ + version: link:../../packages/blocks + '@joincolony/clients': + specifier: workspace:^ + version: link:../../packages/clients + '@joincolony/graphql': + specifier: workspace:* + version: link:../../packages/graphql + '@joincolony/utils': + specifier: workspace:^ + version: link:../../packages/utils + + packages/blocks: + dependencies: + '@joincolony/clients': + specifier: workspace:* + version: link:../clients + '@joincolony/graphql': + specifier: workspace:* + version: link:../graphql + '@joincolony/utils': + specifier: workspace:* + version: link:../utils + + packages/clients: + dependencies: + '@joincolony/utils': + specifier: workspace:* + version: link:../utils packages/graphql: {} + packages/utils: {} + packages: '@ably/msgpack-js@0.4.0':